lukieleetronic lukieleetronic - 5 months ago 17
Ajax Question

jQuery - Ajax POST method error,

I'm experimenting with a simple AJAXing using jQuery. I'm posting an empty data to a .php page then echoing the JSON encoded data back to the page where my javascript is.

I'm getting an error while doing this but I can't figure out why this code is producing the error..

Here is the code I've written,

index.php

<form id="getData">
<button name="control" type="submit" value="A">GET DATA</button>
</form>

<form id="showData">
<button name="control" type="submit" value="A">SHOW DATA</button>
</form>
<div id="results"></div>
<div id="map"></div>

<script>
$("document").ready(function(){
$("#getData").submit(function(event){

$.ajax({
url : "/getVehiclePosition.php",
type: "POST",
data: "",
success: function(data, textStatus, jqXHR)
{
//data - response from server
console.log("Hooray, it worked!");
$('#results').append(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
}
});

});
});
</script>


in the Chrome console, I'm getting the following error..

The following error occurred: error
error @ ?control=A:52
i @ jquery-1.12.2.min.js:2
fireWith @ jquery-1.12.2.min.js:2
y @ jquery-1.12.2.min.js:4
c @ jquery-1.12.2.min.js:4


For some reason if I take out the form submit binding to #getDATA, it works well again.. pulling my hair out at the moment, please help!. Many thanks in advance.

[UPDATE]===================================================================
Captured XHR,

enter image description here

Answer

You didn't stop the form from submitting by its default action so that you can implement your ajax request. Use event.preventDefault() before your ajax.

$("document").ready(function(){
        $("#getData").submit(function(event){
            event.preventDefault();

            $.ajax({
                url : "/getVehiclePosition.php",
                type: "POST",
                data: "",
                success: function(data, textStatus, jqXHR)
                {
                    //data - response from server
                    console.log("Hooray, it worked!");
                    $('#results').append(data);
                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    console.error(
                        "The following error occurred: "+
                        textStatus, errorThrown
                    );
                }
            });

        });
    });
Comments