简体   繁体   中英

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working. PHP

$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);

$return["color"] = $row['APPRENTICE_SIGNATURE'];

$return["json"] = json_encode($return);
echo json_encode($return);
?>

Javascipt

var data = {
    "formId": formID,
    "newSuper": newSuper
};
data = $.param(data);
$.ajax({
    type: "POST",
    dataType: "json",
    url: "src/GetInfo.php", 
    data: data,
success: function() {
    location.reload();
}

});

I'd start by modifing the code like this:

var data = {
    "formId": formID,
    "newSuper": newSuper
};

// No need for serialization here, 
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);

$.ajax({
    type: "POST",
    dataType: "json", 
    url: "src/GetInfo.php", 
    data: data,

    // As suggested by Rocket Hazmat, try to add an error callback here
    error: function(jQueryXHR, textStatus, errorMessage) {
        console.log("Something went wrong " + errorMessage);
    },

    success: function(jsonResponse) {
        // Try to reference the location object from document/window
        // wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
        // Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data

        // One of these should be fine
        wd.location.assign(wd.location.href) : go to the URL
        wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
        wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
    }
});

Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response

$.ajax({
    ...

    // Remove data type
    // dataType: "json", 

    ...

    success: function(plainTextResponse) {
        // Eval response, NOT SAFE! But working
        var jsonResponse = eval('('+ plainTextResponse +')');

        ...
    }
});

Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.

Your php json_encode should be like this:

$data = json_encode($return);
echo $data;

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