Anurag Singh
Anurag Singh

Reputation: 727

$.post() not working as expected

Today i was using the j Query $.post(); method but i cannot find the reason for a problem which i encountered. The code snippet is below

$(document).ready(function(){

    //When the button 1 is clicked
    $('#generateTable1').click(function(){

        //Get the Json data of the product low in stock
        $.post('database_to_phpJSON.php',{option:1},function(value){
            value=JSON.parse(value);
            console.log(value);
            alert("hi");
        },{dataType:'json'});

    });

});

now when i run the code than i did not get the alert message "Hi" and in the console of firebug i did not see the console.log output. But as i removed the dataType from my code every thing worked fine...please let me knoe the reson for this.

Upvotes: 0

Views: 52

Answers (2)

adeneo
adeneo

Reputation: 318162

It's because when using $.post, you pass the dataType as a string only

$.post('database_to_phpJSON.php', {option:1}, function(value){

      console.log(value);

      alert("hi");

}, 'json').fail(function() {
      console.log(arguments); // will tell you what's wrong
});

And the result will be parsed automatically by jQuery when using the correct dataType

Upvotes: 1

xdazz
xdazz

Reputation: 160833

The third parameter is for data type, you only need to pass a string, but an object.

    $.post('database_to_phpJSON.php',{option:1},function(value){
        // and if you set the datatype to json, the value is already parsed.
        // value=JSON.parse(value);
        console.log(value);
        alert("hi");
    }, 'json');

Upvotes: 1

Related Questions