Tom
Tom

Reputation: 12998

Populate alert message from ajax call

I'm trying to populate an element after an ajax call is made, but I'm not too sure whether this is the right way to do it and if it is, where I'm going wrong.

Here's my code...

$(document).ready( function() {
    $("#edit_delete").click(function() {
        $.post('mySelect.php', $("#edit_delete").serialize(), function(result) {
            $('#message1').html(<?php echo $myTest; ?>);
            $('#message2').html(<?php echo $myOtherTest; ?>);
        });
    }   
});

mySelect.php :

<?php include '../../includes/connection.php' ?>
<?php
    $selected_user = $_POST["users"];
    $result = mysql_query("SELECT * FROM users WHERE id = $selected_user");
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
?>
<?php $myTest = $row['id']; ?>
<?php $myOtherTest = $row['name']; ?>
<?php mysql_close($con); ?>

(Let me know if you need more info and please feel free to edit my question so it makes sense!)

Upvotes: 1

Views: 1042

Answers (5)

Dario
Dario

Reputation: 23

In my opinion you should avoid the use of php in the callback of the $.post function. You can do all that you want using ajax.

Javascript code:

$(document).ready( function() {
    $("#edit_delete").click(function() {
    $.ajax({
            type: "POST",
            url: "mySelect.php",   
            data: 'users='+$("#edit_delete").serialize(),
            success: function(data) {
            var result = $.parseJSON(data);    
                $('#message1').html(result.id);
                $('#message2').html(result.name);
            }
       });          
    }   
});

PHP Code:

<?php 
include '../../includes/connection.php';

$selected_user = $_POST["users"];
$result = mysql_query("SELECT * FROM users WHERE id = $selected_user");
$row = mysql_fetch_array($result, MYSQL_ASSOC);

$return = array(
'id' => $row['id'],
'name' => $row['name']
);

mysql_close($con);

echo json_encode($return);
?>

Try to avoid to open and close the php tag in each line. It's enough with one at begginning of the fila and one at the end of it.

Sorry my bad english.

Good luck

Upvotes: 1

Jeff Lambert
Jeff Lambert

Reputation: 24661

After you make the AJAX call, the entire output of the PHP script is placed (in your case) inside of the 'results' parameter of your callback.

This means if you echo 'Hello!'; in your mySelect.php, then results will contain the string 'Hello!'.

If you want to alert the results, then all you have to do is: alert(results); inside your callback.

As a couple others have pointed out, you can also look at using json_encoded arrays to help you make better use of the data you're sending back from the server.

Upvotes: 3

Andy
Andy

Reputation: 2140

You should look at the jQuery manual

There is an example of using JSON

$.post("test.php", { "func": "getNameAndTime" },
 function(data){
   console.log(data.name); // John
   console.log(data.time); //  2pm
 }, "json");

In the code you give about the Javascript variable result will be populated by whatever you echo out.

Upvotes: 0

Menztrual
Menztrual

Reputation: 41597

The way results works is it sends the entire output of the application. So the variables won't work as intended.

Instead, what you would want to do is echo json_encode (javascript object notation ) by like:

<?php
  echo json_encode(array('myTest' => $row['id'], 'myOtherTest' => $row['name']));
?>

Then you can call it through:

results.myTest from the ajax call back

Upvotes: 1

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

No, you should echo your data back to the client and then use it

<?php include '../../includes/connection.php' ?>
<?php
    $selected_user = $_POST["users"];
    $result = mysql_query("SELECT * FROM users WHERE id = $selected_user");
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
//prepare an array to return
$return = array();
$return['id'] = $row['id']; 
$return['name'] = $row['name']; 
//set the header
header('application/json');
//encode it and echo it back
echo json_encode($return);

And then

   $.post('mySelect.php', $("#edit_delete").serialize(), function(result) {
        $('#message1').html(result.id);
        $('#message2').html(result.name);
    });

You do this because you are making an asynchronous call to the server: you don't reload your page, you just make a call and get some data back

Upvotes: 1

Related Questions