简体   繁体   中英

Ajax Php Mysql retrieve confirmation when data inserted

I have the following ajax call for sending a form into a mysql database through a php file hosted on a server:

 <script type"text/javascript">
$(document).ready(function(){
    $("form#submit").submit(function() {
    // we want to store the values from the form input box, then send via ajax below
    var fname     = $('#fname').attr('value');
    var lname     = $('#lname').attr('value'); 

        $.ajax({
            type: "POST",
            url: "jquery-ajax-control.php",
            data: "fname="+ fname + "&lname=" + lname,
            success: function(){
                $('form#submit').hide();
                //$('form#submit :input').val("");
                $('div.success').fadeIn();
            }
        });
    return false;
    });
});
</script>

And my php:

<?php

    include ("db.php");

    // CLIENT INFORMATION
    $fname        = htmlspecialchars(trim($_POST['fname']));
    $lname        = htmlspecialchars(trim($_POST['lname']));

    $addClient  = "INSERT INTO clients (fname,lname) VALUES ('$fname','$lname')";
    mysql_query($addClient) or die(mysql_error());

?>

On success function I want to retrieve an alert message from php or mysql to be sure that data is inserted in the database because the ajax it will be successful even if the connection it's down and I have the php file hosted on another server. How could I do that? Thank you!

Have the jquery-ajax-control.php script return this information (perhaps encoded in a JSON string) and then parse it in the success function.

Here's an example that would display the output of the PHP script in an alert (if the request was successful):

     $.ajax({
        type: "POST",
        url: "jquery-ajax-control.php",
        data: "fname="+ fname + "&lname=" + lname,
        success: function(message) {
            alert(message);
        }
    });

You'd just need to alter your PHP script to return a message based on what happens.

You could also amend your PHP script to return the correct HTTP status code (eg a 500 if there was an error) and check for that, using the various callback functions jQuery allows to the ajax method.

First of all, calling php from another server will give you error if you do not make the call with jsonp.

And for next part, if your php file get any error due to connection down you can send the error via response from php and getting it from jquery ajax callback function success.

Also you can get the message in callback function and show it through javascript alert message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM