How can I send looped data via json? - php

I send data via json. It is working well:
$.ajax({
url: "json.php",
type: "POST",
dataType: "json",
encode: true,
data: {},
success: function (data) {
$(".blue").html(data.blue);
$(".red").html(data.red);
}
});
json.php
$array['blue'] = "blue array";
$array['red'] = "red content";
echo json_encode($array);
My problem is now, that instead of..
blue array
...I want to send:
$pdo = $db->query('SELECT * FROM data;');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo "<li>".$row['name']."</li>";
}
is this possible?

Here's an extremely basic example:
<?php
$json = array(
'blue' => '',
'red' => 'Empty red content or whatever'
);
$pdo = $db->query('SELECT * FROM data;');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
$json['blue'].= "<li>".$row['name']."</li>";
}
echo json_encode($json);
Not sure what logic you would use to actually populate red but you can work it into the while loop or whatever.

Related

UNDEFINED response in getting the return multiple values from PHP to AJAX?

I want to get the return multiple value from my php to ajax, but the problem is I always get a Undefined response from my page. I tried different ways but still getting the same problem
here is my code...
addSizeandPrice.php
if($selectResult){
while($data = mysqli_fetch_assoc($selectResult)){
$dataprice = $data['Price'];
$datasize = $data['CoffeeSize'];
echo json_encode (array(
'size' => $datasize,
'price' => $dataprice,
));
}
}
billingCoffee.php
$.ajax({
url: "addSizeandPrice.php",
type: "POST",
data: {coffeename: txtCoffeeName, sizes: cmbSizes, price: txtPrice},
datatype: "json",
success: function (result){
alert(result.size);
alert(result.price);
}
});
Any ideas and suggestions would be greatly appreciated. . :)
Your json_encode is incorrect. If your DB query returns MULTIPLE rows, then you're sending out MULTIPLE separate json-encoded strings, which is a syntax error. e.g.
{"size":"val1","price":"val1"}{"size":"val2","price":"val2"}
^^--illegal/invalid javascript
You should have:
$arr = array();
while($data = mysqli_fetch_assoc($selectResult)){
$dataprice = $data['Price'];
$datasize = $data['CoffeeSize'];
$arr[] = array(
'size' => $datasize,
'price' => $dataprice,
)
}
echo json_encode($arr);
which would produce:
[{"size":"val1","price":"val1"},{"size":"val2","price":"val2"}]
which is valid javascript/json, and then
success: function(response) { console.log(response[0].size); }

How to pass mysql result as jSON via ajax

I'm not sure how to pass the result of mysql query into html page via ajax JSON.
ajax2.php
$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
echo $row['Name']; //How to show this in the html page?
echo $row['PostUUID']; //How to show this in the html page?
$row2[] = $row;
}
echo json_encode($row2);
How to pass the above query result to display in the html page via ajax below?
my ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
//how to retrieve the php mysql result here?
console.log(data); // this shows nothing in console,I wonder why?
}
});
return false;
});
Your json encoding should be like that :
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
And in your javascript part, you don't have to do anything to get back your data, it is stored in data var from success function.
You can just display it and do whatever you want on your webpage with it
header('Content-Type: application/json');
$row2 = array();
$result = array();
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while( $row = $statement->fetch())
{
echo $row['Name'];//How to show this in the html page?
echo $row['PostUUID'];//How to show this in the html page?
$row2[]=$row;
}
if(!empty($row2)){
$result['type'] = "success";
$result['data'] = $row2;
}else{
$result['type'] = "error";
$result['data'] = "No result found";
}
echo json_encode($row2);
and in your script:
$("form").on("submit",function() {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
if(data.type == "success"){
for(var i=0;i<data.data.length;i++){
//// and here you can get your values //
var db_data = data.data[i];
console.log("name -- >" +db_data.Name );
console.log("name -- >" +db_data.PostUUID);
}
}
if(data.type == "error"){
alert(data.data);
}
}
});
return false;
});
In ajax success function you can use JSON.parse (data) to display JSON data.
Here is an example :
Parse JSON in JavaScript?
you can save json encoded string into array and then pass it's value to javascript.
Refer below code.
<?php
// your PHP code
$jsonData = json_encode($row2); ?>
Your JavaScript code
var data = '<?php echo $jsonData; ?>';
Now data variable has all JSON data, now you can move ahead with your code, just remove below line
data = $(this).serialize() + "&" + $.param(data);
it's not needed as data variable is string.
And in your ajax2.php file you can get this through
json_decode($_REQUEST['data'])
I would just..
$rows = $statement->fetchAll(FETCH_ASSOC);
header("content-type: application/json");
echo json_encode($rows);
then at javascript side:
xhr.addEventListener("readystatechange",function(ev){
//...
var data=JSON.parse(xhr.responseText);
var span=null;
var i=0;
for(;i<data.length;++i){span=document.createElement("span");span.textContent=data[i]["name"];div.appendChild(span);/*...*/}
}
(Don't rely on web browsers parsing it for you in .response because of the application/json header, it differs between browsers... do it manually with responseText);

DataType JSON doesn't work with php

Here is my HTML
<input x-webkit-speech id="mike" name="string" style="position: relative;" disabled lang="ru" />
Then when the field is changes,
This function executes
$(document).ready(function(){
$('#mike').bind('webkitspeechchange',function()
{
a= $(this).val();
recognizeAjax(a);
}) ;
});
function recognizeAjax(string) {
var postData ="string="+string;
$.ajax({
type: "POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php',
success: function(data) {
// 'data' is a JSON object which we can access directly.
// Evaluate the data.success member and do something appropriate...
if (data.success == true){
alert(data.message);
}
else{
alert(data.message+'hy');
}
}
});
And here is my PHP (please don't say anything about the way i connect to DB it doesn't metter right now)
<?php header('Content-type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', true);
// Here's the argument from the client.
$string = $_POST['www'];
$quest=1;
$con=mysql_connect("localhost", "******", "*********") or die(mysql_error());
mysql_select_db("vocabulary", $con) or die(mysql_error());
mysql_set_charset('utf8', $con);
$sql="SELECT * FROM `text` WHERE event_name = 'taxi' AND quest_id = '".$quest."'";
$result = mysql_query($sql);
mysql_close($con);
while($row = mysql_fetch_array($result))
{
if ($string == htmlspecialchars($row['phrase']))
{
$data = array('success'=> true,'message'=>$row['phrase']);
// JSON encode and send back to the server
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
} else {
// Set up associative array
$data = array('success'=> false,'message'=>'aint no sunshine');
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
}
}
When i change the dataType to "text" in the javasript function - i receive an alert with 'undifiend'
But when chenge it to 'json'.. i receive nothing (chrome debuger see nothing)
I set up all encodings to this article http://kunststube.net/frontback/
And i checked it with simple POST requests - it works perfect.
The problem with json.
Any suggestions?
Thanks
Just remove the datatype="json" bit and change the data bit to data: { "string": string }
After that try a print_r(json_decode($_POST['string']));. I'm quite sure that will get you your data.
And indeed remove your beforeSend callback.
I think the prob is the code var postData ="string="+string;
jQuery expects this to be a proper JSON Object.
Next: $string = $_POST['www']; takes a parameter named "www" from your post request, but the name above is "string" (at least).
Try either (!) this:
var getData ="www="+string;
$.ajax({
type: "POST",
dataType: "json",
data: null,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php?' + getData,
and server:
$string = $_GET['www'];
or this (php)
$string = $_POST['string'];
$stringData = json_decode($string);
// catch any errors ....
$quest=$stringData[....whatever index that is...];

jQuery AJAX call to a database query

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"
)
);

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