简体   繁体   中英

Calling JavaScript function after updating table with PHP

I have a simple website that uses JavaScript to collect user input and sends data to PHP script (script is an external php file) via AJAX request. PHP script updates database with this information.

Now, i have a JS function on my website that i want to call only after PHP script is sucessfuly run and database updated. I don't need any data from database or PHP script, i only want to make sure that database is updated before calling this Javascript function.

This is what AJAX request looks like:

function ajax_post(){
  if (typeof featureId !== 'undefined') {
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    var url = "parse_file.php";
    var fn = featureId;
    var vars = "featureId="+fn;
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var return_data = hr.responseText;
            document.getElementById("status").innerHTML = return_data;
        }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    document.getElementById("status").innerHTML = "processing...";
    hilites.destroyFeatures();
    featureId = undefined;
  }
  else {
    window.alert("Select polygon first");
  }
}

What is the best way to do this? Some examples would really help.

Looking at your code, you simply need to call the function around this part:

hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("status").innerHTML = return_data;

        // CALL YOUR FUNCTION HERE
    }
}

The best solution is to use a Promise . However, this is not supported in IE 11, so you will need to use a polyfill on some browsers.

Here is an example using jQuery.

// This is the function you want to call after the script succeeds
function callbackSuccess() {
  console.log('Done!');
}

// This is the data you want to submit to the PHP script
var myData = {
  hello: "world"
};

// This is the actual AJAX request
$.post('/my-script.php', myData).done(function(){
  callbackSuccess();
});

Add this to the end of your php save-function:

header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('status' => 'SUCCESS'));

Making the call:

$.getJSON('url_to_your_php_file.php', function(data) {
    if (data.status == 'SUCCESS') {
        console.log('Save complete');
    }
    else {
        console.log('oops, something went wrong!!');
    }
});

It's possible to return something like ERROR, this will return:

console.log('oops, something went wrong!!');

You may try the following:

In php you can use return code from sql statement

echo $sqlResult = $conn->query($sqlStatement);

On Javascript, you can try the following $.ajax({ url: 'file.php', type: 'POST', data: {

                    data1 : data1,
                    data2: data2
                },
                success: function(data){
                if(data == success_code){
                    alert("Success")

} }

Hope this helps!

Completing ajax request without errors does not mean that the data is saved to DB without errors.

Even if your PHP script fails to save the data, it probably echos some error message or even empty output as regular HTTP response, and it would show as success as far as the ajax request goes.

If your intention is to make sure that the data is really saved before calling the JS function, then the PHP script should containg enough error handling.

If you write the PHP script to return response status code based on the real outcome of save operation, then you can rely on those status codes in ajax response handling (success = ok, error = not ok).

Bu what I usually do, is that instead of using HTTP status codes, I echo "OK" or something similar at the end of succesfull PHP execution (and "ERROR" if there are any errors), and then check for those strings in ajax response handler (hr.responseText in your code).

Maby you have to try this:

setTimeout(function(){
  //your function here...
}, 500);

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