Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Alert the returned data of ajax?

Tags:

jquery

php

I have a jQuery page with AJAX, and is submitted in a separate PHP file that has no UI. so what i want is if say for example an insert query in my PHP file will fail, an echo(your insert failed) in my PHP will be alerted in my jQuery page. how to do that?

something like this alert(data);

like image 660
user628961 Avatar asked Mar 11 '11 11:03

user628961


1 Answers

EDIT 2:

Alerting anything that PHP echos:

function get_data() {
    $.ajax({
        url: 'get_data.php?rand=' + Math.random(),
        type: 'GET'
        success: function(results) { 
            alert(results);
        }
    });
}

EDIT 1:

If you want the errors to appear in an alert, do this:

for debugging ajax, you can check the xhr, status, and error like so:

function get_data() {
    $.ajax({
        url: 'get_data.php?rand=' + Math.random(),
        type: 'GET',
        error: function(xhr, status, error) {
            alert(status);
            alert(xhr.responseText);
        },
        success: function(results) { 
            /* clear old results, then display the new results */
            $("#divResults").empty().append(results);
        }
    });
}

But this might not always display the full message, especially if the error message contains lots of data. it might end up going off the screen.

ORIGINAL ANSWER:

for debugging ajax, you can check the xhr, status, and error like so:

function get_data() {
    $.ajax({
        url: 'get_data.php?rand=' + Math.random(),
        type: 'GET',
        error: function(xhr, status, error) {
            /* clear old error message, then display the new php error message */
            $("#divErrorMessages").empty().append(status);
            $("#divErrorMessages").append(xhr.responseText);
        },
        success: function(results) { 
            /* clear the error message first */
            $("#divErrorMessages").empty();

            /* clear old results, then display the new results */
            $("#divResults").empty().append(results);
        }
    });
}

In your HTML you should have the 2 divs

<div id="divResults"></div>
<div id="divErrorMessages"></div>
like image 119
oshirowanen Avatar answered Oct 02 '22 03:10

oshirowanen