开发者

jquery ajax results message

I have a ajax call to a php script that updates my MySQL DB with a new record when the user submits a data string as an entry. Part of the PHP is an if/else in place that will check to see if the entry is a duplicate. I can stop the duplicate from updating the database but I don't know how to send back an "error" message that says "That record already exists"...here is my jquery: [script] $(function() {

    $(".entry_button").click(function() 
{
    var element = $(this);
    var boxval = $("#entry").val();
    var dataString = 'entry='+ boxval;
        if(boxval=='') {
            alert("Please Enter Some Text");
        } else {

            $("#flash").show();
            $("#flash").fadeIn(400).html('<img src="images/loading.gif" align="absmiddle">&nbsp;<span class="loading">Broifying It...</span>');
            $.ajax({
                    type: "POST",
                    url: "update_data.php",
                    data: dataString,
                    cache: false,
                    success: function(html){
                        $("ol#update").prepend(html);
                        $("ol#update li").slideDown("slow");
                        document.getElementById('entry').value='';
                  开发者_运维知识库      $("#flash").hide();
                    }

            });
        }
        return false;
    });
});
[/script]

and here is my php script that updates the DB (update_data.php):

[php]
include('db.php');
if(isset($_POST['entry']))
{
$date_created = date('Y-m-d H:i:s');
$entry = $_POST['entry'];
$query = "SELECT COUNT(*) AS count FROM table WHERE entry = '$entry'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if ($row['count'] == 0) {
mysql_query("insert into table (entry,date_created) values     ('$entry','$date_created')");
$sql_in= mysql_query("SELECT entry,id FROM table order by id desc");
$r=mysql_fetch_array($sql_in);
$newentry=$r['newentry'];
$id=$r['id'];
?>
<li class="entry bar<?php echo $id; ?>">
<div class="thebro"><span><?php echo $newentry; ?></span></div>
<div class="hr"></div>
<div class="utility-left"><span class="share"><a href="#" title="Share">share</a></span> | <span class="time">days ago</span></div>
<div class="utility-right"><span class="comments">COMMENTS</span> | <span  class="like">LIKE</span></div>
</li>
<?php
} else {
$error = "Sorry, that record already exists";
}   

}
[/php]

I want to be able to spit that $error variable from the php script to be sent back in the ajax call and be displayed in a element in my HTML. I've googled the crap out of ajax error messages but they all have to do with header errors, not validation error messages. I also am not using json_encode, unless someone wants to redo that jquery chunk above so that it is sent as json data.

Any ideas would be awesome!


If an error is produced in PHP, I want it to be handled by the error method of the jquery ajax object, and not 'fake it' by sending a normal HTTP 200 response with some error marking the responseText.

When a HTTP 500 is returned from PHP, no 'responseText' is captured by the ajax error handler. The error handler receives the XHR object, a status of 'error', and an error message of 'Internal Server Error'.

I tried to manipulate the error message..

header( 'HTTP/1.1 500 My Custom Error Message' );

But that didn't work.

What did work is this:

function errorHandler( $number, $message, $file, $line ) {
    $data = array(
        'message' => $message,
        'line' => $line,
        'file' => $file,
        'trace' => debug_backtrace()
    );

    header( 'Debug: ' . json_encode( $data, true ) );
}

This will get PHP to return HTTP 500, with your custom details in an extra header.

To access the custom details from the ajax error handler:

$.ajax({
    success: function( response ) {
        // ...
    },
    error: function( XHR, status, errorThrown ) {
        $.each( XHR.getAllResponseHeaders().split( '\n' ), function( i, header ) {
            if ( header.substr( 0, 7 ) == 'Debug: ' ) {
                var error = JSON.parse( header.substr( 7 ) );
                console.log( error );
            }
        });
    }
});


Just echo it in your phpfile and use:

document.getElementById('ajaxCatchbox').innerHTML = ajaxRequest.responseText;

The responsetext from your ajaxrequest object picks up everything thats echoed... Dunno the equivalent in jquery tho


Echo the error in PHP and exit. Then, at the beginning of your success: function, do something like this:

    if(ajaxRequest.responseText.substring(0, 5) === 'Sorry') {
        alert(ajaxRequest.responseText);
        return;
    }

I suggest using the substring approach because it allows you to create a variety of different error messages as long as they all begin with "Sorry". Useful for debugging.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜