0

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!

3
  • 5
    Have the php return a json array containing objects representing your six rows, then have jQuery accept a json answer. Commented Apr 5, 2018 at 15:03
  • 1
    When we make AJAX requests we typically are doing so to retrieve only the data required on the page. It sounds like you are taking the approach of sending back a complete HTML file. As Federico says, you can simply echo the json_encoded() data and then deal with the data in the browser using JS and jQuery. Commented Apr 5, 2018 at 15:09
  • Everything you get from the server is basically just a bunch of chars. However you couod use markup languages like JSON or YAML to sent ordered data. Commented Apr 5, 2018 at 15:10

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the thorough explanation! I should have said I am very familiair with PHP but owh well, thanks anyway. I have a question though, is it possible to save the values into an array or something and then push it into the already existing HTML?
Yes, you can save the object return. And you can use anything in that object anywhere in your html document. If you have specifics, I could add some examples.
Thanks you so much for the help, very well explained! I got it to work after some messing around with javascript objects... Thanks again! Well deserved answer :D
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.