Sandeep vashisth Sandeep vashisth - 5 months ago 13
jQuery Question

Jquery post not working?

i am trying to load data from my local json file with jquery post. but it's not working for me but the same code below works when i replace $.post() to $.ajax(). but i want this with jquery Post only. I am getting (failed)net::ERR_FILE_NOT_FOUND in console.

<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {

$("#ajx").click(function(){
$.post({
type:"POST",
dataType:"JSON",
data:{},
url: 'ajax_info.json',
beforeSend:function(){
alert("before ajax");
},
success:function(data){

console.log(data);

},error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}

});

});
});
</script>

</head>
<body>

<input type="button" id="ajx" value="Load File Content">


</body>
</html>

Answer

$.post has a different structure of arguments compared to $.ajax, because $.post is simply a shortcut without having to specify a type property, so $.post and $.ajax aren't directly interchangeable.

The closest $.post equivalent would be:

$.post('ajax_info.json', {}, function(data){
    console.log(data);
}, 'json')
.error(function(){
    // handle erros
});

As you can see, $.post is not able to set a beforeSend handler, so it's not functionally the same as your $.ajax version.