2

I am fairly new to Javascript, and Ajax in particular so bear with me...

I want to have a table updated after inserting a new row, but instead of having the Ajax output an html table all together, I'd much prefer to collect all the data from the PHP mysql and insert it into a pre-existing table with a loop.

This is how I would usually do it using PHP and a while() function so that I can insert various parts of data using an array. For eg "$mem['Name']"

    $mems = mysql_query($sql,$con);
    while($mem=mysql_fetch_array($mems)){
                $lmc++;


                            echo '<tr class="data">';
                                echo '<td class="index">'.$lmc.'</td>';          
                                echo '<td class="name">'.$mem['Name'].'</td>';
                                echo '<td class="arcid">'.$mem['ArcID'].'</td>';
                                echo '<td class="type">'.$mem['Type'].'</td>';
                                echo '<td class="role">';
                                echo '<input style="width:100%;" type="text" name="art_realname" id="art_realname" class="field" value="'.$mem['Role'].'"   tabindex="1" />';
                                echo '</td>';
                            echo '</tr>';
                        };

Is there any way of using AJAX so that I can firstly collect all the data in the PHP file and put it in an array, then secondly send it back to the AJAX, and then finally do the loop section using Javascript on the actually page and insert it into the tables there?

1 Answer 1

1

This solution requires jQuery, but you are free to use any JS framwork/lib.

Also, you should know that using the mysql_* functions is a bad idea as they are going to be deprecated soon.

Now, let's assume you have a script named ajax.php on your server. You should go about querying your database in the same way as always, but instead of echoing it - put in a variable.

<?php
/* your script here */
$data = ... /* data your query returned */

header ("Content-Type: application/json" );
echo json_encode ($data);
?>

Then on the client side:

$.getJSON ( "ajax.php", function (data) {
   /* data is the $data from your PHP script */
});

You are not an idiot :)

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, thank you very much for your quick and helpful response. Could I just check one thing though... Say if I had in PHP $data['row1'], would the equivalent in Jquery, after having done as you have shown above, be data.row1? Cheers, George

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.