I have a json_encode in my php script which seems to fail the Jquery side of things if the json_encode is called inside a while loop.
When i view the result in a browser window other than the page i need the result in i can see that it does actually does work.
For example:
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$data = array("id" => $id,
"title" => $title,
"success" => true
);
echo json_encode($data); // Inside the While Loop
}
and the output in the browser is:
{"id":"15","title":"Advanced Booking Examples","success":true}
{"id":"14","title":"Advanced Booking Fields","success":true}
{"id":"11","title":"Add New Driver","success":true}
{"id":"10","title":"Registering a Driver \/ Add New Vehicle","success":true}
{"id":"8","title":"Dispatch Controls","success":true}
{"id":"7","title":"Troubleshooting Driver Device Checklist","success":true}
{"id":"6","title":"Requirements Checklist","success":true}
In the jQuery response this is actually blank but if I leave the echo json_encode($data); just outside the while loop the jQuery picks up the response, however only 1 record - being the last record in the loop.
I need the jQuery to pick up all results from the loop.
Here's the JS
$.ajax({ // Send it off for prcessing
type: "POST",
dataType: 'json',
url: "includes/auto_suggest.php",
data: {
q: inputString
},
success: function (result) {
if (result.success) {
var id = result.id;
var title = result.title;
$('#auto_id').append("<input type='text' class='hideid' id='hideid_" + id + "' value='" + id + "'/>");
$('#auto_title').prepend("<p>" + title + "</p>");
}
}
});
Any ideas?
Thanks in advance
JSON needs to all be on one array or object. You need to append each row to an array, then json_encode that.
$data = array();
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$data[] = array(
"id" => $id,
"title" => $title,
"success" => true
);
}
echo json_encode($data);
Then in JavaScript, you will have an array of objects, that you can loop through.
$.ajax({ // Send it off for prcessing
type: "POST",
dataType: 'json',
url: "includes/auto_suggest.php",
data: {
q: inputString
},
success: function (result) {
$.each(result, function(){
if (this.success) {
var id = this.id;
var title = this.title;
$('#auto_id').append("<input type='text' class='hideid' id='hideid_" + id + "' value='" + id + "'/>");
$('#auto_title').prepend("<p>" + title + "</p>");
}
});
}
});
Well, you are not sending valid JSON.
Store the objects in an array and then json_encode that array after the loop.
$data = array();
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$data[] = array("id" => $id,
"title" => $title,
"success" => true
);
}
echo json_encode($data);
You then need to change your JavaScript code to properly handle an array instead of an object. Since nobody here knows what exactly you intend to do you'll have to do that on your own or provide more information.
You need to add the resulting data to an array and call json_encode once, like so:
$data = array();
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$data[] = array("id" => $id,
"title" => $title,
"success" => true
);
}
echo json_encode($data);
This will change your outputted JSON (since currently your JSON is invalid), which you now have to loop over in your jQuery callback.
The JSON that gets returned when that line is inside the loop isn't valid as a whole. It's multiple JSON strings together. You would need to split them up.
I would make an array and inside the loop add each $data to that array. Then, outside of the loop, json_encode it and echo it. This will create one JSON string to return to your javascript.
Perhaps...
$data = array();
while( WHATEVER ){
// other code
$data[] = array('id' => $id, 'title' => $title, 'success' => true);
}
echo json_encode($data);
Store all your information in one array, then encode that array.
You can't pass multiple objects like that to jQuery. Put the in array and print the array of objects when the while loop is done.
You need to encode json outside the while loop. it will return single json, which is actually correct
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$data[] = array("id" => $id,
"title" => $title,
"success" => true
);
}
echo json_encode($data);
Your JSON output is not valid. Try this complete code (EDIT):
$result = Array();
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$data = array("id" => $id,
"title" => $title,
);
$result[] = $data;
}
echo json_encode(Array('data'=>$result,'success'=>true)); // Outside the While Loop
And in your javascript code
$.ajax({ // Send it off for prcessing
type: "POST",
dataType: 'json',
url: "includes/auto_suggest.php",
data: {
q: inputString
},
success: function (results) {
if (results.success) {
for(var i in results.data) {
var result = results.data[i];
var id = result.id;
var title = result.title;
var $newfield = $("<input type='text' class='hideid' id='hideid_" + id + "' value='" + id + "'/>");
$newfield.prepend("<p>" + title + "</p>");
$('#auto_title').append($newfield);
}
}
}
});
Related
I am doing this ajax call
<script>
function reserveSeat(showID) {
$.ajax({
url: 'reserve_seat.php',
type: 'post',
data: { "showID": showID}
}).done(function(data) {
var booked_seats = JSON.parse( data1, data2, data3 ); //get multiple values
console.log(booked_seats);
});
};
</script>
and in my reserve_seat.php I want to pass multiple echo
$query = "SELECT * FROM `seats` WHERE show_id='" . $_POST['showID'] ."'";
$result = mysql_query($query);
if($result){
$booked_seats = array();
while($row = mysql_fetch_array($result)){
array_push ($booked_seats, array($row['id'], $row['row_no'], $row['col_no']));
}
echo json_encode($booked_seats, var2, var3); //echo multiple variable
} else {
echo mysql_error();
}
What I want is commented in the above code. How can I do this?
Change your echo line to :
echo json_encode(array("booked_seats" => $booked_seats, "var2" => $var2, "var3" => $var3);
And in your ajax
function(data) {
var arr = JSON.parse( data );
var booked_seats = arr["booked_seats"];
console.log(booked_seats);
}
Why don't you just print the encoded JSON output?
Not to mention json_encode() requires an array as said by other posters
json_encode() PHP Manual
use array in side
json_encode(array($booked_seats, var2, var3)).
i know how to validate form using it for 1 field. But i would like enter code and take back multiple values from my db. exmp: price, quantity etc.
It is posible to do using ajac?
php file:
$sql = "SELECT * FROM database WHERE code='$field_code'";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$query=sqlsrv_query($conn, $sql, $params, $options);
$row = sqlsrv_fetch_array($query);
if ($row == true)
{
$code = ($row['code']);
$life = ($row['life']);
$agree = ($row['agree']);
}
echo $code;
echo $life;
echo $agree;
?>
And script is:
$("#field_code").change(function() {
$("#message").html("<img src='pictures/ajax_loader.gif' width='26px' height='26px' /> checking...");
var data1 = $("#field_code").val();
$.ajax({
type: 'POST',
url: 'validation.php',
data: $('form').serialize(),
success: function validate(code) {
if (data == ? ) {
to do something
} else {
to do something
}
How to receive all 3 values from php file?
}
})
you need to use json encode for this
$values[]= array('code'=>$row['code'],
'life'=>$row['life'],
'agree'=>$row['agree']);
echo json_encode($values);
and in ajax
var data = jQuery.parseJSON(data);
and access values like data.life,data.code and data.agree
I am trying to populate a selected menu when the page is created but there are no options that show.
$(document).ready(function() {
$.ajax('patientlist.php', function(data){
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option value="' + data[i].patient_id + '">' + data[i].patient_firstname + data[i].patient_lastname + '</option>';}
$('#patientselect').append(html);
});
});
my patientlist.php
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname` FROM `patients` WHERE `company_id` = " . $user_data['company_id'] . " ORDER BY `patient_firstname`");
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
echo json_encode( $data );
}
My result from the php page
[{"patient_id":"9","patient_firstname":"Adam","patient_lastname":"Steve"}] etc...
Really appreciate any help, been stuck on this for a week!
So, posting again.
First of all, you should put the echo json_encode( $data ); out of your while loop
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode( $data );
Second, your $ajax syntax isn't correct, change this to $.post and tell the $.post request you are expecting a 'json' response from patientlist.php
$(document).ready(function() {
$.post('patientlist.php', {}, function(data){
/* code */
}, 'json'); // <= set data type json here
});
When retrieving a valid json string, you can iterate over data by using the $.each method
$.each(data, function(index, patient) {
console.log(patient.patient_id); // or use patient['patient_id']
});
At least you will now receive a valid request.
Noticing your HTML, do not use .append if it is not a DOM element, you are just building html elements as a string, so use instead
$('#patientselect').html(html);
I have an AJAX function as so:
function admin_check_fn(type)
{
//$("#notice_div").show();
//var allform = $('form#all').serialize();
$.ajax({
type: "POST",
//async: false,
url: "<?php bloginfo('template_url'); ?>/profile/adminquery_check.php",
data: { type: type },
//data: 'code='+code+'&userid='+userid,
dataType: "json",
//dataType: "html",
success: function(result){
var allresult = result.res
$('#result').html( allresult );
alert(allresult);
//$("#notice_div").hide();
}
})
}
And server-side:
$queryy="SELECT * FROM wp_users";
$name = array();
$resultt=mysql_query($queryy) or die(mysql_error()); ?>
<?php while($rowss=mysql_fetch_array($resultt)){
$name = $rowss['display_name'];
}
echo json_encode( array(
"res" => array($rowss['display_name']),
"fvdfvv" => "sdfsd"
)
);
Basically for some reason it is not displaying all of the returned values from the query to the users table in the database. It works when I query another table with just one entry in it, so im thinking it could be something to do with the fact there is an array it is not parsing correctly?
Just wondered if anyone else has came accross this problem?
Thanks
Your ajax success is treating the returned data as html but it is json.
var allresult = result.res
/* assumes allResult is html and can be inserted in DOM*/
$('#result').html( allresult );
You need to parse the json to create the html, or return html from server
Also php loop:
$name = $rowss['display_name'];
Should be more like:
$name[] = $rowss['display_name'];
You always overwrite the name:
<?php while($rowss=mysql_fetch_array($resultt)) {
$name = $rowss['display_name'];
}
But this part is not within your loop:
"res" => array($rowss['display_name']),
Therefore you only get one result (the last one).
Smamatti has a good point.
To fix this:
<?php
$query = "SELECT * FROM wp_users";
$names = array();
$result = mysql_query($query) or die(mysql_error());
while( $rows = mysql_fetch_array( $result ) ){
$names[] = $rows['display_name'];
}
echo json_encode( array(
"res" => $names,
"fvdfvv" => "sdfsd"
)
);
Hi searched through the questions here, but couldn't find anything. I'm new at writing PHP and jQuery, so bear with me.
What I'm trying to do is send an ajax request using jQuery to my script which runs a mysql query on data from my database and serializes it into the JSON format using php's json_encode. The response is then parsed with the available json2.js script. All of this works fine, but I'd also like to return more data other than just JSON from this script.
mainly, i'd like to also echo the following line before the json_encode:
echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
however, my jQuery is evaluating the entire response during the ajax success, making the json.parse function fail due to the script's return being in an invalid format.
success: function(data) {
//retrieve comments to display on page by parsing them to a JSON object
var obj = JSON.parse(data);
//loop through all items in the JSON array
for (var x = 0; x < obj.length; x++) {
//Create a container for the new element
var div = $("<div>").addClass("bubble").appendTo("#comments");
//Add author name and comment to container
var blockquote = $("<blockquote>").appendTo(div);
$("<p>").text(obj[x].comment).appendTo(blockquote);
var cite = $("<cite>").appendTo(div);
$("<strong>").text(obj[x].name).appendTo(cite);
$("<i>").text(obj[x].datetime).appendTo(cite);
}
$("#db").attr("value", '' + initialComments + '');
}
does anyone know how i can return the html line as well as the json_encode to use this script for more than just json population?
thankyou, this website has been wonderful in answering my noob questions.
my php:`
for ($x = 0, $numrows = mysql_num_rows($result); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($result);
$comments[$x] = array("name" => stripslashes($row["name"]), "comment" => stripslashes($row["comment"]), "datetime" => date("m/d/Y g:i A", strtotime($comment['datetime'])));
}
//echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
$response = json_encode($comments);
echo $response;`
Don't echo the line, save it in a variable. Construct a simple array
$response = array(
'html' => $the_line_you_wanted_to_echo,
'jsobject' => $the_object_you_were_going_to_send_back
); and send that back ( via json_encode ) instead.
Also, you don't need json2.js, jQuery has an excellent JSON parser.
you can load like this $.get( 'your/url', { params : here }, success, 'JSON' );
Changed to match your newly introduced iteration.
for ($x = 0, $num_rows = mysql_num_rows($result); $x < $num_rows; $x++) {
$row = mysql_fetch_assoc($result);
$comments[$x] = array(
"name" => stripslashes($row["name"]),
"comment" => stripslashes($row["comment"]),
"datetime" => date("m/d/Y g:i A", strtotime($comment['datetime']))
);
}
$html = "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
echo json_encode(array( 'comments' => $comments, 'html' => $html ));
then, in your javascript, you have
function success( parsedObject ){
parsedObject.html; // "<h1 style..."
parsedObject.comments; // an array of objects
parsedObject.comments[0].name
+ " on " + parsedObject.comments[0].datetime
+ " said \n" + parsedObject.comments[0].comment; // for example
}
As said above just put all the data you want to get back in an array and encode that.
<?php
echo json_encode(array(
'html' => $html,
'foo' => $bar,
'bar' => $baz
));
?>
Also as said you don't need json2.js. You can parse JSON data with any of jQuery's ajax functions by specifying the data type as json.
$.ajax({
type: 'POST',
url: 'path/to/php/script.php',
dataType: 'json',
data: 'foo=bar&baz=whatever',
success: function($data) {
var html = $data.html;
var foo = $data.foo;
var bar = $data.bar;
// Do whatever.
}
});
EDIT Pretty much what Horia said. The only other variation I could see is if you wanted everything in the same array.
For example:
PHP:
<?php
// You have your comment array sent up as you want as $comments
// Then just prepend the HTML string onto the beginning of your comments array.
// So now $comments[0] is your HTML string and everything past that is your comments.
$comments = array_unshift($comments, $your_html_string);
echo json_encode($comments);
?>
jQuery:
$.ajax({
type: 'POST',
url: 'path/to/php/script.php',
dataType: 'json',
data: 'foo=bar&baz=whatever',
success: function($comments) {
// Here's your html string.
var html = $comments[0];
// Make sure to start at 1 or you're going to get your HTML string twice.
// You could also skip storing it above, start at 0, and add a bit to the for loop:
// if x == 0 then print the HTML string else print comments.
for (var x = 1; x < $comments.length; x++) {
// Do what you want with your comments.
// Accessed like so:
var name = $comments[x].name;
var comment = $comments[x].comment;
var datetime = $comments[x].datetime;
}
}
});
You might be interested in jLinq, a Javascript library that allows you to query Javascript objects. A sample query would be:
var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();
jLinq supports querying nested objects and performing joins. For example:
var results = jLinq.from(data.users)
.join(data.locations, //the source array
"location", //the alias to use (when joined)
"locationId", // the location id for the user
"id" // the id for the location
)
.select(function(r) {
return {
fullname:r.first + " " + r.last,
city:r.location.city,
state:r.location.state
};
});