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(',')
Related
I am using PHP to retrieve some records from a MySQL database, I would like to send these to my AJAX and loop through them, in order to prepend rows to an existing table.
However I can only see the last (most recent) record returned from my query. Could someone please point out where I am going wrong?
AJAX:
$.ajax({
type: "POST",
url: 'feed.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
console.log(data); // logs `{Direction: "O", CardNo: "02730984", SerialNo: 20559303}`
$.each(data, function(key, value) {
// here I want to loop through the returned results - for example
$("#transactionTable").prepend('<tr><td>'+ SerialNo +'</td><td>'+ CardNo +'</td><td>'+ Direction +'</td></tr>');
});
}
});
feed.php
if(isset($_POST['lastSerial']) && $_POST['lastSerial'] == true) {
$query = "SELECT TimeStamp, Direction, CardNo, SerialNo FROM Transactions";
// this query returns approx. 20 results
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$data["Direction"] = $row['Direction'];
$data["CardNo"] = $row['CardNo'];
$data["SerialNo"] = $row['SerialNo'];
}
echo json_encode($data);
}
Also in my PHP, should I be using a while or if statement?
You're using a single $data object and resetting its contents each time. You want to build an array of objects:
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = array(
"Direction" => $row['Direction'],
"CardNo" => $row['CardNo'],
"SerialNo" => $row['SerialNo']
);
}
echo json_encode($data);
Followed by:
success: function(data) {
$.each(data, function(key, value) {
$("#transactionTable").prepend(
'<tr><td>' + value.SerialNo + '</td>' +
'<td>' + value.CardNo + '</td>' +
'<td>'+ value.Direction +'</td></tr>');
});
}
In your feed.php you loop through the results, but on each loop you overwrite the data. Thus, you are only returning the last result from the database to the AJAX request.
Many solutions exist, but you have to do something like
$data["Direction"][] = $row['Direction'];
$data["CardNo"][] = $row['CardNo'];
$data["SerialNo"][] = $row['SerialNo'];
or better:
$data[] = $row;
Since you dont change the key, you can use the last option. With jQuery you can loop over it, and access the data with value.Direction, value.CardNo, value.SerialNo
note: not tested
I am trying to run a SELECT query in PHP and then multiple rows are selected, but I need to fetch them into an array and then use: echo json_encode($array). After That I need to get this array into AJAX.
Here is the PHP code:
$val = $_POST['data1'];
$search = "SELECT * FROM employee WHERE emp_name = :val OR salary = :val OR date_employed = :val";
$insertStmt = $conn->prepare($search);
$insertStmt->bindValue(":val", $val);
$insertStmt->execute();
$insertStmt->fetchAll();
//echo "success";
//$lastid = $conn->lastInsertId();
$i = 0;
foreach($insertStmt as $row)
{
$arr[$i] = $row;
$i++;
}
echo json_encode($arr);
The problem is that I can't get all the lines of this array into AJAX so I can append them into some table. Here is the script:
var txt = $("#txtSearch").val();
$.ajax({
url: 'search.php', // Sending variable emp, pos, and sal, into this url
type: 'POST', // I will get variable and use them inside my PHP code using $_POST['emp']
data: {
data1: txt
}, //Now we can use $_POST[data1];
dataType: "json", // text or html or json or script
success: function(arr) {
for() {
// Here I don't know how to get the rows and display them in a table
}
},
error:function(arr) {
alert("data not added");
}
});
You need to loop over your "arr" data in the success callback. Something along the lines of:
var txt = $("#txtSearch").val();
$.ajax
({
url: 'search.php', //Sending variable emp, pos, and sal, into this url
type: 'POST', //I will get variable and use them inside my PHP code using $_POST['emp']
data: {data1: txt},//Now we can use $_POST[data1];
dataType: "json", //text or html or json or script
success:function(arr)
{
var my_table = "";
$.each( arr, function( key, row ) {
my_table += "<tr>";
my_table += "<td>"+row['employee_first_name']+"</td>";
my_table += "<td>"+row['employee_last_name']+"</td>";
my_table += "</tr>";
});
my_table = "<table>" + my_table + "</table>";
$(document).append(my_table);
},
error:function(arr)
{
alert("data not added");
}
});
You could just return
json_encode($insertStmt->fetchAll());
Also, be sure to retrieve only characters in UTF-8 or JSON_encode will "crash".
Your success function should be like this :
success:function(arr)
{
$.each(arr,function (i,item) {
alert(item.YOUR_KEY);
});
}
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>"));
}
}
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 :)
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"? */ }
});