Issue with JSON and return data for $.Post
Hello,
I am having a problem with json data always appearing as "false" when directly returning it to $.post
My jQuery function is the following:
- //inside another function called with "page" as an argument
- //this function is to repopulate form fields
- jQuery.post("Edit.php", {SearchFor: page}, function(data,success){
- alert(data);
- //should loop through the json object and assign it to the correct form fields
- $.each(data, function (i, elem) {
- $("input[name='"+i+"']").val(elem);
- });
- }, "json");
Edit.php generates a json string to return as follows:
- <?php
- //excluding some code
- $sql = "SELECT * FROM `test` WHERE `testname` = 'Default' LIMIT 1";
- $result =$db->query($sql);
- //echo result back to $.post function
- echo json_encode(mysql_fetch_assoc($result));
- ?>
This will display as false when I alert(data); in the jQuery function.
If I explicitly return the string that json_encode(mysql_fetch_assoc($result)); creates the data appears correctly. (I have the string that json_encode outputs logged to a text file, so I know it is generating the correct json string).
Short version:
Something about the way php echo's json_encode(mysql_fetch_assoc($result)); is causing a problem when passing the json string back to jQuery, that directly passing the string does not.
If I pass the string explicitly it works!! ie: echo '{"formtag": "Somedata"}';
Thanks for any advice the community can offer!