Json with PHP mysql and Jquery - php

I have a strange problem..
When i try to access my json code with the corresponding number [0], [1] etc.. I just get the first character of the object.
First of my code:
test2.php
if(isset($_POST['getCustomersArray'])){
$runQuery = mysql_query($Query) or
die("SQL: $Query)<br />".mysql_error());
$numrows = mysql_num_rows($runQuery);
$array = array(array());
for($i = 0;$i <= 2; $i++){
$row = mysql_fetch_array($runQuery);
$array[$i]['namn'] = $row['fornamn'];
}
print json_encode($array);
}
scriptfile.js
$.ajax({
type:"POST",
url: "test2.php",
data: "getCustomersArray=true",
datatype: "JSON",
cache: false,
success: function(json) {
console.log(json[0]);
}
});
The result (from console.log(json[0])):
[
The result from just console.log(json):
[{"namn":"the first name"},{"namn":"The secound name"},{"namn":"the third name"}]
Im not sure why the squarebrackets are there but maybe they should be?
Ive been fuzzing with this problem for a while now and im sure its something stupid. Please help.

You have an incorrect option in the AJAX settings,
datatype: "json",
It should be:
dataType: "json",

datatype: "JSON",
supposed to be
dataType: "json", // json in lowercase and T has to be captalized

Make sure you have the following code:
if(isset($_POST['getCustomersArray'])){
$runQuery = mysql_query($Query) or
die("SQL: $Query)<br />".mysql_error());
$numrows = mysql_num_rows($runQuery);
$array = array(array());
for($i = 0;$i <= 2; $i++){
$row = mysql_fetch_array($runQuery);
$array[$i]['namn'] = $row['fornamn'];
}
header("Content-Type: application/json; charset=UTF-8");
print json_encode($array);
}
Here you need to set the content-type to application/json and set the correct charset to avoid any cross-browser issues. Take a look at the following tutorial from my website which should cover all of this and perhaps some improvements to your code: PHP jQuery Search Tutorial - using JSON object the proper way
Hope this helps :)

Related

How do I retrieve data from mysql as an array and display in another page for manipulation?

My goal is to get the relevant rows from the database using getideas.php, so then on displayideas.php, I can actually pick them apart (e.g. get the idea with the highest score, display the idea score, display the idea in a particular html part of the code within a span).
On getideas.php, I have the following:
$sql = "SELECT evals.idea_score, evals.ideas_idea_id, ideas.idea
FROM evals, ideas
WHERE evals.ideas_idea_id = ideas.idea_id
AND evals.users_eval_id = '$eval_id'";
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_assoc($result)){
$data[] = $row["idea_score"];
array_push($data, $row["ideas_idea_id"], $row["idea"]);
}
return $data;
On displayideas.php, I have the following:
$.ajax({type: "POST",
url: "getideas.php",
data: { eval_id: eval_id },
success: function(response){
console.log(response);
}
})
I am not sure if I necessarily need an array. I am new to PHP/MySQL. I have been searching an answer to this online but cannot find a place that just puts it all together in a way I can understand to solve my problem. At this point, I feel like I have spent way too much time on it, and it is time to ask for help!
You need to json encode your array before using it into javascript
so use
return json_encode($data);
reference:
http://in3.php.net/manual/en/function.json-encode.php
I hope this will help you.
getideas.php will bocome as follow.
$sql = "SELECT evals.idea_score, evals.ideas_idea_id, ideas.idea
FROM evals, ideas
WHERE evals.ideas_idea_id = ideas.idea_id
AND evals.users_eval_id = '". mysql_real_escape_string($_POST['eval_id'])."'";
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_assoc($result)){
$data[] = $row["idea_score"];
array_push($data, $row["ideas_idea_id"], $row["idea"]);
}
$post = json_encode($data);
echo $post;
On displayideas.php,
$.ajax({type: "POST",
url: "getideas.php",
dataType: "json",
data: { eval_id: eval_id },
success: function(response){
console.log(response);//you can access data from here by response[0].attributename.ie,response[1].idea_score.
}});

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 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(',')

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.

PHP Arrays - jQuery referencing issue

I have the following php:
1) echo json_encode(array('message' => 'Invalid Login Details: '.$user));
I also have the following:
2) $row = mysql_fetch_assoc($result);
echo(json_encode($row));
Now consider the following jQuery:
$.ajax({
type: "POST",
url: "get_login.php",
data: {username: getusername, password:getpassword, usertype:getusertype},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
}
})
This succeeds for (1) but not for (2). This is obviously because jQuery expects a php response containing a message variable. (2) does not conform to this...I don;t know how to make this work as I am using different methods for creating the arrays...
How can I make $row in the php compatible with the data.message in the jQuery?
try:
$data = array();
$data["message"] = "Valid request";
$data["row"] = mysql_fetch_assoc($result);
echo(json_encode($data));
message = row:
$data = array();
$data["message"] = mysql_fetch_assoc($result);
echo(json_encode($data));
or two line solution (inspired by val):
$row = mysql_fetch_assoc($result);
echo(json_encode(array("message" => $row)));
Try
$row = mysql_fetch_assoc($result);
echo(json_encode(array('message'=>'I am the message','result'=>$row));
Then to answer your second question on the comments something similar to this could show the information ....
$.ajax({
type: "POST",
url: "get_login.php",
data: {username: getusername, password:getpassword, usertype:getusertype},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
var html = '';
for(var i = 0; i<data.result.length;i++){
html +='<div>'+data.result[i].fname+'</div>';
}
$('#result').html(html);
}
})
ofcourse you need to edit it abit where applicable .
i believe you don't have $row['message'] from mysql_fetch_assoc.
you have to explicitely define the message key on the array before json_encode.
$row = mysql_fetch_assoc($result);
$row['message'] = 'Hello '.$row['username'];
echo(json_encode($row));

Categories