javascript - How can I "read" a response from the php file I call here using ajax? - Stack Overflow

I am very new to ajax and jquery, but I came across a code on the web which I am manipulating to suit m

I am very new to ajax and jquery, but I came across a code on the web which I am manipulating to suit my needs.

The only problem is that I want to be able to respond to the ajax from PHP.

This ajax POSTS to a php page (email.php).

How can I make the email.php reply back if the message is sent or if message-limit is exceeded (I limit the nr of messages sent per each user)?

In other words, I want ajax to take a 1 or 0 from the php code, and for example:

  if(response==1){ alert("message sent"); } else { alert("Limit exceeded"); }

Here is the last part of the code: (If you need the full code just let me know)

var data_string = $('form#ajax_form').serialize();

$.ajax({
    type:       "POST",
    url:        "email.php",
    data:       data_string,
    success:    function() {

    $('form#ajax_form').slideUp('slow').before('');
    $('#success').html('<h3>Success</h3>Your email is has been sent.');
    }//end success function
}) //end ajax call

 return false;

 })

Thanks

I am very new to ajax and jquery, but I came across a code on the web which I am manipulating to suit my needs.

The only problem is that I want to be able to respond to the ajax from PHP.

This ajax POSTS to a php page (email.php).

How can I make the email.php reply back if the message is sent or if message-limit is exceeded (I limit the nr of messages sent per each user)?

In other words, I want ajax to take a 1 or 0 from the php code, and for example:

  if(response==1){ alert("message sent"); } else { alert("Limit exceeded"); }

Here is the last part of the code: (If you need the full code just let me know)

var data_string = $('form#ajax_form').serialize();

$.ajax({
    type:       "POST",
    url:        "email.php",
    data:       data_string,
    success:    function() {

    $('form#ajax_form').slideUp('slow').before('');
    $('#success').html('<h3>Success</h3>Your email is has been sent.');
    }//end success function
}) //end ajax call

 return false;

 })

Thanks

Share Improve this question asked Nov 22, 2010 at 15:03 user188962user188962
Add a ment  | 

6 Answers 6

Reset to default 6

The success function of an $.ajax call receives a parameter, usually called data though that's up to you, containing the response, so:

success: function(data) {
    // Use the data
}

(It also receives a couple of other parameters if you want them; more in the docs.)

The data parameter's type will vary depending on the content type of the response your PHP page sends. If it sends HTML, data will be a string containing the HTML markup; if your page sends JSON, the data parameter will be the decoded JSON object; if it's XML, data will be an XML document instance.

You can use 1 or 0 if you like (if you do, I'd probably set the content type to "text/plain"), so:

success: function(data) {
    if (data === "1") {
        // success
    }
    else if (data === "0") {
        // failure
    }
    else {
        // App error, expected "0" or "1"
    }
 }

...but when I'm responding to Ajax requests, nine times out of ten I send JSON back (so I set the Content-Type header to application/json), because then if I'm using a library like jQuery that understands JSON, I'll get back a nice orderly object that's easy to work with. I'm not a PHP guy, but I believe you'd set the content type via setContentType and use json_encode to encode the data to send back.

In your case, I'd probably reply with:

{"success": "true"}

or

{"success": "false", "errMessage": "You reached the limit."}

so that the server-side code can dictate what error message I show the user. Then your success function would look like this:

success: function(data) {
    var msg;

    if (typeof data !== "object") {
        // Strange, we should have gotten back an object
        msg = "Application error";
    }
    else if (!data.success) {
        // `success` is false or missing, grab the error message
        // or a fallback if it's missing
        msg = data.errMessage || "Request failed, no error given";
    }
    if (msg) {
        // Show the message -- you can use `alert` or whatever
    }
}

You must pass an argument to your "success" function.

success: function(data)
{
    if(data == '1')
    {
        $('form#ajax_form').slideUp('slow').before('');
        $('#success').html('<h3>Success</h3>Your email is has been sent.');
    }
}

And in your php file, you should just echo the response you need

if(mail())
{
    echo '1';
}
else
{
    echo '0';
}

Anything you echo or return in the php file will be sent back to you jquery post. You should check out this page http://api.jquery./jQuery.post/ and think about using JSON formatted variables to return so like if you had this in your email script:

echo '{ "reposonse": "1" }';

This pass a variable called response with a value of 1 back to you jquery script. You could then use an if statement how you described.

just have email.php echo a 0 or 1, and then grab the data in the success event of the ajax object as follows...

$.ajax({
  url: 'email.php',
  success: function(data) {
    if (data=="1"){
        ...
    }else{
        ...
    }
  }
});

what you do is, you let your ajax file (email.php) print a 1 if successful and a 0 if not (or whatever else you want)

Then, in your success function, you do something like this:

function(data) {

$('form#ajax_form').slideUp('slow').before('');
if(data==1){ alert("message sent"); } else { alert("Limit exceeded"); }
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}

So you capture the response in the data var of the function. If you a bigger variety in your output, you can set you dataType to "json" and have your php file print a json_encoded string so that you can access your different variables in your response via for example data.success etc.

PHP can only return to AJAX calls, by its output. An AJAX call to a PHP page is essentially the same as a browser requesting for the page.

If your PHP file was something like,

<?php
echo "1";
?>

You would receive the "1" in your JavaScript success callback,

that is,

success: function(data) {
   // here data is "1"
}

As an added note, usually AJAX responses are usually done in JSON format. Therefore, you should format your PHP replies in JSON notation.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744159534a4561026.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信