BarclayVision
BarclayVision

Reputation: 863

JQuery AJAX failing

My AJAX call executes and returns what I want it too but not within .done It fails under .fail and results work in .always

 $(document).ready(function() {
        $("#submit").click(function(){

            var formData = $("#callAjaxForm").serialize();

            $.ajax({
                type: "POST",
                url: "JSON_MDB_UPDATE.php",
                data: formData
            })
            .done(function(data) {
                alert( "Done: " + data );
                data = $.trim(data);
                $("#notification").text(data.responseText);
            })
            .fail(function(data) {
                alert("Failed: " + data);
                console.log(data);
            })
            .always(function(data) { 
                $("#notification").text(data.responseText);
            });

            return false;
        });
    });

here is my console results:

console.log

My PHP is just a simple example echo:

<?php

header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");


$firstName = $_POST[firstName];
$lastName = $_POST[lastName];

echo("My First Name: " . $firstName . " Last Name: " . $lastName);
?>

Upvotes: 0

Views: 72

Answers (1)

Quentin
Quentin

Reputation: 944392

header('content-type: application/json; charset=utf-8');

This says you are outputting JSON, so jQuery will attempt to parse it as JSON and fall to the error state if it can't.

echo("My First Name: " . $firstName . " Last Name: " . $lastName);

This is not JSON

Output JSON instead.

echo json_encode(Array("My First Name" => $firstName, "Last Name" => $lastName));

Alternatively, if you do not want structured data: Don't say you are sending JSON:

header('content-type: text/plain; charset=utf-8');

Upvotes: 4

Related Questions