somejkuser
somejkuser

Reputation: 9040

jquery json parsing error from $.ajax and not $.post

This code gives me a json parsing error:

$(document).on('ready', function() {            
    $("#q").on('keyup', function(){                  
        $.ajax({
            url: 'newsearch.php',
            dataType: 'json',
            type: 'POST',
            timeout: 125,
            data: {q:$("#q").val()},
            success: function(jsonData){
                var responseData = $.parseJSON(jsonData);
                parseSearchResults(responseData);
            },
            error: function() {
                console.log("Error");
            }
        });
    }); 
});

When this code does not:

$(document).on('ready', function() {            
    var filterTimeout;
     $("#q").keyup(function (event) {            
         clearTimeout(filterTimeout);
         filterTimeout = window.setTimeout(function () {
             $.post("newsearch.php", {q: $("#q").val()}, function (jsonData) {
                 var contactData = $.parseJSON(jsonData);
                 parseSearchResults(contactData);                
             });
         }, 125);
    }); 
});

Here is my json string:

{"A":[{"primary_emailaddress":"[email protected]","alternate_emailaddress":"[email protected]","personal_address_line1":"123 west avenue\\n","personal_address_city":"boynton beach","birthday_month":"October","personal_address_zipcode":"33324","home_phonenumber":"1111","company_phonenumber":"1111","cell_phonenumber":"1111","birthday_day":"19","birthday_year":"1982"}]}

Upvotes: 1

Views: 651

Answers (1)

Evan Mulawski
Evan Mulawski

Reputation: 55344

Because you specified dataType: 'json', jQuery automatically parsed it as JSON, causing the $.parseJSON call to fail (since the data is no longer a valid JSON string, it's a JavaScript object).

Just use:

var responseData = jsonData;

Upvotes: 1

Related Questions