简体   繁体   中英

Retrieve multiple variables from an AJAX call to jQuery

I have a PHP file that requests six rows from a database. I'm using an ajax call.

I want these six rows (multiple columns) to be passed through to my main file. I was unable to find a way to get these values to my main page except for posting them in html in the request file and posting this as a table on my main page.

I don't want them on the page in a plain table for everyone to be seen.

So not like this:

success: function(html) {
    $("#display").html(html).show();
}

I always need six rows at the moment but could be more later on.

One of the ideas that I had was posting it as one long string and loading this into a variable, and then reading using explode or something a-like. Not sure if this is a good way to do this...

I am basically asking for ideas to expand my horizon.

I am still learning JavaScript and jQuery so I'd rather have a good explanation than a block of working code.

Thanks in advance!

PHP Side

This is a very simple process, which you may kick yourself after grasping ;) But once you do, it opens a world of possibilities and your mind will go crazy with ideas.

The first stage is you want to adjust your data that you will be returning to the ajax call. If you have a few rows of a few fields, you would do have something along these lines (could come from db, or assignments, whatever):

$rows = [];
$rows[] = array('thing'=>'value 1','something'=>'blah','tertiary'=>'yup');
$rows[] = array('thing'=>'value 2','something'=>'yadda','tertiary'=>'no');
$rows[] = array('thing'=>'value 3','something'=>'woop','tertiary'=>'maybe');

Now, to get this rows of data out to ajax, you do this one simple operation:

echo json_encode($rows);
exit; // important to not spew ANY other html

Thats all you really need to do on the PHP side of things. So what did we do? Well, we took a multidimensional array of data (usually representing what comes from a database), and encoded it in JSON format and returned it. The above will look like this to your browser:

[{"thing":"value 1","something":"blah","tertiary":"yup"},
 {"thing":"value 2","something":"yadda","tertiary":"no"},
 {"thing":"value 3","something":"woop","tertiary":"maybe"}]

It will have handled all escaping, and encoding of utf8 and other special characters. The joys of json_encode() !

JAVASCRIPT Side

This side is not as difficult, but theres some things to understand. FIrst off, lets get your jquery ajax call into shape:

<div id="rows"></div>
<script>
$("#your-trigger").on('click',function(e){
    e.preventDefault(); // just stops the click from doing anything else
    $.ajax({
       type: "POST",
       url: 'your_ajax.php',
       data: { varname: 'value', numrows: '6' },// your sent $_POST vars
       success: function(obj) {
           // loop on the obj return rows
           for(var i = 0; i < obj.length; i++) {
               // build a div row and append to #rows container
               var row = $('<div></div>');
                   row.append('<span class="thing">'+ obj[i].thing +'</span>'); 
                   row.append('<span class="details">'+  
                                   obj[i].something +' '+ obj[i].tertiary
                               +'</span>');
               $("#rows").append(row);
           }
       },
       dataType: 'json' // important!
    });
});
</script>

So lets explain a few key points.

The most important is the dataType: 'json' . This tells your ajax call to EXPECT a json string to turn into an object. This object becomes what you define in the success function arg (which I named obj above).

Now, to access each specific data variable of each row, you treat it as an object. Array of rows, each row has vars named as you named them in PHP. This is where I have the for example to loop through the array of rows.

For example obj[0].thing refers to the first row of variable thing . The use of i lets you just go through all rows automatically based on length of the object. A few handy things in there.

You can build any html you wish from the returned object and values. I just showed how to setup a <div><span class="thing"></span><span class="details"></span></div> example row. You may want to use tables, or more complex setups and code.


To keep the return data from your ajax call, you can store it in a local or global variable like so:

<script>
var globalvar;
$....('click',function(e){
    var localvar;
    $.ajax(.... success: function(obj){
        ....
        localvar = obj;
        globalvar = obj;
        ....
    });
});
</script>

Do what Frederico says above. Return json from your php and get in in jQuery using ajax call. Something like this: http://makitweb.com/return-json-response-ajax-using-jquery-php/ . Just skip step #3 and do what you need with received data in step #5 if you don't need it to be printed to html.

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