简体   繁体   中英

Multiple returns from jQuery AJAX post

Let me quickly explain what I do, I have multiple jQuery AJAX post which are returing different results. Here is what I'm doing at the moment:

JavaScript

$("select#be_betrieb")
  .change(function() {

    $.ajax({
      type: "POST",
      url: "/functions/antragsformulare_benutzer.inc.php",
      data: { action: "getkst", bkuerzel: $(this).val() },
      success: function(data) {
        $("select#be_kostenstelle").attr('disabled',false);             
        $("select#be_kostenstelle").html(data);
      }
    });

    $.ajax({
      type: "POST",
      url: "/functions/antragsformulare_benutzer.inc.php",
      data: { action: "getcompnames", bkuerzel: $("select#be_betrieb").val() },
      success: function(data) {             
        $("select#be_arbeitsplatzbestehend").html(data);
      }
    });
  });

As you can see, I do a post to the same PHP file twice, just with a different action defined. Since I have several other posts to do to this file (about 6) I was wondering if there is an other way to do that?

I hope you guys understand my question. I'm looking forward to your input.

based on your inputs I changed my code, can you may have an other look if that is good?

Javascript

$("select#be_betrieb")
        .change(function() {

            $.ajax({
                type: "POST",
                url: "/functions/antragsformulare_benutzer.inc.php",
                dataType: "json",
                data: 
                    { 
                        actions: [
                                    {action: "getkst", bkuerzel: $(this).val()},
                                    {action: "getcompnames", bkuerzel: $(this).val()}
                                 ]
                    },
                success: function(data)
                    {
                        for (var i = 0; i<data.length; i++)
                        {
                            switch(data[i]["action"])
                            {
                                case "getkst":
                                    alert(data[i]["queryresult"]);
                                    break;

                                case "getcompnames":
                                    alert(data[i]["queryresult"]);
                                    break;
                            }
                        }
                    }
            });

PHP

if ( $_POST['actions'] != "" )
{
foreach ($_POST['actions'] as $action)
{
    switch ($action['action'])
    {
        case "getkst":

            $queryresult = "here something to return";

            $results[] = array('action' => 'getkst', 'queryresult' => $queryresult);
            break;

        case "getcompnames":

            $queryresult = "here something to return";

            $results[] = array('action' => 'getcompnames', 'queryresult' => $queryresult);
            break;
    }
}

echo json_encode($results);
}

Thanks a lot so far!

Once you are sending all of those requests one by one, to the same page, I think it would be better to do something like this:

$.ajax({
      type: "POST",
      url: "/functions/antragsformulare_benutzer.inc.php",
      dataType:'json',
      data: {actions: [{action: "getkst", bkuerzel: $(this).val()},
                       {action: "getcompnames", bkuerzel: $("select#be_betrieb").val()},
                       ...] },
      success: function(data) {
        for(var i = 0;i<data.length;i++) {
            switch(data[i]["action"]) {
                case "getkst":
                    $("select#be_kostenstelle").attr('disabled',false);             
                    $("select#be_kostenstelle").html(data[i].resultHTML);
                    break;
                case "getcompnames":
                    $("select#be_arbeitsplatzbestehend").html(data[i].resultHTML);
                    break;
            }
        }
      }
    });

And in your /functions/antragsformulare_benutzer.inc.php return array of results encoded with json_encode .

dataType:'json' this will let jQuery know that it should handle response like JSON, so data will contain regular JS object.

Reasons:

  • one request leading to lower load on server (no need to initialize environment for 6 request)
  • faster (each request require some time to connect to server, also there could be a problem with session lock: once you are using default session all requests will be used one by one, waiting for previouse request to be finished)

Basic idea is to push all actions and its values with one AJAX request. Than, on server, iterate through $_POST['actions'] and execute what you need for each action. Collect results into PHP array like this:

 $results = array(array("action" => 'action1', 
                        "results" => "some action results"), 
                  array("action" => 'action2', 
                        "results" => "some action results"),
                  ...);

and than encode that array with json_encode, so jQuery can parse it:

echo json_encode($results);

you may use a library that does that automatically for you, even chaining AJAX responses when it's done, but instead of doing it client side, you call the ajax functions from the server side. using phery library ( http://phery-php-ajax.net ) you can do it all from the server:

<select data-remote="getkst" name="bkuerzel" data-target="/functions/antragsformulare_benutzer.inc.php">
   // fill your options here
</select>

in your antragsformulare_benutzer.inc.php file

function getcompnames($data){
  $r = new PheryResponse;  
  // get your comp names here. If you are appending to a select, use
  $r->jquery('select#be_arbeitsplatzbestehend')->html($html_content);
  return $r;
}

function getkst($data){
  $r = new PheryResponse; 
  $html_content = set_your_html_content();

  $r
  ->jquery('select#select#be_kostenstelle')
  ->removeAttr('disabled')->html($html_content);
  // you could do
  // $r->phery_remote('getcompnames', array('bkuerzel' => $data['bkuerzel']), array('target' => '/functions/antragsformulare_benutzer.inc.php'));
  // to call a second ajax when this one is completed, but it's best to merge the response from getcompnames and keep it all in one single AJAX call
  return $r->merge(getcompnames());
}

Phery::instance()->set(array(
  'getkst' => 'getkst',
  'getcompnames' => 'getcompnames'
))->process();

As you can see, you can either call a second AJAX response, or merge the both answers, which I think it's the best bet for you, and save one AJAX call ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM