最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make a submit button POST and AJAX call same time? - Stack Overflow

programmeradmin0浏览0评论

I have this form that will POST to show_aht2.php but I also want it to make the AJAX call that you see in my code below. So, how can I do both so the user doesn't go to the other? I want the user to stay on map.php

thanks in advance

map.php

    <form action="show_aht2.php" method="post">
           <input type="radio" name="date_selected" value="1d" checked="checked"/>1d
           <input type="radio" name="date_selected" value="1w" />1w
           <input type="radio" name="date_selected" value="1m" />1m
           <input type="radio" name="date_selected" value="3m" />3m
           <input type="submit" id="aht_btn" name="get_aht" value="Get AHT" />
    </form>


<script type="text/javascript">
        $(document).ready(function() {
                $('#aht_btn').click(function(){
                    $.ajax({
                    type:"GET",
                    url : "show_aht2.php",
                    data:{ } , // do I need to pass data if im GET ting?
                    dataType: 'json',
                    success : function(data){
                       //doing stuff
                        //get the MIN value from the array
                            var min = data.reduce(function(prev, curr) {
                                return isNaN(+curr['aht_value']) || prev < +curr['aht_value'] ? prev : +curr['aht_value'];
                            }, 1000000);

                        //  alert("min:" + min); //return min for debug

                            //get the MAX value from the array
                            var max = data.reduce(function(prev, curr) {
                              return isNaN(+curr['aht_value']) || prev > +curr['aht_value'] ? prev : +curr['aht_value'];
                            }, -1000000); 

                            //alert("max:" + max); //return max number for debug

                            //function for calculation of background color depending on aht_value               
                            function conv(x){
                                return Math.floor((x - min) / (max - min) * 255);
                            }

                            //function for background color
                            //if NA then show white background, either show from green to red
                            function colorMe(v){
                              return v == 'NA' ? "#FFF" : "rgb(" + conv(v) + "," + (255-conv(v)) + ",0)";
                            }

                        //going through all DIVs only once with this loop
                        for(var i = 0; i < data.length; i++) { // loop over results
                        var divForResult = $('#desk_' + data[i]['station']); // look for div for this object
                        if(divForResult.length) { // if a div was found
                            divForResult.html(data[i]['aht_value']).css("background-color", colorMe(data[i]['aht_value']));
                        //  alert("station " + data[i]['station'] + " <br>aht value" + data[i]['aht_value'] + "<br>timestamp:"+data[i]['ts_generated']);
                        }//end if
                        }//end for  
                    }//end success
                });//end ajax   
              });//end click
            });//end rdy
        </script>

show_aht2.php

    if (isset($_POST['get_aht'])) {
    if($_POST['date_selected'] == "1d" )//yesterdays result  and using past 10 minute
    {
        $start_date = $one_day;
        //$interval_value = "10 MINUTE";
        //echo $start_date;
    }
    elseif($_POST['date_selected'] == "1w" )//1 week results
    {
        $start_date = $one_week;
        //$interval_value =  "7 DAY";
        //echo $start_date;
    }
    elseif($_POST['date_selected'] == "1m" )//1 month results
    {
        $start_date = $one_month;
        //$interval_value =  "30 DAY";
        //echo $start_date;
    }
    elseif($_POST['date_selected'] == "3m" )//3 month results
    {
        $start_date = $three_month;
        //$interval_value =  "90 DAY";
        //echo $start_date;
    }
}


/* what I expect from ther call back*/
$result = array();
    foreach ($memo as $username => $memodata) {
    if (in_array($username, array_keys($user))) {
    // Match username against the keys of $user (the usernames) 
    $userdata = $user[$username];
    //if AHT is null give N/A as value
    if (is_null($memodata['aht_value'])) {
        $result[] = array( 'username'  => $userdata['username'],
                                             'aht_value' => 'NA',
                                             'station'  => $userdata['station']//,
                                            // "ts_generated" =>  $userdata['ts_generated'] 
                                            );
    }//end inner if 
    //else give the actual value of AHT without the decimals
    else {
        $result[] = array( 'username'  => $userdata['username'],
                                             'aht_value' => substr($memodata['aht_value'],0,-3),
                                             'station'   => $userdata['station']//,
                                        //   "ts_generated" =>  $userdata['ts_generated']   
                                        );
    }//end else
    }//end outer if
    }//end for

echo json_encode($result);

I have this form that will POST to show_aht2.php but I also want it to make the AJAX call that you see in my code below. So, how can I do both so the user doesn't go to the other? I want the user to stay on map.php

thanks in advance

map.php

    <form action="show_aht2.php" method="post">
           <input type="radio" name="date_selected" value="1d" checked="checked"/>1d
           <input type="radio" name="date_selected" value="1w" />1w
           <input type="radio" name="date_selected" value="1m" />1m
           <input type="radio" name="date_selected" value="3m" />3m
           <input type="submit" id="aht_btn" name="get_aht" value="Get AHT" />
    </form>


<script type="text/javascript">
        $(document).ready(function() {
                $('#aht_btn').click(function(){
                    $.ajax({
                    type:"GET",
                    url : "show_aht2.php",
                    data:{ } , // do I need to pass data if im GET ting?
                    dataType: 'json',
                    success : function(data){
                       //doing stuff
                        //get the MIN value from the array
                            var min = data.reduce(function(prev, curr) {
                                return isNaN(+curr['aht_value']) || prev < +curr['aht_value'] ? prev : +curr['aht_value'];
                            }, 1000000);

                        //  alert("min:" + min); //return min for debug

                            //get the MAX value from the array
                            var max = data.reduce(function(prev, curr) {
                              return isNaN(+curr['aht_value']) || prev > +curr['aht_value'] ? prev : +curr['aht_value'];
                            }, -1000000); 

                            //alert("max:" + max); //return max number for debug

                            //function for calculation of background color depending on aht_value               
                            function conv(x){
                                return Math.floor((x - min) / (max - min) * 255);
                            }

                            //function for background color
                            //if NA then show white background, either show from green to red
                            function colorMe(v){
                              return v == 'NA' ? "#FFF" : "rgb(" + conv(v) + "," + (255-conv(v)) + ",0)";
                            }

                        //going through all DIVs only once with this loop
                        for(var i = 0; i < data.length; i++) { // loop over results
                        var divForResult = $('#desk_' + data[i]['station']); // look for div for this object
                        if(divForResult.length) { // if a div was found
                            divForResult.html(data[i]['aht_value']).css("background-color", colorMe(data[i]['aht_value']));
                        //  alert("station " + data[i]['station'] + " <br>aht value" + data[i]['aht_value'] + "<br>timestamp:"+data[i]['ts_generated']);
                        }//end if
                        }//end for  
                    }//end success
                });//end ajax   
              });//end click
            });//end rdy
        </script>

show_aht2.php

    if (isset($_POST['get_aht'])) {
    if($_POST['date_selected'] == "1d" )//yesterdays result  and using past 10 minute
    {
        $start_date = $one_day;
        //$interval_value = "10 MINUTE";
        //echo $start_date;
    }
    elseif($_POST['date_selected'] == "1w" )//1 week results
    {
        $start_date = $one_week;
        //$interval_value =  "7 DAY";
        //echo $start_date;
    }
    elseif($_POST['date_selected'] == "1m" )//1 month results
    {
        $start_date = $one_month;
        //$interval_value =  "30 DAY";
        //echo $start_date;
    }
    elseif($_POST['date_selected'] == "3m" )//3 month results
    {
        $start_date = $three_month;
        //$interval_value =  "90 DAY";
        //echo $start_date;
    }
}


/* what I expect from ther call back*/
$result = array();
    foreach ($memo as $username => $memodata) {
    if (in_array($username, array_keys($user))) {
    // Match username against the keys of $user (the usernames) 
    $userdata = $user[$username];
    //if AHT is null give N/A as value
    if (is_null($memodata['aht_value'])) {
        $result[] = array( 'username'  => $userdata['username'],
                                             'aht_value' => 'NA',
                                             'station'  => $userdata['station']//,
                                            // "ts_generated" =>  $userdata['ts_generated'] 
                                            );
    }//end inner if 
    //else give the actual value of AHT without the decimals
    else {
        $result[] = array( 'username'  => $userdata['username'],
                                             'aht_value' => substr($memodata['aht_value'],0,-3),
                                             'station'   => $userdata['station']//,
                                        //   "ts_generated" =>  $userdata['ts_generated']   
                                        );
    }//end else
    }//end outer if
    }//end for

echo json_encode($result);
Share Improve this question edited Nov 26, 2014 at 21:44 alda1234 asked Nov 26, 2014 at 21:12 alda1234alda1234 2041 gold badge4 silver badges15 bronze badges 7
  • Make the button type="button" so it won't submit the form. – marekful Commented Nov 26, 2014 at 21:15
  • @DavidNguyen my show_aht2.php script is querying multiple tables and returning values from it on map.php – alda1234 Commented Nov 26, 2014 at 21:17
  • You can't do both a normal submit and Ajax at once. Choose one or the other. You also can't do POST and GET at the same time. Choose one or the other. – developerwjk Commented Nov 26, 2014 at 21:29
  • @developerwjk well, not at the same time. but he could do a POST with callback and then submit the form. – low_rents Commented Nov 26, 2014 at 21:37
  • @northkildonan, True, but its pletely unclear what he's trying to do since there's nothing in the success method of the ajax call. We've got a GET that gets nothing, but supposedly expects Json from a PHP page that only handles POST. Clear as mud what the goal is here. – developerwjk Commented Nov 26, 2014 at 21:42
 |  Show 2 more ments

3 Answers 3

Reset to default 5

do ajax call first, then submit form with .submit() later with callback of ajax.

<form action="show_aht2.php" method="post" id="formtopost">

<script type="text/javascript">
    $(document).ready(function() {
        $('#aht_btn').click(function() {
            $.ajax({
                type: "GET",
                url: "show_aht2.php",
                data: {}, // do I need to pass data if im GET ting?
                dataType: 'json',
                success: function(data) {
                    //doing stuff
                    //end success
                },
                always: function() {
                    //submit form !!!
                    $("#formtopost").submit();
                }
            }); //end ajax   
        }); //end click
    }); //end rdy
</script>

Try :

<script type="text/javascript">
    $(document).ready(function() {
            $('#aht_btn').click(function(event){
                event.preventDefault();
                $.ajax({
                type:"GET",
                url : "show_aht2.php",
                data:{ } , // do I need to pass data if im GET ting?
                dataType: 'json',
                success : function(data){
                   //doing stuff
                }//end success
            });//end ajax   
          });//end click
        });//end rdy
    </script>

Use method preventDefault : http://api.jquery./event.preventdefault/

You could submit the form with ajax rather than trying to do both at the same time

Something like this maybe?

<script type="text/javascript">
    $(document).ready(function() {
        $('#aht_btn').click(function(){

            // This prevents the form from submitting
            event.preventDefault();

            // Capture form input
            var $form = $(this);
            var serializedData = $form.serialize();

            // Run the ajax post
            $.ajax({
                url : "show_aht2.php",
                type:"POST",
                data: serializedData
                success: function(response) {
                    // Do something
                }
            });

          });//end click
        });//end rdy
</script>
发布评论

评论列表(0)

  1. 暂无评论