Here is what I have in PHP:
$arrayresults = array();
while($popularbrushesrow = mysql_fetch_array($popularBrushes)){
$arrayresults[] = '<a href="brushdescription.php?id='.$popularbrushesrow['bd_brushid'].'"><img class="slideImg" alt="'.$popularbrushesrow['bd_brushname'].'" title="'. $popularbrushesrow['bd_brushname'].'" src="'.$popularbrushesrow['bd_imagefilepath'].'" /></a>';
}
echo json_encode($arrayresults);
Now, jquery:
$.ajax({
type:'GET',
url:'getDataForSlide.php',
data:"limit="+limit+"&required="+required,
dataType:"json",
cache:true,
success: function(result){
var arrayFromPHP = JSON.parse(result);
alert(arrayFromPHP);
}
})
Could someone please help me out. Whats the correct way to form an array in JSON?
The problem is likely to be this line:
var arrayFromPHP = JSON.parse(result);
Because you've specified dataType: 'json'
in the ajax
options, jQuery has already done the parsing for you. So doing it a second time starts out by doing toString
on the array, which does a join
, which results in invalid JSON.
Simply use result
directly.
For example, suppose you have this JSON:
[
"<a href=\"http://stackoverflow.com\">Stack Overflow</a>",
"<a href=\"http://google.com\">Google</a>"
]
Because jQuery has already done JSON.parse
on it, result
is an actual array. So if you then pass it into JSON.parse
, the first thing that does is toString
, which gives you this:
<a href="http://stackoverflow.com">Stack Overflow</a>,<a href="http://google.com">Google</a>
...which is not, of course, valid JSON.
I would simplify your jquery....like this...
$.getJSON("getDataForSlide.php", { limit: limit, required: required}, function(json) {
console.log(json);
});
I like to use
jQuery.parseJSON(response);
And don't forget to use die(); or exit(); on php side after you echo your results, since it's a ajax call. This information can be found here: http://codex.wordpress.org/AJAX_in_Plugins