JSON object to PHP associative array - php

I am building an array in JS as such:
var slots = {};
$(".taken").each(function(item) {
var key = $(this).attr("id");
slots[key] = "<?php echo $_SESSION['alias']; ?>";
});
var json = JSON.stringify(slots);
var date = "<?php echo $_GET['date']; ?>"
$.ajax({
type: "POST",
url: "controllers/dutyupdate2.php",
data:{ array : json, date: date },
success : function(response){
console.log (response)
}//end success
});//end ajax
In my PHP script I am posting to, I need to decode it to match the following format:
array( 'D1P'=>"JohnC" , 'D6E' => "JohnC")
I get:
Array(
[D2E] => JohnC
[D6E] => JohnC
[D3BU] => JohnC
)
No matter how I decode the array, I get an indexed array with my key as the index.
Am I building the array incorrectly in the JS code or decoding incorrectly?
Thanks in advance

This is the format you want, just displayed differently. See this PHP code to verify
$a = array( 'D1P'=>"JohnC" , 'D6E' => "JohnC");
print_r($a);
this gives
Array
(
[D1P] => JohnC
[D6E] => JohnC
)
as output. So, there's no need to try or search anything different.

Related

remove character from php key value array

This is the array i have right now. I want to remove the random open bracket in the [0] => ["A100" and also the random close bracket in [4] => "B11"] ....I ve tried using :
foreach($list as $key=>$value)
{
**//its suppose to be the same array that is $list not a new array $array**
$list[$key]=str_replace("[","",$value);
}
$list being the array that contains the pictured elements. It doesnt seem to remove the brackets.. Am I doing something wrong?
**UPDATE: **
Im getting the array from a localstorage sending it through post to another php where i catch the value and explode to a array called $list.
$(function(){
$('#fbtn').click(function(){
$.ajax({
url: 'FactorAnalysis.php',
type: 'POST', // GET or POST
data: {data: localStorage.getItem('reportArray')}, // will be in $_POST on PHP side
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert("Response is"+ data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("failed");
}
});
});
});
the localStorage outputted to a div shows me :
so here im sending the data through a ajax call:
$list = array();
$list = explode(',',$_POST['data']);
^ then in another php (FactorAnalysis.php) i get the array and explode to array $list.
Try this
$list = json_decode($_POST['data'], true);
instead
$list = explode(',',$_POST['data']);

Accessing JSON Object returned from PHP using Jquery Ajax

I am having trouble accessing the JSON data returned from my AJAX JQUERY call.
The AJAX executes correctly as does the query. I get the correct data returned; this consists of two arrays that I JSON_ENCODE. I need to be able to access both data sets independently.
It may make sense when you guys see the code:
**PHP**
$sql501 = "SELECT member,COUNT(member) as cont from loggederrors WHERE err = '".$hello."' GROUP BY member ";
$result50 =mysqli_query($con,$sql501);
$count50=mysqli_num_rows($result50);
$member = array();
$count = array();
while($row56 = mysqli_fetch_assoc($result50)) {
array_push($member, $row56['member']);
array_push($count, $row56['cont']);
}
echo JSON_encode($member);
echo JSON_encode($count);
?>
$member and $count are arrays and when they are returned and logged in my AJAX success function they look like this :
["Missed Entry"]["1"]["Missed Entry","Overwrite"]["1","1"]
The data is in the right order but seems to repeat which I understand is because I am pushing in each iteration to the arrays. Its the closest I got because the order is correct. I have tried building an associative array and using various different mysqli outputs i.e num_rows, fetch_assoc
Previously when I have used JSON I have never had an issue and have key to access the data:
Here is the AJAX:
$.ajax({url: 'getstaffresults.php',
data: {stafftosend:stafftosend },
type: 'post',
async: 'true',
success: function(data){
console.log(data);
}
});
I have previously been able to access individual keys with data.keyIwantbut this is not coming out as expected. Any help is much appreciated.
The goal is to get access to the two arrays. I do not need access to values in the arrays if that makes sense.
I have tried building a 2d array and encoding that but again I had not way of accessing it.
I have tried JSON.stringyfy , JSON.parse
Try packing the two responses into an array and only echo'ing one response.
$sql501 = "SELECT member,COUNT(member) as cont from loggederrors WHERE err = '".$hello."' GROUP BY member ";
$result50 =mysqli_query($con,$sql501);
$count50=mysqli_num_rows($result50);
$member = array();
$count = array();
while($row56 = mysqli_fetch_assoc($result50)) {
array_push($member, $row56['member']);
array_push($count, $row56['cont']);
}
$arrayResponse = array(
'member' => $member,
'count' => $count
);
echo JSON_encode($arrayResponse);
?>
I only suggest this because I am unsure if the javascript would parse to json strings side by side?
The nack it to create a single sensible PHP data structure and then convert it to json
You dont need 2 arrays for you information. Also if you echo 2 responces the likelyhood is the second will be lost in the ether.
So try this instead, create an array of arrays to return to the javascript code, which makes them easy to process here and in javascript.
$sql501 = "SELECT member,COUNT(member) as cont
from loggederrors
WHERE err = '".$hello."'
GROUP BY member ";
$result50 =mysqli_query($con,$sql501);
$count50=mysqli_num_rows($result50);
$member = array();
while($row56 = mysqli_fetch_assoc($result50)) {
$member[] = array('member' => $row56['member'],
'cont' => $row56['cont']);
}
echo JSON_encode($member);
?>
In fact you can simplfy this even further to
$sql501 = "SELECT member,COUNT(member) as cont
from loggederrors
WHERE err = '".$hello."'
GROUP BY member ";
$result50 =mysqli_query($con,$sql501);
$count50=mysqli_num_rows($result50);
$member = array();
while($row56 = mysqli_fetch_assoc($result50)) {
$member[] = $row56;
}
echo JSON_encode($member);
?>
Now change the javascript to add the dataType: 'json', property
$.ajax({url: 'getstaffresults.php',
data: {stafftosend:stafftosend },
type: 'post',
async: 'true',
dataType: 'json',
success: function(data){
console.log(data);
}
});
and the data should be converted to javascipt array automatically
In your php:
echo json_encode(['member' => $member, 'count' => $count]);
In javascript:
$.ajax({url: 'getstaffresults.php',
data: {stafftosend:stafftosend },
type: 'post',
async: 'true',
success: function(data){
var parsedData = JSON.parse(data);
console.log(parsedData);
}
});

javascript variable parsing by php regex

I am trying to parse some javascript variables using PHP.
Random website: (not my website)
//.... content ...
function(response) {
if (response) {
var data = { id: "fka1q021", action: "post", date: "today" };
}
//.....
$url = 'www.website.com';
$content = htmlspecialchars(file_get_contents($url));
preg_match_all('/var data = { id: "(.*?)", action: "post", date: "today" };/', $content, $matches);
print_r($matches);
Output:
Array ( [0] => Array ( ) [1] => Array ( ) )
I want to get value of id which is fka1q021
How can I get it? Thanks
You may want to try preg_match instead of preg_match_all. Then, the $matches array will contain the entire matched expression as its 0th element, and the match within your parenthesized sub-expression as its 1st element. That 1st element is the id you're looking for.
So, try:
preg_match('/var data = { id: "(.*?)", action: "post", date: "today" };/', $content, $matches);
Here is full example code:
<?php
$content = <<<ENDOFCONTENT
//.... content ...
function(response) {
if (response) {
var data = { id: "fka1q021", action: "post", date: "today" };
}
//.....
ENDOFCONTENT;
preg_match('/var data = { id: "(.*?)", action: "post", date: "today" };/', $content, $matches);
print_r($matches);
print "id = " . $matches[1] . "\n";
Here is resulting output:
Array
(
[0] => var data = { id: "fka1q021", action: "post", date: "today" };
[1] => fka1q021
)
id = fka1q021
You are not getting anything with your regular expression, because you are applying htmlspecialchars to the content you are reading – and that replaces " with ", so your expression does not find the " you have in there.
Just remove htmlspecialchars, and your pattern will match.
Javascript is client side and PHP is server side, so all the PHP will have executed before the Javascript can run. See this question: How to pass JavaScript variables to PHP?
I'm not sure what your doing is legit... JS ans PHP doesn't execute at the same time and in the same place. Maybe you got this after an ajax call ?
Anyway, analysing a JS data with php can be done with json_decode. I think your problem here will be that json_decode won't understand {id:"value"}, he needs {"id":"value"} instead...
if ( preg_match("#data = ({[^}]*})#",$data,$matches) )
json_decode($matches[1]) ;
For example,
print_r(json_decode('{"id":"fka1q021","action":"post","date":"today"}') );
Render a php object :
stdClass Object
(
[id] => fka1q021
[action] => post
[date] => today
)
A very simple regex is
(?:id:\s(\".*?\"))
Debuggex Demo
then the id will be in capture group 1.
Let me know if you need a more complex regex. And if so, provide more info.

How to read Json_encoded php array from jquery?

I have a php array like this one :
Array
(
[0] => banana, peach, cherry
[1] => strawberry, apple, lime
)
I pass it to Jquery using json_encode($myArray)
In Jquery I receive my array like this : ["banana, peach, cherry","strawberry, apple, lime"]
Now I wanna extract each value : "banana, peach, cherry" & "strawberry, apple, lime"
When I try to use this :
$.each(data, function(key, value){
alert(value);
});
it alerts me each chars : [ " b a n a n................ etc instead each value.
Do you know why ?
EDIT :
This is how I receive my data from php :
$.post('ajax/fruits.php', function(data) {
var obj = $.parseJSON(data);
var chunks = obj['chunks'] // gives me : ["banana, peach, cherry","strawberry, apple, lime"]
if (obj['error']==0) {
mix_fruits(chunks); // a function that should extract each value
}
});
You don't show how you are passing and receiving the data, but somewhere in the process you are making a mistake.
It is evident from the description that data is a string, not an array as it should have been based on the PHP variable. And since the string begins with the characters that make up the JSON representation of your data, this means the JSON is being wrapped into a string instead of parsed as a JavaScript literal.
Assuming that passing/receiving is not done through an AJAX request (in which case jQuery would almost certainly parse the data automatically) I 'm guessing that you are doing this:
var data = '<?php echo json_encode($data); ?>';
while you should instead be doing this:
var data = <?php echo json_encode($data); ?>; // no quotes!
You need to parse the JSON object before you can use it,
var jsonObj = jQuery.parseJSON(data);
then to loop through each item use this,
for(var key in jsonObj)
{
curr = jsonObj[key];
}
And if you want to use non-jquery one,
Parse JSON in JavaScript?

How to get the POST values from serializeArray in PHP?

I am trying this new method I've seen serializeArray().
//with ajax
var data = $("#form :input").serializeArray();
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
So I get these key value pairs, but how do I access them with PHP?
I thought I needed to do this, but it won't work:
// in PHP script
$data = json_decode($_POST['data'], true);
var_dump($data);// will return NULL?
Thanks, Richard
Like Gumbo suggested, you are likely not processing the return value of json_decode.
Try
$data = json_decode($_POST['data'], true);
var_dump($data);
If $data does not contain the expected data, then var_dump($_POST); to see what the Ajax call did post to your script. Might be you are trying to access the JSON from the wrong key.
EDIT
Actually, you should make sure that you are really sending JSON in the first place :)
The jQuery docs for serialize state The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Ready to be encoded is not JSON. Apparently, there is no Object2JSON function in jQuery so either use https://github.com/douglascrockford/JSON-js/blob/master/json2.js as a 3rd party lib or use http://api.jquery.com/serialize/ instead.
The OP could have actually still used serializeArray() instead of just serialize() by making the following changes:
//JS
var data = $("#form :input").serializeArray();
data = JSON.stringify(data);
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
// PHP
$data = json_decode(stripslashes($_POST['data']),true);
print_r($data); // this will print out the post data as an associative array
its possible by using the serialize array and json_decode()
// js
var dats = JSON.stringify($(this).serializeArray());
data: { values : dats } // ajax call
//PHP
$value = (json_decode(stripslashes($_REQUEST['values']), true));
the values are received as an array
each value can be retrieved using $value[0]['value'] each html component name is given as $value[0]['name']
print_r($value) //gives the following result
Array ( [0] => Array ( [name] => name [value] => Test ) [1] => Array ( [name] => exhibitor_id [value] => 36 ) [2] => Array ( [name] => email [value] => test#gmail.com ) [3] => Array ( [name] => phone [value] => 048028 ) [4] => Array ( [name] => titles [value] => Enquiry ) [5] => Array ( [name] => text [value] => test ) )
The JSON structure returned is not a string. You must use a plugin or third-party library to "stringify" it. See this for more info:
http://www.tutorialspoint.com/jquery/ajax-serializearray.htm
I have a very similar situation to this and I believe that Ty W has the correct answer. I'll include an example of my code, just in case there are enough differences to change the result, but it seems as though you can just use the posted values as you normally would in php.
// Javascript
$('#form-name').submit(function(evt){
var data = $(this).serializeArray();
$.ajax({ ...etc...
// PHP
echo $_POST['fieldName'];
This is a really simplified example, but I think the key point is that you don't want to use the json_decode() method as it probably produces unwanted output.
the javascript doesn't change the way that the values get posted does it? Shouldn't you be able to access the values via PHP as usual through $_POST['name_of_input_goes_here']
edit: you could always dump the contents of $_POST to see what you're receiving from the javascript form submission using print_r($_POST). That would give you some idea about what you'd need to do in PHP to access the data you need.
Maybe it will help those who are looking :)
You send data like this:
$.ajax({
url: 'url_name',
data: {
form_data: $('#form').serialize(),
},
dataType: 'json',
method: 'POST'
})
console.log($('#form').serialize()) //'f_ctrType=5&f_status=2&f_createdAt=2022/02/24&f_participants=1700'
Then on the server side use parse_str( $_POST['form_data'], $res).
Then the variable $res will contain the following:
Array
(
[f_ctrType] => 5
[f_status] => 2
[f_createdAt] => '2022/02/24'
[f_participants] => 1700
)
You can use this function in php to reverse serializeArray().
<?php
function serializeToArray($data){
foreach ($data as $d) {
if( substr($d["name"], -1) == "]" ){
$d["name"] = explode("[", str_replace("]", "", $d["name"]));
switch (sizeof($d["name"])) {
case 2:
$a[$d["name"][0]][$d["name"][1]] = $d["value"];
break;
case 3:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]] = $d["value"];
break;
case 4:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]][$d["name"][3]] = $d["value"];
break;
}
}else{
$a[$d["name"]] = $d["value"];
} // if
} // foreach
return $a;
}
?>

Categories