I have a function that is calling a php page on a remote server that is not reaching the server. This function was working until I checked it today, when the customer told me that the counter was not updating. The param being passed in is a string, the alert shows the parameter ok, but the res.counterValue value is not coming back from the php page.
function getCounterJSON(param) {
//alert('param: '+ param);
$.getJSON('http://domainname/path/view.php?callback=?', 'counter=' + param, function(res) {
//alert('return value '+res.counterValue);
document.getElementById(param).innerHTML = '   ' + res.counterValue + ' views';
});
}
Callback function on the PHP page
{
echo $_GET['callback'] . '(' . "{'counterValue' : $counterValue}" . ')';
}
The counterValue is retrieving from the db ok too.
You should use
json_encodeinstead of constructing your own JSON, like this:Unless you use JSONP (and you’re not, since the
dataTypeparameter of jquery.Ajax is not set to"jsonp"), you don’t need the callback.Apart from that, the reason why your code doesn’t work is that it separates strings with single quotes (
'). According to the JSON spec, strings must be enclosed with double quotes (").Also, you should use DOM functions (or their jQuery equivalents, such as
append) instead ofinnerHTML.Either way, HTML entities must be terminated with a semi-colon; you want
(although some browsers will render the invalid as well).