create and modify json string - php

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

Related

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

PHP pass multiple parameters on success in ajax call

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

JSON inside a Loop

The code's that I have is executing fine but after I included the loop that was suggested to me the problem is that the data it retrieves shows only [Object Object]
here is my current progress
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT message_content, username , message_time, recipient FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
$json = array();
if($message_query->rowCount() > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$json[] = $message_array;
}
echo json_encode($json);
}
Here is my JS
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.get('includes/getChat.php', data, function (result) {
var res = $([]);
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
$("#clog").html(res);
}, 'json');
}
res is a jQuery object (as created by $([]) and populated by res.add
You're outputting an object into a string context (HTML) so of course it will result in [object Object] - that's just how objects are converted to string.
Consider... not using jQuery where it's not needed.
var res = [], out = document.getElementById('clog'), div;
while(out.firstChild) out.removeChild(out.firstChild);
$.each(result[0], function(key, value) {
div = document.createElement("div");
div.appendChild(document.createTextNode(value});
res.push(div);
out.appendChild(div);
}
First of all check your input array in php side. And show it. Second step is to RE-CHECK manual on http://www.php.net/manual/en/function.json-encode.php and look on depth param.
JS side won't help if you sending wrong params/array/json.

Pass an array from PHP (from DB) to JS?

My goal is to get - finally - a 'normal' JS array in my js-file. Maybe json is the way to do it - but the elements in the array should remain in order and its just an array of three arrays: [["1","2","3"]["1","2","3"]["1","2","3"]].
my php-query (it does produce the array above - I mean: it does work):
// this is file 'dbquery.php'
<?php
include_once('../resources/init.php');
$query = mysql_query("SELECT `useranswer`, `solution`, `time` FROM `results`");
$qlen = mysql_query("SELECT COUNT(1) FROM `results`");
$len = mysql_result($qlen, 0);
$user_a = array();
$solu_a = array();
$time_a = array();
while($row = mysql_fetch_assoc($query)){
array_push($user_a, $row['useranswer']);
array_push($solu_a, $row['solution']);
array_push($time_a, $row['time']);
}
$cd_result = array($user_a, $solu_a, $time_a);
$cd_answer = json_encode($cd_result);
echo $cd_answer;
?>
I assume json is not the adequat form here.
Now all I want is an js-array in my js-file like : my_array = [[1,2,3],[1,2,3],[1,2,3]]
But I terribly fail to achieve this.
With $.ajax() I don't know how to get ALL the data at once without 'data: ' each single value. I just want to "catch" my echo from the php - how to do so?
do like this
<?php
include_once('../resources/init.php');
$query = mysql_query("SELECT `useranswer`, `solution`, `time` FROM `results`");
$qlen = mysql_query("SELECT COUNT(1) FROM `results`");
$len = mysql_result($qlen, 0);
$user_a = array();
$solu_a = array();
$time_a = array();
while($row = mysql_fetch_assoc($query)){
array_push($user_a, $row['useranswer']);
array_push($solu_a, $row['solution']);
array_push($time_a, $row['time']);
}
$cd_result = array($user_a, $solu_a, $time_a);
$cd_answer = json_encode($cd_result);
echo json_encode ($cd_answer); // encode in json format
?>
and in ajax:
$.ajax({
type: "GET",
url: "test.php",
dataType: "json",
data : {anything : 1},
success:function(data){
var x = jQuery.parseJSON( data ); // parse the answer
// if you want in an array format then just use eval()
x = eval(x);
alert(x);
}
});
If you just need a PHP variable passed to JS when the page is rendered, then do this in your PHP view layer:
<script type="text/javascript">
var myInt = <?php echo $int ?>;
var myString = '<?php echo $string ?>';
var myArray = <?php echo json_encode($array) ?>;
// All these JS variables can now be used here
</script>
Obviously, you need to ensure that the variables are valid - so in the case of the int, if it is null or undefined, you need to ensure you don't render the assignment - otherwise it will produce a client-side error.

jQuery $.post not returning JSON data

I've read multiple similar posts on this, and my code seems to match the suggestions, but still no data returned.
Here's my JS:
$.post('php/get_last_word.php', { user_id : userID },
function( data ) {
currentLanguage = data.language_id;
currentWord = data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
},'json');
And the relevant php:
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$encoded = json_encode($row);
echo $encoded;
}
And the resulting log:
Connected successfully{"language_id":"1","word_id":"1"}
So the json array is being echoed, but it's not ending up in data, because currentLanguage and currentWord are not being populated. Is this a problem with asynchronicity? Or something else?
Make sure you have a valid json coming back to your variable from your PHP script
IF your json object is like this,
{"language_id":"1","word_id":"1"}
You can access the values like this
currentLanguage = data.language_id;
currentWord = data.word_id;
Example JsFiddle http://jsfiddle.net/NuS7Z/8/
You can use http://jsonlint.com/ to verify your jSon is in correct form or not.
Specifying json as the data type value in your post request will make sure the reponse is coming back as json format to the success callback.
$.post('php/get_last_word.php',{user_id:userID}, dataType:"json",function(data){
currentLanguage = data.language_id;
currentWord = data.word_id;
});
You can also use getJson to simply get json data. getJson is a shorthand of ajax Call with datatype as json
http://api.jquery.com/jQuery.getJSON/
Try changing your JS to:
$.getJSON('php/get_last_word.php', { user_id : userID },
function( response ) {
if (response.success) {
currentLanguage = response.data.language_id;
currentWord = response.data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
} else {
alert('Fail');
}
});
and your PHP to:
<?php
$success = false;
$data = null;
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$success = true;
$data = $row;
}
// I generally format my JSON output array like so:
// Response
header('Content-Type: application/json');
echo json_encode(array(
'success' => $success,
'data' => $data
));
?>
That way its more organized and don't forget to set the content type.
Hope that helps.

Categories