I have a mysql database, I am using ajax to query it via php, it works fine when only a single row is returned it errors out with this when multiple rows are returned.
"xhr=[object Object]
textStatus=parsererror
errorThrown= SyntaxError: Unexpected token { in JSON at position 221"
Here is the code I am using, any help would be much appreciated.
$('button').click(function(){
event.preventDefault();
var box = document.getElementById('machine');
var rdata;
var id= box.options[box.selectedIndex].text;
$.ajax({
url: 'machine_report.php',
data: 'machine=' + id,
dataType: 'json',
success: function(rdata)
{
var uid = rdata[0];
var date = rdata[1];
var time = rdata[2];
var machine =rdata[3];
var reps = rdata[4];
var sets = rdata[5];
var weight = rdata[6];
var settings = rdata[7];
$('#status').html("<b>id: </b>"+uid+"<b> date: </b>"+date + "<b> Machine: </b>" + machine + "<b> reps: </b>" + reps + "<b> sets: </b>" +
sets + "<b> weight: </b>" + weight + "<b> settings: </b>" + settings);
},
error: function(xhr,textStatus, errorThrown) {
$("#status").html("xhr=" + xhr + "textStatus=" + textStatus + "errorThrown= " + errorThrown);
}
});
});
PHP Code
<?php
require_once("connect.php");
$machine = $_GET['machine'];
$mysql="SELECT * FROM workouts WHERE machine LIKE '$machine' ORDER BY uid DESC";
$result=mysqli_query($con,$mysql);
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$rowCount = mysqli_affected_rows($con);
while($row = mysqli_fetch_array($result)){
$date = $row['date'];
$time = $row['time'];
$machine = $row['machine'];
$reps = $row['reps'];
$sets = $row['sets'];
$weight = $row['weight'];
$settings = $row['settings'];
echo json_encode($row);
}
?>
Your PHP code is outputting one term at time so it will give response in following way.
{name:"abc",age:21}{name:"pqr",age:12}
which is not an valid json if you are passing multiple JSON Objects then you have to create collection of it.(which is simply a array of objects) The valid json for above json will be
[{name:"abc",age:21}{name:"pqr",age:12}]
You can produce this by first catching all the database rows into one array and then pass this array to json_encode
while($row=mysqli_fetch($result)
$rows[] = $row;
echo json_encode($rows);
All the above stuff is to do at the server side.
Now let's look at the client side.
Your Javascript code look fine except for success function because it is written for handling only one object.
Server response returns the data as array of json objects so first you have to iterate the array and then write a code for single object something like this
success:function(data) {
for(var i in data) {
var Row = data[i] // it will contain your single object
//console.log function is used for debugging purpose only you can find more about it by googling.
console.log(Row.name) // you can access it's member like this
// do other stuff such as dom manipulation.
}
}
NOTE: you can also use JQuery's $.each to traverse an array.
Related
Edit:
I can output the table now but the strange thing is, trying to parse the JSON returned from PHP using JS or jQuery methods results in skipping all remaining lines in the debugger with zero output to the browser. Where as not parsing and using it to construct at table works.
Also, trying to .append() the JSON using the parse methods or not to a ` does not work.
I'm so confused right now.
Anyways, the jQuery that worked looks like this making a .post() request, notice I added the 'json' fourth parameter although it might work without it.
$(document).ready(function(){
$('#disease_btn').click(function(){
showDisease();
});
});
function showDisease(){
//var disease = $("#disease-dropdown:selected").text();
//var disease = $("#disease-dropdown:selected").val();
var disease_dropdown = document.getElementById("disease-dropdown")
var disease = disease_dropdown.options[disease_dropdown.selectedIndex].text;
var controller = 'controller.php';
$.post(controller, //url, data, callback, dataype=Json
{
page: 'SpaPage',
command: 'search-disease',
search_term: disease
},
function(disease_json, status){
//#search-results display table
//var disease_obj = JSON.parse(disease_json); this did not work
//var disease_obj = jQuery.parseJSON(disease_json); //this did not work
var disease_obj = disease_json;
//$('#test-out').append(disease_obj); /this did not work
var table = $.makeTable(disease_obj);
$('#search-results').append(table); //this worked!
}, 'json');
//https://stackoverflow.com/a/27814032/13865853
$.makeTable = function(disease_obj){
var table = $('<table border=1>');
var tblHeader = "<tr>";
for (var h in disease_obj[0]) tblHeader += "<th>" + h + "</th>";
$(tblHeader).appendTo(table);
$.each(disease_obj, function(index, value){
var tblRows = "<tr>";
$.each(value, function (key, val){
tblRows += "<td>" + val + "</td>";
});
tblRows += "</tr>";
$(table).append(tblRows);
});
return ($(table));
}
};
That table code I mimicked what I saw here: https://stackoverflow.com/a/27814032/13865853
I sort of get it but still not crystal clear on all of it. I guess it's outputting HTML so I can throw in a class for the table to take advantage of bootstrap.
On the PHP side I do this:
case 'search-disease':
$matches_arr = [];
$disease = $_POST['search_term'];
$matches_arr = search_disease($disease);
//todo: decide to use session or returned arr
if(isset($_SESSION['disease-matches_arr'])){
$matches_arr = $_SESSION['disease-matches_arr'];
}
if(count($matches_arr) > 0) {
//jsonify array here to send back
//https://stackoverflow.com/a/7064478/13865853
//https://stackoverflow.com/a/58133952/13865853
header('Content-Type: application/json');
$disease_json = json_encode($matches_arr);
echo $disease_json;
exit;
}
and then the model.php interaction with database looks like this:
function search_disease($disease_option){
// search DB for substring of question
//add results to an array of strings
//return array of strings or empty array
//
$user_id = -1;
$matches_arr = array();
$sql = "SELECT * FROM diseases
WHERE disease LIKE '%$disease_option%'";
$result = mysqli_query(Db::$conn, $sql);
if (mysqli_num_rows($result) > 0) {
//iterate
while($row = mysqli_fetch_assoc($result)){
//get username
$disease = $row['disease'];
$food = $row['food'];
$en_name = $row['en_name'];
$health_effect = $row['healthEffect'];
$metabollite = $row['metabollite'];
$citation = $row['citation'];
$next_row = array("Disease"=>$disease, "Food"=>$food,
"Name"=>$en_name, "Health Benefits"=>$health_effect, "Metabollite"=>$metabollite,
"Sources"=>$citation);
$matches_arr[] = $next_row;
}
}
$_SESSION['disease-matches_arr'] = $matches_arr;
return $matches_arr;
//https://stackoverflow.com/questions/1548159/php-how-to-sen
So I set a session variable and also return it, still have to decide which way but they are both working.
My questions still remaining are:
Why do the parse methods cause this strange behavior?
How can I just output the JSON to a testing <div>?
If you have to return data from PHP to javascript you must have use json_encode() if data type is array otherwise just return.
To take action with array type data by javascript you have to decode this json data by JSON.parse() function.
Array example
$data = array('carname' => 'TOYOTA','model'=>'ARTYIR500');
echo json_encode($data);
exit;
String example
echo 'lorem ipsum is a simple text';
exit;
A PHP script obtains data from a MySQL database and returns an array to javascript using JSON. I can get the results but I cannot get them to print them out individually.
The PHP code -
header('Content-type:application/json');
$link = #new mysqli(_HOST, _USER, _PASS, _DB); //constants
if(mysqli_connect_errno())
{
//failure
}
else
{
//success
$sqlQuery = "SELECT COL1, COL2 FROM TABLE"; //the query should return two
//columns from every selected row
$mix = array(); //array to return using JSON
$result = $link->query($sqlQuery);
if ($result->num_rows <= 0)
{
//no data
}
else
{
while ($row = $result->fetch_assoc()) //fetch loop
{
$mix["C1"][] = $row['COL1'];
$mix["C2"][] = $row['COL2'];
}
}
$result->free();
// Close connection
$link->close();
}
print json_encode($mix); //this line wont show up in previous code formatting block for some reason.
The Javascript / jQuery code -
$.ajax({ // ajax call
url: 'serv.php', // server page
data: 'fetch=1', //ignore any data
dataType: 'json', // server return type
success: function(data) // on success
{
for (var i in data) {
$('#someDiv').append( i + " = " + data[i] + '<br>');
}
}
});
The output, as expected is like this -
C1 = 1,2
C2 = A,B
What I want to accomplish is to put these data (1,2,A,B) inside a form table element. And to do that I need to pick the every element of C1 or C2 individually.
How can I accomplish this?
I've found the solution myself.
The following ajax call works-
$.ajax({ // ajax call
url: 'serv.php', // server page
data: 'fetch=1', //ignore any data
dataType: 'json', // server return type
success: function(data) // on success
{
for (var i in data["C1"]) {
$('#someDiv').append( i + " = " + data["C1"][i] + '<br>');
}
for (var i in data["C2"]) {
$('#someDiv').append( i + " = " + data["C2"][i] + '<br>');
}
}
});
Instead of accessing the data, I've tried to access the indices inside data. It was so simple.
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"? */ }
});
How can I get the array data from a JSON sent back by my php script?
PHP code:
<?php
//connects to database
include 'connect.php';
$callback = $_GET['callback'];
$query = mysql_query("SELECT * FROM users");
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
$out_string = json_encode($rows);
print $callback.'('.$out_string.');';
?>
The php code above puts all of user table's rows into an array and JSONencodes it. It is then sent back to this script:
$.getJSON(domain_path + 'generate.php?table=' + tbname + '&callback=?', function(data) {
});
How can I display each row from the JSON array sent back?
For example the data will be sent back is:
([{"name":"user1","link":"google.com","approve":"true"},{"name":"user2","link":"yahoo.com","approve":"true"},{"name":"user3","link":"wikipedia.com","approve":"true"}]);
How would I use javascript (jQuery) to display it out like this:
Name: User1 , Link: google.com , Approve:True
Name: User2 , Link: yahoo.com , Approve:True
Name: User3 , Link: wikipedia.com , Approve:True
When you done print $callback.'('.$out_string.');'; you've ruined JSON formatted string. Send back in array instead then loop on through your rows and display data.
$out_string = json_encode(array('callback' => $callback, 'rows' => $rows));
You should do
function(data) {
$.each(data, function(){
$('#result').append('<p>Name:'+this.name+' Link:'+this.link+' Approve'+this.approve+'</p>');
});
}
fiddle here http://jsfiddle.net/hUkWK/
$.getJSON(domain_path + 'generate.php?table=' + tbname + '&callback=?', function(data) {
$.each(data, function(i, item) {
$("#mycontainer").append("<p>Name: " + item.name + "</p>");
$("#mycontainer").append("<p>Link: " + item.link + "</p>");
});
});
I have a project where I've created JSON data for Project Prices/Prices I've gotten this far and pretty much ran into a wall, any help at all would help! I've checked all over the web and on jQuery.getJSON but I wound up getting super confused.
$data = mysql_query("SELECT * FROM xxx")
or die(mysql_error());
$arr = array();
$rs = mysql_query("SELECT product, price FROM products");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"products":'.json_encode($arr).'}';
I need to get the product price and product name into this jquery script
$(document).ready(function() {
/*** CONSTANTS ***/
var KEY = 0;
var VALUE = 1;
/*** DEFINE DATA SETS ***/
var POINTS = [ ["$productA", $PRICE ], ["$productB", $PRICE], ["$productC", $PRICE], ["$productD", $PRICE], ["$productE", $PRICE], ["$productF", $PRICE] ];
var SHIPPING_COSTS = [ ["Pickup", 0], ["Next Day Delivery", 30], ["Same Day Print/Same Day Delivery", 65] ];
for (var i = 0; i < POINTS.length; i++) {
$("#quantity").append("<option value='" + POINTS[i][VALUE] + "'>" + POINTS[i][KEY] + "</option>");
}
for (var i = 0; i < SHIPPING_COSTS.length; i++) {
$("#shipping").append("<option value='" + SHIPPING_COSTS[i][VALUE] + "'>" + SHIPPING_COSTS[i][KEY] + "</option>");
}
$("select.autoUpdatePrice, input.autoUpdatePrice").bind("mousedown click change", function(event) {
Calculate();
});
Calculate();
});
function Calculate() {
var net = parseFloat($("#quantity").val());
/* Calculate the magical # by adding the form fields*/
var designFee = $("#abcDesignFee").attr("checked") ? $("#abcDesignFee").val() : 0.0;
var proofFee = $("#abcProofFee").attr("checked") ? $("#abcProofFee").val() : 0.0;
var MyPrice;
MyPrice = parseFloat( parseFloat(proofFee) + parseFloat(designFee) + net + parseFloat($("#shipping").val()));
$("#DumpHere").html("Your Price: $" + formatNumber(MyPrice));
$("#abcName").val($("#quantity").find(":selected").text() + " " + ProductNamePlural);
$("#abcPrice").val(MyPrice);
}
In your PHP script, can you just json_encode() your array of objects without wrapping it in the string? And instead encode the JSON object like so:
<?php
// your script ...
echo json_encode($arr);
This creates an array of JSON encoded objects:
[{"name":"item 1","price":4.99},{"name":"item 2","price":9.99}]
Make an AJAX request in your JS to query your PHP script, and use jQuery's $.each() and $.parseJSON() methods to iterate over the returned JSON data:
$.post('get_products.php', { data: foo }, function(json) {
$.each($.parseJSON(json), function(key, product) {
console.log(product.name + ' ' + product.price);
});
});
Hope this helps :)
When I was learning - I had exactly the same problem - but it got answered here
What I didn't realise at the time was that you can use object notation (which is the ON of json) to access the data you sent.
If you look at my question and the answer I selected, once you have sent the data back to javascriot you can access it easily. In my example it would be as straitforward as using data.catagory_desc in javascript to find the data that was encoded.