Get JSON data from ajax call to PHP page through POST - javascript

I want to get some data from a form making AJAX call. I am getting the data as a string in my PHP page. The string looks like
'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''
Now I want to convert this entire string into array which would look like
["fname"] => "abc",
["lname"] => "xyz"... and so on
The ajax call is like below:
fname = $("#form-fname").val();
lname = $("#form-lname").val();
email = $("#form-username").val();
pwd = $("#form-password").val();
phone = $("#form-phone").val();
gender = $("#form-gender").val();
dob = $("#form-dob").val();
var user = {"fname":fname,"lname":lname,"email":email,"pass":pwd,"phone":phone,"gender":gender,"dob":dob};
$.ajax({
type: "POST",
url: "doRegistration.php",
data: user
})
.done(function( msg ) {
window.location.href = "../profile.php";
})
.fail(function(msg) {
sessionStorage.setItem("success","0");
window.location.reload();
});
And here is my PHP code:
$content = file_get_contents("php://input");
file_put_contents("log1.txt",$content); //This produces the string I get above
Now I try to convert the string into array as above
$dec = explode(",",$content);
$dec1 = array();
for($i=0;$i<count($dec);$i++)
{
$dec1[i] = substr($dec[i],strpos($dec[i],":"));
}
//After this $dec1 is empty and count($dec1) gives 0.
But this does not give me the required array. I have checked several answers here, but they do not solve my issue. I tried to google but did not find any resolution. Is there something wrong in the code? Kindly help. Thanks in advance.

Change quotes and add braces. Then you can decode resulting json
$string = "'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''";
print_r(json_decode('{' . str_replace("'", '"', $string) . '}', true));
result
Array
(
[fname] => abc
[lname] => xyz
[email] =>
[pass] =>
[phone] =>
[gender] =>
[dob] =>
)

In your code above, you are using the index of the for loop for the key of the array. If you are trying to archive (I believe it is called dictionary in Java). You can try the following code:
<?php
$string = "'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''";
$pieces=explode(',',$string);
foreach($pieces as $array_format){
list($key,$value) = explode(':',$array_format);
$array[$key]=$value;
}

Related

Replace JSON array quotes with brackets [

I have a JSON array being passed form PHP and it looks like this:
[{from: "2019,09,14", to: "2019,09,14"}]
and I need it to look like this:
[{from: [2019, 9, 14], to: [2019, 9, 17]}]
here is my code thus far:
function getPricingDateRanges() {
var city = document.getElementById("pricingcityselect").value;
$.ajax({
url: 'getpricingdaterangepicker.php?city=' + city, // Change this to the uri of your file
method: 'GET', // Use the GET method
dataType: 'json', // Expect a JSON response
success: function(response) { // What will happen when the request succeeds
var darray = [{from:[2019,9,14], to:[2019,9,17]}];
console.log(response);
console.log(darray);
}
});
}
Added code from my PHP:
<?php
include 'dbconfig.php';
$city = ($_GET['city']);
$sql="SELECT start_date, end_date FROM date_ranges WHERE city='" . $city . "'";
$result = mysqli_query($conn,$sql);
// Create empty array.
$date_ranges = array();
// Add every row to array;
while($row = mysqli_fetch_array($result)) {
// Create an associative array to store the values in.
// This will later be a JavaScript Object.
$from = new DateTime($row['start_date']);
$ffrom = $from->format('Y,m,d');
$to = new DateTime($row['end_date']);
$fto = $from->format('Y,m,d');
array_push($date_ranges, array(
'from' => $ffrom,
'to' => $fto
));
}
// Send the $date_ranges as JSON.
$json = json_encode($date_ranges); // '[{"start": "2019-08-18", "end": "2019-08-19"}]'
echo $json;
?>
First, it's important to point out that the "JSON" you've included is not JSON. It is neither a string, nor are the property names quoted.
However, if this is actually the input you're dealing with, you can loop through the items, split the from and to values on ,, and use .map(Number) to convert them to integers.
const arr = [{from: "2019,09,14", to: "2019,09,14"}];
//Helper function to split on comma, convert items to numbers
const toIntegerArray = str => str.split(",").map(Number);
const result = arr.map(({from,to}) => ({
from: toIntegerArray(from),
to: toIntegerArray(to)
}));
console.log(result);
Parse JSON till the point with "2019,09,14".
then "2019,09,14" convert to array of numbers by:
"2019,09,14".split(',').map(el => parseInt(el, 10))

Read JSON returned by PHP in Javascript

I want to select some content from the database and return it to the javascript. There are several rows returned by the database. I tried this with JSON and also get a result, if I print it out. But if I want to convert the JSON string, there is always the error message below. (at the JSON.parse) So, I assume maybe an mistake while filling the array? Thanks in advance guys!
Javascript:
$.ajax({
url: "./select_firsttracks.php",
type: "post",
success: function(resultset) {
$("#erroroutput").html(resultset);
var arr = JSON.parse("{" + resultset + "}"); // --> "Uncaught SyntaxError: Unexpected token {"
},
error: function(output) {
$("#erroroutput").html("fatal error while fetching tracks from db: " + output);
}
});
PHP:
$storage = array();
while($row = $result->fetch_array())
{
$storage[] =
array
(
"id" => $row["id"],
"trackname" => $row["trackname"],
"artist" => $row["artist"],
"genre" => $row["genre"],
"url" => $row["url"],
"musicovideo" => $row["musicovideo"]
);
echo json_encode($storage);
}
Output on the console:
[{"id":"1","trackname":"yes","artist":"Lady Gaga","genre":"Pop","url":"ftp:\/development","musicovideo":"1"}][{"id":"1","trackname":"yes","artist":"Lady Gaga","genre":"Pop","url":"ftp:\/development","musicovideo":"1"},{"id":"2","trackname":"no","artist":"Prinz Pi","genre":"Rap","url":"ftp:\/development","musicovideo":"1"}]
echo the json after the while
$storage = array();
while($row = $result->fetch_array())
{
$storage[] =
array
(
"id" => $row["id"],
"trackname" => $row["trackname"],
"artist" => $row["artist"],
"genre" => $row["genre"],
"url" => $row["url"],
"musicovideo" => $row["musicovideo"]
);
}
echo json_encode($storage);
and change:
var arr = JSON.parse(resultset);
You're adding curly braces in front and behind your received JSON, here:
var arr = JSON.parse("{" + resultset + "}");
Phps json_encode returns perfectly valid JSON by itself. Try it without adding the braces:
var arr = JSON.parse(resultset);
The resulting json string is not valid, you can check it with jsonlint
Modify your php code to echo outside the loop:
while($row = $result->fetch_array())
{
$storage[] =
array
(
"id" => $row["id"],
"trackname" => $row["trackname"],
"artist" => $row["artist"],
"genre" => $row["genre"],
"url" => $row["url"],
"musicovideo" => $row["musicovideo"]
);
}
echo json_encode($storage);
And in javascript just use the output as a javascript object
success: function(resultset) {
console.log(resultset)
resultset.each(function(index,element){ console.log(index,element )})
},

strange behavior json_decode

I'm creating a json in javascript in that way
jsonArr.push({
position: 'WN',
wind: windWN,
wave: waveWN,
sea: seaWN
});
var myJsonString = JSON.stringify(jsonArr);
I'm sending it via an AJAX method with jsonData: jsonData:Ext.encode(myJsonString)
My json array looks like that when I send it :
In PHP side, I'm getting the Json and decoding it that way :
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata, true);
I tried print_r( $rawpostdata2[1]); and got '{', as the second character of the "string", and I can't understand why.
In the other side, I tried print_r($rawpostdata), cut/past the result in a $string and retest my json_decode like that :
$rawpostdata = file_get_contents("php://input");
// print_r($rawpostdata);
$string = '[{"position":"N","wind":"2","wave":"65","sea":"65"},{"position":"E","wind":"3","wave":"5","sea":"6"},{"position":"S","wind":"56","wave":"4","sea":"8"},{"position":"W","wind":"1","wave":"56","sea":"84"},{"position":"NE","wind":"5","wave":"6","sea":"65"},{"position":"ES","wind":"6","wave":"45","sea":"6"},{"position":"SW","wind":"69","wave":"8","sea":"4"},{"position":"WN","wind":"7","wave":"8","sea":"56"}]';
$rawpostdata2 = json_decode($string,true);
print_r ($rawpostdata2[1]);
It gives me the correct result !
Array (
[position] => E
[wind] => 3
[wave] => 5
[sea] => 6 )
Do you have some explanations?
EDIT : I make it working by making another json_decode
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata,true);
$rawpostdata3 = json_decode($rawpostdata2,true);
But I don't really understand...
First, you create json string:
var myJsonString = JSON.stringify(jsonArr);
Then you encode the resulting string into json again:
Ext.encode(myJsonString)
Thus, you have to json_decode() twice in PHP.
Try using $_POST instead of file_get_contets() which gives you a string.
you need to do a type cast on the result of json_decode like this:
<?php
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = (array) json_decode($rawpostdata,true);
?>
I hope this works for you.. Cheers..!!

php array to javascript format?

I have an array.
Array
(
[0] => Array
(
[title] => Badminton Men's Singles Gold Medal Kashyap Parupalli
[mp4] => http://www.tensports.com/media/video/kashyap.mp4
[webm] => http://www.tensports.com/media/video/kashyap_VP8.webm
[playThumb] => {filedir_2}Kashyap_medal.jpg
[videoPoster] =>{filedir_3}Kashyap_medal.jpg
)
[1] => Array
(
[title] => Boxing Men's Welter (69kg) Silver medal: Mandeep Jangra
[mp4] => http://www.tensports.com/media/video/MandeepJangraMedal.mp4
[webm] => http://www.tensports.com/media/video/MandeepJangraMedal_VP8.webm
[playThumb] => {filedir_2}Mandeep_Jangra_medal.jpg
[videoPoster] =>{filedir_3}Mandeep_Jangra_medal.jpg
)
)
I am trying to convert it in a object like below.
Javascript Format required :
videos = [
{
src : [
'http://www.tensports.com/media/video/kashyap_VP8.webm',
'http://www.tensports.com/media/video/kashyap.mp4'
],
poster : '{filedir_2}Kashyap_medal.jpg',
title : "Badminton Men's Singles Gold Medal Kashyap Parupalli"
},
{
src : [
'http://www.tensports.com/media/video/MandeepJangraMedal.mp4',
'http://www.tensports.com/media/video/MandeepJangraMedal_VP8.webm'
],
poster : '{filedir_2}Mandeep_Jangra_medal.jpg',
title : "Boxing Men's Welter (69kg) Silver medal: Mandeep Jangra"
}
];
what I have done :
var videoObject = $.parseJSON(<?php echo $js_VideoURL ?>);//where $js_VideoURL = json_encode($above-array);
$.each(videoObject, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
It's giving me error.I am uncertaing about getting the data in required format.Any help?
The format you're expecting in javascript is not compatible with the php array you've given.
Going from there I am assuming that is the problem, since you didn't give the exact error message you're encountering. From what I can gather you're missing a piece of PHP to put the video's in the correct format. To solve that you can do the following:
Note the comments in the code, they should explain what is going on.
PHP:
// $videos is assumed to be the array you've given in your question
$arr = [];
foreach ($videos as $video) {
// Create video object
$obj = new stdClass;
$obj->src = [
$video['webm'],
$video['mp4']
];
$obj->poster = $video['playThumb'];
$obj->title = $video['title'];
$arr[] = $obj;
}
// $arr is now the output you would need for processing
Javascript:
var videoObject = <?php echo $js_VideoURL ?>; //where $js_VideoURL = json_encode($arr);
$.each(videoObject, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
Edit:
Your first mistake is as Quentin mentioned that you're putting the json directly into javascript, which means it will be interpreted as a native javascript object. I missed that in my original answer.
It means you indeed do not need to use $.parseJSON to get the object you want. I changed my answer to reflect that.
Note:
Your code implies that you have Javascript snippets in your php / html templates. This is considered bad practice, and can be resolved with relative ease.
What you could do is put the json in a data attribute of the relevant html element on the page (escape the json before printing) then picking up the json string using jQuery on initialization with
var object = $element.data('json');
Using this (jQuery will automatically try parse the string as json) it will be ready for use.
The JSON format is a subset of JavaScript literal syntax
json_encode outputs JSON (which, if just dumped in JS, will be treated as a literal)
parseJSON takes a string of JSON and converts it to a data structure
Therefore: Don't use parseJSON as it will force the object you have into a string ("[Object object]") and then try to parse that as JSON.
Just:
var videoObject = <?php echo $js_VideoURL ?>;
Come on.. did you even check PHP docs, or even google json encode!?!?!
var videoObject = <?php echo json_encode($js_VideoURL); ?>;

Parsing a Multidimensional array from php to Javascript via json

I am trying to send an array from php to javascript through ajax and am having some troubles.
My php array code looks something like this:
if($_REQUEST['action'] == 'miniCart'){
foreach($_SESSION['cart']['items'] as $item){
$message[$item['id']]['name'] = $item['name'];
$message[$item['id']]['price'] = number_format($item['price'], 2, '.', '');
$message[$item['id']]['qty'] = $item['count'];
}
$message = json_encode($message,true);
}
And this builds an array that looks something like this:
[2] =>
[name] => "Product 1"
[price] => "$15.00"
[qty] => "2"
[1] =>
[name] => "Product 2"
[price] => "$15.00"
[qty] => "3"
My JS code looks something like this:
var miniCart = function () {
$(".tester").on("click", function(event) {
var action = 'miniCart';
$.ajax({
type: "POST",
url: "cart/cart.php",
data:"action=" + action + "&ajax=true",
success: function(string){
var obj = jQuery.parseJSON(string);
alert( obj.name);
}});
});
}
My Json that is sent from php to JS looks like this:
{“2”:{“name”:”Product 1”,”price”:”15.00”,”qty”:”3”},”1”:{“name”:”Product 2”,”Price”:”15.00”,”qty”:”3”}}
I understand that this wont work, if someone can help finish this so that I can construct another array on the JS side that would be most helpful. My problem is that I can't parse them out correctly. I have tried many variations of JSON parsing but I think the "2" in the beginning is throwing it off. The item ID will never always be changing depending upon the order.
Perhaps I'm trying to engineer this incorrectly. I ultimately want to use these variables to build a shopping cart table.
Please assist.
Thank you kindly.
And this builds an array that looks something like this:
You're actually building an associative array in PHP, not a 0-indexed array. It then gets converted into a JSON object (with item IDs as keys), not a JSON array.
To get the name of the item with ID "2" in javascript:
alert(obj["2"].name);
You can iterate over the JSON object like this:
for (var key in obj) {
console.log("Item ID: " + key);
console.log(obj[key]);
}

Categories