PHP pass multiple parameters on success in ajax call - php

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)).

Related

create and modify json string

This is my first time, that I am working with json.
This is the situation:
I get data via php from my mysql database and store this into a php array:
$statement = $mysqli->prepare("SELECT chatToken, lastMessageID FROM chat")
$statement->execute();
$result = $statement->get_result();
while($row = $result->fetch_object()) {
$chatData[$row->chatToken] = $row->lastMessageID;
}
Now I would like to get this in a jquery function:
I tried this:
var chatData = '<? echo json_encode($chatData); ?>'
myFunction(chatData)
function myFunction(chatData) {
console.log(chatData)
// OUTPUT: {"tgv5pxfjsDGXA3JcEYVM":88,"a9gxNZ7HzfcJXQsWCtAp":99}
$.ajax({
type: "POST",
url: "getData.php",
data: 'chatData='+chatData,
dataType: 'json',
}).done(function(result) {
console.log(result);
// Please look the Picture below for output
})
}
Output of console.log(result)
getData.php
<?php
$chatData = json_decode($_POST['chatData']);
$message = array();
foreach($chatData AS $chatToken => $lastMessageID) {
$statement = $mysqli->prepare("SELECT * FROM `messages` WHERE `chatToken` = ? AND `ID` > ?")
$statement->bind_param("ss", $chatToken, $lastMessageID);
$statement->execute();
$result = $statement->get_result();
while($row = $result->fetch_object()) {
$message[] = array(
"lastMessageID" => $row->ID,
"chatToken" => $row->chatToken,
);
}
$statement->close();
}
echo json_encode($message);
?>
So far so good.
But now I would like to replace / update my var chatData:
{"tgv5pxfjsDGXA3JcEYVM":88,"a9gxNZ7HzfcJXQsWCtAp":99}
with values from the result. Finally it have to be:
{"tgv5pxfjsDGXA3JcEYVM":188,"a9gxNZ7HzfcJXQsWCtAp":99}
How can I realize it?
As chatData is JSON (a string), you can:
parse it into an object JSON.parse
make the change
convert it back to a string JSON.stringify
// result from ajax call, jquery converts this from the php json to an object/array
var result = [{chatToken:"tgv5pxfjsDGXA3JcEYVM",lastMessageID:188}];
// string from `var chatData = <?php ...` as JSON
var chatData = '{"tgv5pxfjsDGXA3JcEYVM":88,"a9gxNZ7HzfcJXQsWCtAp":99}';
// convert string to object
var data=JSON.parse(chatData);
// use the first result array ([0]) chatToken to update chatData
data[result[0].chatToken] = result[0].lastMessageID;
// convert back to JSON (string)
chatData = JSON.stringify(data);
// show result
console.log(chatData);
In your case, I'd recommend converting chatData to an object at the start
var chatData = JSON.parse('<? echo json_encode($chatData); ?>');
and then using it as an object, then convert to json(string) only as needed (in the ajax post)
data: 'chatData='+JSON.stringify(chatData),

json_encode for more than 2 arrays

I have 2 tables to be retrieved from database with 2 different queries and needs to be encoded in json and send to ajax.The issue is I am not able to pass 2 json's to ajax .
I have tried with echo json_encode(array($data1,$data2)); but it is not working.
//My php code
$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
$data1['value1'] = $row['value1'];
$data1['value2'] = $row['value2'];
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
$data2['value2'] = $row['value2'];
$data2['value3'] = $row['value3'];
}
echo json_encode(array($data1,$data2));
//My AJAX code
$(document).ready(function(){
$('#Form').submit(function(e){
e.preventDefault(); // stops the form submission
$.ajax({
url:$(this).attr('action'), // action attribute of form to send the values
type:$(this).attr('method'), // method used in the form
data:$(this).serialize(), // data to be sent to php
dataType:"json",
success:function(data){
//main
alert(data.value1);
},
error:function(err){
alert(err);
}
});
});
});
Kindly help in solving this issue.Thanks in advance
In PHP:
echo json_encode(array($data1, $data2));
In AJAX:
var data1 = data[0];
var data2 = data[1];
$.each(data1, function() {
console.log(this.value1 + ',' + this.value2);
});
$.each(data2, function() {
console.log(this.value2 + ',' + this.value3);
});
EDIT:
After a whole year, I just noticed that the initial PHP code was wrong, because the loop for the sql result would overwrite each time the values of the array. So, the correct one is this:
$query = $db->query("select * from table1 where valu1='".$value1."'");
while ($row = $query->fetch_assoc()) {
$data1[] = array('value1' => $row['value1'], 'value2' => $row['value2']);
}
$query = $db->query("select * from table2 where value2='".$value2."' ");
while ($row = $query->fetch_assoc()) {
$data2[] = array('value2' => $row['value2'], 'value3' => $row['value3']);
}
echo json_encode(array($data1,$data2));
Your code is fine, you just have to handle the two arrays within your success function:
success: function(data){
var object1 = data[0];
var object2 = data[1];
// Do whatever you like to do with them
}

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

receive multiple values from db using ajax

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

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

Categories