Output json array in jQuery - php

I am a little stuck on how to retrieve all the values from the json array in jquery. I know it needs to be looped but how ? The function -
at the moment is:
$.ajax({
url: 'query.php',
data: "",
dataType: 'json',
success: ajaxfunction
});
function ajaxfunction(json_data){
// problem is below, i need to output all the data from the array
console.log (json_data)
while(json_data){
$('#maindisplay').html("<b>Product: </b>"+json_data.prod_name+"<b> colour: </b>"+json_data.colour); // problem is here, i need to output all the data from the array
}
}
The php:
$result = mysql_query("SELECT * FROM fproduct WHERE fproduct.category='Shirts'");
$elements = array ();
do{
$row=mysql_fetch_array($result);
if ($row) //if there is anything
$elements[] = ($row);
} while($row);
echo json_encode($elements);

You have to iterate over the elements of the array.
function ajaxfunction(json_data){
for (var i = 0; i < json_data.length; i++){
$('#maindisplay').append($("<b>Product: </b>"+json_data[i].prod_name+"<b> colour: </b>"+json_data[i].colour+"<br>"));
}
}

Related

igetting data in json form using jquery ajax php

Hi I was trying to get 2 dimensional array from php using ajax ,jquery ,but I am not able to get the response
here is my code
html code
$.ajax({
type: "POST",
url: "get_data.php",
data: "",
dataType: "json",
success: function (json) {
var data = json.msg;
initChart(data);
}
});
php code
header('Content-Type: application/json');
$responce=array();
for($i=0;$i<10;$i++)
{
$responce[]=array($i,$j);
}
echo json_encode(array("msg"=>$responce));
but I am getting message "json is empty " when debugged in Bugzilla
Maybe this is what you mean?
for($i=0;$i<10;$i++) {
for($j=0;$j<10;$j++) {
$responce[]=array($i,$j);
}
}
Try this :
$response = array();
for($i=0; $i<10; $i++) {
$response[$i] = array();
for($j=0; $j<10; $j++) {
$response[$i][$j] = 10 * $i + $j;//Value is just an example. The important part is the left hand side of the assignment.
}
}

how to fetch the array data from database query in a php file to ajax sucess data

i am trying to get the data which is in array, from an SQL query to the ajax success data. Here is the code i tried,
function adminchecksub(value1){
//alert('hi');
var value1=$('#adminsid').val();
//alert(value1);
if(value1==''){
alert('Please enter a Sub id');
}
else{
//alert(value1);
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=adminsubcheck',
data: {value1:value1},
async: true,
success: function (data) {
alert(data);
if (data == 1) {
alert('inside');
//window.location.assign(rdurl+"?sid="+sid);
return true;
} else {
//alert('does not exist!');
//alert('outside');
return false;
}
}
});
}
now in the php method which is requested from the above ajax call, i have to get the data return by this function which is returning an array
function adminsubcheck($sid){
$subid=$sid['value1'];
$row = array();
//echo $subid;
$query = "SELECT Sub_id,Status,Sub_type FROM Sub WHERE Sub_id=$subid";
//echo $query;
//echo $subid;
$queryresult = mysql_query($query);
$count = mysql_num_rows($queryresult);
//echo $count;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
return $row;
}
here $row is returning an array as data to the ajax function, where i need to get all the items seperately. Some one help me out to get the values into the ajax call. Thanks in advance..
In your PHP file, you can return your array as a json object in the following way (notice how the PHP file echos the result to pass it back to javascript)
...
$json = json_encode($row);
echo $json
Now add the following to your javascrip ajax
$.ajax({
...
// Whatever code you currently have
...
}).done(function ( json ) {
var data = JSON.parse(json);
//Continue with javascript
});
You can handle the java script variable 'data' as an associative array like it was in PHP
also, look how you populate the php variable $row and adjust the following way:
$cnt = 0;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[$cnt] = $r;
$cnt++;
}
$json = json_encode($row);
echo $json;
in javascript you can access your rows the following way in teh data variable:
var value = data[0]['field_name'];
in the above statement, 0 will correspond to the value of $cnt (i.e. mysql returned row number)
return $row;
replace like this
echo json_encode($row);
and add dataType='json' in ajax like this
dataType: 'json',
If you want get the value in ajax call i think it shoul be :
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
echo json_encode(array('data'=>$row));
exit;

How to get MySQL data into correct array structure

I just finished getting a script to work by using a hard coded array like so:
dataArray[0] =[50,10,0.3,0.25,50,"FFF",3];
dataArray[1] =[50,10,0.3,0.2,50,"FFF",3];
....
dataArray[5] =[50,20,0.5,0.7,120,"FF0",4];
I put the contents of dataArray into a db table so I could eliminate the hard coded array.
I'm returning the data in a string from MySql with PHP, and a data dump shows that the number of values and the values themselves are correct.
However, I'm apparently not coding the data capture correctly because I'm not ending up with an array like my hard coded array (I need to maintain the structure of my hard coded array).
Here's the code for the db read:
function getSomeData(){
$.ajax({
type: "GET",
url: "GetSomeData.php",
dataType: "text",
success:function(result){
setSomeData(result);
}
});
}
var someDataArray = new Array();
function setSomeData(resultData){
var resData = resultData.split('^');//record split
for(var i = 0; i < resData.length; i++){
someDataArray[i] = resData[i].split('#');//field split
someDataArray[i].pop();//removes array element occupied by '^'
if(i == resData.length - 1){
setDataArray();
}
}
}
This for loop in setDataArray() doesn't create the correct array structure because someDataArray[x] is just a string:
var dataArray = new Array();
function setDataArray(){
for(var i = 0; i < dataArray.length; i++){
dataArray[i] = someDataArray[i];
}
}
So I tried putting someDataArray[x] in an array like so:
dataArray[i] = [someDataArray[i]];
But that didn't work either.
I've spent the 2 days trying to puzzle this out, reading blogs, and experimenting with everything I could think of, but no luck. I think it's a simple solution but I just can't get it.
Help?
EDIT:
After learning a bit about JSON and json_encode I now have my script working. I wanted to post the way I did it to acknowledge that I received some valuable advice from Pat Burke. The code below may not be what he had in mind but I massaged it until it worked. But I don't really understand why it works, so I'll have to do some more reading on json_encode I think.
Note that using dataType:"json" in the ajax call threw an error.
//GetSomeData.php
$return_arr = array();
$query1 = "SELECT * FROM mytable ORDER BY idx ASC";
$result = mysql_query($query1) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($result)){
$resultArray = array();
$resultArray[] = (int)$row['dc'];
$resultArray[] = (int)$row['smlspc'];
$resultArray[] = (float)$row['sclx'];
$resultArray[] = (float)$row['scly'];
$resultArray[] = (int)$row['lgspc'];
$resultArray[] = (int)$row['colr'];
$resultArray[] = (int)$row['diam'];
if(count($resultArray) == 7){
array_push($return_arr, $resultArray);
}
}
echo json_encode($return_arr);
mysql_free_result($result);
//new js
function getSomeData(){
resultData = new Array();
$.ajax({
type: "GET",
url: "GetSomeData.php",
dataType: "text",
//dataType: "json", //using this threw an error (see below)
success:function(result){
resultData = $.parseJSON(result);
$("#p1").append("resultData.length =" + resultData.length + "<br />");
//resultData.length =114 (it's a string not an array)
$("#p1").append("resultData =" + resultData + "<br />");
//resultData =
//[[50,10,0.375,0.25,50,0,0],
//[50,10,0.3,0.2,50,0,1],
//[50,10,0.6,0.4,0,0,2],
//[50,0,0.4,0.4,0,0,3],
//[50,0,0.4,0.4,0,0,3]]
for(var i = 0; i < resultData.length; i++){
$("#p1").append("resultData[" + i + "] =" + resultData[i] + "<br />");
//data displayed with dataType: "text"
//resultData[0] =50,10,0.375,0.25,50,0,0
//resultData[1] =50,10,0.3,0.2,50,0,1
//resultData[2] =50,10,0.6,0.4,0,0,2
//resultData[3] =50,0,0.4,0.4,0,0,3
//resultData[4] =50,0,0.4,0.4,0,0,3
//data displayed with dataType: "json"
//resultData is null
}
},
//this has no effect with either dataType: "text" or dataType: "json"
contentType: 'application/json'
});
}
if someDataArray[i] is a string of values separated by commas, you could do
dataArray[i] = someDataArray[i].split(',')

is php json_encode & AJAX breaking my array?

I'm grabbing some database entries, creating a 2D array and then passing them to js with AJAX. But when I loop through the array in javascript, it's an "undefined" mess. The console log for dbArray works fine, so I know the PHP/AJAX is working. Not sure what I am doing wrong with the loop...
PHP ('load-words.php):
$query = mysql_query("
SELECT * FROM words
ORDER BY RAND()
LIMIT 50
") or die(mysql_error());
$dbArray = array();
while ($row = mysql_fetch_assoc($query)) {
$word_phrase = stripslashes($row['word_phrase']);
$description = stripslashes($row['description']);
// construct a 2D array containing each word and description
$dbArray[] = array($word_phrase,$description);
};
echo json_encode($dbArray);
Javascript:
$.ajax({
url: 'func/load-words.php',
success: function(dbArray) {
console.log(dbArray);
var items = "<ul>";
for (var i in dbArray) {
items += "<li><a href='#'><b>" + dbArray[i][0] + ' : ' + dbArray[i][1] + "</a></li>";
}
items += "</ul>";
div = $('#dbArray');
div.html(items);
}
});
I guess this is failing because jQuery is interpreting the AJAX response as a string, since your PHP is not outputting a JSON header and your AJAX is not stipulating JSON. This is easily tested:
$.ajax({
url: 'func/load-words.php',
success: function(dbArray) { alert(typeof dbArray); /* "string"? */ }
});
Try
$.ajax({
url: 'func/load-words.php',
dataType: 'json', //<-- now we explicitly expect JSON
success: function(dbArray) { alert(typeof dbArray); /* "object"? */ }
});

about json_encode and ajax dataType: "json"

In my ajax code:
$.ajax({
url: CI_ROOT + "isUserExist",
type: "GET",
data: {recepient: recepient},
success: function(r) {
console.log(r)
}
})
Gives me an output [{"records":"1"}][{"records":"1"}] So I parsed it to json by adding dataType: "json" in my ajax code. But when I parsed it, it doesn't give me output but error on try-catch-block.
How do I get it to display as objects?
In my PHP code, I'm doing it this way:
for ($i = 0; $i < count($matches[0]); $i++) {
echo json_encode($this->searchmodel->doesUsersExists($matches[0][$i]));
} //gets the user id of the user from a given string.
Add each entry to an array and then json encode that array, instead of json encoding each one separately. If you only have one call to json_encode, you will get valid JSON:
$result = array();
for ($i = 0; $i < count($matches[0]); $i++) {
$result[] = $this->searchmodel->doesUsersExists($matches[0][$i]);
} //gets the user id of the user from a given string.
echo json_encode($result);
That's not valid JSON. Make an array from your exist results and encode that.

Categories