0

I am trying to populate a div using ajax.Here goes the code

$.ajax({
    url: "/assets/location.php",
    //dataType:"json",
    success: function (result) {
        alert("hello");

        $.each(result, function (i, val) {
            alert("hello");
            alert(val.title);
        });
    }
});

server

<?php
require_once 'include.php';

$db = connect_db();
$query = 'CALL get_location()';
$result = mysql_query($query, $db) or die(mysql_error($db));
$data = array();
while ($row = mysql_fetch_array($result)) {
    array_push($data, $row);
}

echo(json_encode($data));
?>

Everything works fine but when I uncomment dataType:"json" script stops executing success function. Please point out the errors.

3
  • 1
    Is your json formatted correctly? When you add dataType:json, success callback is not called when there is an error in parsing the response. And also you wont need JSON.parse , jquery will do it automatically for you. Commented Feb 7, 2015 at 11:36
  • I am new to web development so I don't know it well.Read somewhere that I should use JSON.parse to make code work in chrome :( :( Commented Feb 7, 2015 at 11:40
  • Thats right, you will need JSON.parse when you dont have dataType: json. But when you have it jQuery will automatically parse the json response and pass the JSON object to your success callback. Commented Feb 7, 2015 at 11:41

2 Answers 2

1

Your success function includes the expression JSON.parse(result).

With dataType:"json" uncommented, jQuery automatically json-decodes the data.

Therefore, JSON.parse(result) will try to decode something that's already decoded.

I'm guessing you get a parse error. Check your console.

Sign up to request clarification or add additional context in comments.

Comments

0

Without dataType:'json' option, your code should be.

$.ajax({
    url: "/assets/location.php",
    success: function (result) {
        alert("hello");

        //data is not parsed, so you have to explicitly parse to json
        $.each(JSON.parse(result), function (i, val) {
            alert("hello");
            alert(val.title);
        });
    }
});

With dataType:'json' option, your code should be.

  $.ajax({
        url: "/assets/location.php",
        dataType:'json',
        success: function (result) {
            alert("hello");

            //result is already parsed to json (by dataType option), 
            //So no need to parse again.
            $.each(result, function (i, val) {
                alert("hello");
                alert(val.title);
            });
        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.