0

By using Alert on the response paramater after a jquery success will display the values I need, and the problem is picking them out with k/v. I don't know if this is some incompatibily issue with json format or what, from php. Either nothing happens (no Alert) or the alert will say 'undefined' if I attempt to get values by using the keys to them.

Relevant code:

JQuery:

var curr = $(this).val();
// alert(curr);
$.ajax({
type: 'GET',
url: 'CurrencyResponse.php?q='+curr,
contentType: "application/json; charset=utf-8",
success: function(response) {
var items = response.d;
// alert(response); this will display some json key value from server
$.each(items, function (index, item) {
// alert(item.msg); or updating some div tag here, eventless
});
},

PHP:

<?php
// $query = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
// $query = $_GET["q"];
$response = array();
$response["msg"] = "Hjksa!";
$response["nok"] = "9.32";

echo json_encode($response);
?>

Help here will be much appreciated! =)

4 Answers 4

2

Use the dataType parameter for jQuery's AJAX, like so:

$.ajax({
    type: 'GET',
    url: 'CurrencyResponse.php?q='+curr,
    dataType: 'json',
    success: function( json) {
        alert( json.msg); // Will output Hjksa!

    }
});

This tells jQuery that the response from the server is JSON, and that it should return a JSON object to the callback functions that take the server response as their parameters.

Read more about dataType on jQuery's site.

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

1 Comment

Doh! Such tiny details cost me many hours. Thank you so much =) I actually had dataType in earlier on but something else must have broken the script and dataType got removed somehow.
1

Judging from the documentation, it'll read the MIME type from the response header, and use that, unless you explicitly specify it. So either set the headers on the PHP script to application/json or set the "dataType" param to "json".

Comments

0

I recommend sending an object to the client script. It makes it easier to read the data.

echo json_encode((object) $array);

Comments

0

I was working through a similar problem for a couple of days, I had set

dataType: "json",

but it was still coming back as a string. Specifying json in the header of my php file in addition to in the jquery request resolved the issue for me.

header("Content-type: application/json");

Hopefully that helps someone!

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.