How to properly deserialize a string from JQuery using PHP? [duplicate] - php

This question already has answers here:
JQuery string not parsing correctly in PHP
(2 answers)
Closed 9 years ago.
I was wondering, does anyone know how do I properly deserialize a string from a JQuery using PHP? The string that JQuery passes into my PHP file is this:
age_gender=1&age_gender=2&age_gender=3&age_gender=4&age_gender=5&age_gender=6
The values I need are the numbers after the equal signs (they are just dummy values that I used for testing).
EDIT: Actually, I am already using parse_str(). Here is my PHP code:
if(isset($_POST['age_gender'])) {
$formSerialized = $_POST['age_gender'];
$formData = array();
parse_str($formSerialized, $formData);
addRow($formData, $link);
}
function addRow($dataArray, $link) {
$age_group = $dataArray[0];
$populations = array(intval($dataArray[1]) + intval($dataArray[2]), intval($dataArray[1]), intval($dataArray[2]));
$percents = array(doubleval($dataArray[3]) + doubleval($dataArray[4]), doubleval($dataArray[3]), doubleval($dataArray[4]));
$m_per_100_f = doubleval($dataArray[6]);
$query = "INSERT INTO national_age_gender_demographics (age_group, both_pop, male_pop, female_pop, both_percent, male_percent, female_percent, males_per_100_females)
VALUES ('$age_group','$populations[0]','$populations[1]','$populations[2]','$percents[0]','$percents[1]','$percents[2]','$m_per_100_f')";
$result = mysqli_query($link,$query);
if(!$result) die( "Query: " . $query . "\nError:" . mysql_error() );
}
For some reason, I am getting a blank string for $age_group, and 0's for all other values. Could anyone help me here?

See parse_str()
Example:
parse_str('age_gender=1&age_gender=2&age_gender=3&age_gender=4&age_gender=5&age_gender=6', $output);
print_r($output);
Also if you want to get the querystring of the request you can get it with php using $_SERVER['QUERY_STRING']

parse_str()
is the function you are looking for.
You have two options to use with this:
parse_str($string) - this will actually create a variable for each key in the string.
parse_str($string,$arr) - this will populate $arr with an associative array containing all the key=>value pairs from the string.
The documentation gives some great code to demonstrate this behavior:
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

Related

function array_push returns empty array [duplicate]

This question already has an answer here:
PHP json_encode returns null value from unicode character
(1 answer)
Closed 7 years ago.
I try to save the rows of a table in an array but I am getting an empty array.
My code is:
$a = array();
$b = array();
if ($result->num_rows > 0){
while ($row = $result->fetch_assoc()) {
$b["id"] = $row["id"];
$b["title"] = $row["title"];
$b["description"] = $row["description"];
$b["lat"] = $row["lat"];
$b["lng"] = $row["lng"];
$b["walkId"] = $row["walkId"];
echo json_encode($b);
array_push($a,$b);
}
echo json_encode($a);
}
Using echo json_encode($b); I see the results one by one but the array a is empty.
EDIT 1
After Random's help, using the echo print_r($a,true); I am getting the below screenshot:
And the screenshot from other tables in which I get the data correctly is:
EDIT 2
problem with json_encode. I get the below
[{"id":"55","title":"\u00ce\u203a\u00ce\u00bf\u00cf\u2026\u00ce\u00bb\u00ce\u00bf\u00cf\u2026\u00ce\u00b4\u00ce\u00ac\u00ce\u00b4\u00ce\u00b9\u00ce\u00ba\u00ce\u00b1","description":"\u00ce\u201c\u00ce\u00b5\u00ce\u00bd\u00ce\u00b9\u00ce\u00ba\u00ce\u00ae \u00ce\u00b1\u00ce\u00bd\u00ce\u00b1\u00cf\u2020\u00ce\u00bf\u00cf\u0081\u00ce\u00ac \u00cf\u0192\u00cf\u201e\u00ce\u00b1 x\u00ce\u00b1\u00cf\u0081\u00ce\u00b1\u00ce\u00ba\u00cf\u201e\u00ce\u00b7\u00cf\u0081\u00ce\u00b9\u00cf\u0192\u00cf\u201e\u00ce\u00b9\u00ce\u00ba\u00ce\u00ac \u00cf\u201e\u00ce\u00b7\u00cf\u201a \u00ce\u00b3\u00ce\u00b1\u00cf\u0192\u00cf\u201e\u00cf\u0081\u00ce\u00bf\u00ce\u00bd\u00ce\u00bf\u00ce\u00bc\u00ce\u00af\u00ce\u00b1\u00cf\u201a \u00cf\u201e\u00ce\u00b7\u00cf","lat":"40.634356","lng":"22.940716","walkId":"92"},{"id":"56","title":"\u00ce\u2018\u00ce\u00b3\u00ce\u00bf\u00cf\u0081\u00ce\u00ac \u00ce\u0153\u00ce\u00bf\u00ce\u00b4\u00ce\u00b9\u00ce\u00ac\u00ce\u00bd\u00ce\u00bf","description":"H \u00ce\u00b9\u00cf\u0192\u00cf\u201e\u00ce\u00bf\u00cf\u0081\u00ce\u00af\u00ce\u00b1 \u00ce\u00bc\u00ce\u00b9\u00ce\u00b1\u00cf\u201a \u00ce\u00b9\u00cf\u0192\u00cf\u201e\u00ce\u00bf\u00cf\u0081\u00ce\u00b9\u00ce\u00ba\u00ce\u00ae\u00cf\u201a \u00ce\u00b1\u00ce\u00b3\u00ce\u00bf\u00cf\u0081\u00ce\u00ac\u00cf\u201a. \u00cf\u201e\u00ce\u00b1 X\u00ce\u00b1\u00cf\u0081\u00ce\u00b1\u00ce\u00ba\u00cf\u201e\u00ce\u00b7\u00cf\u0081\u00ce\u00b9\u00cf\u0192\u00cf\u201e\u00ce\u00b9\u00ce\u00ba\u00ce\u00ac \u00cf\u201e\u00ce\u00b7\u00cf\u201a \u00ce","lat":"40.634609","lng":"22.941081","walkId":"92"}
First thing I note is the special ? that appears 3 time. The problem must come from here.
Try to edit the 3 descriptions that contain the special ? so it doesn't appear again in the print_r.
That must turn array_push into an error.
You could also try to encode it in latin to make it safe. (please follow #deceze link to understand what to do)

converting a delineated string into an array path in PHP

I'd appreciate any help I could get with this — I've been scouring stack overflow and couldn't find anything that directly related with what I'm trying to accomplish.
Issue: I'm trying to update a specific name/value pair in a JSON file, and I'm trying to do it by sending specific parameters through an AJAX call to a PHP file. Two of the parameters are the path (delineated with hyphens) to the name, and the value that I'm swapping in.
A small portion of the JSON:
{
"character" :
{
"name" : "Foo",
"species" : "Bar",
}
}
Using this JSON as an example, I'm trying to update a specific array value, such as:
$char['character']['name']
I'm passing a variable to the PHP file with the path information, such as:
updater.php?char=character-name&val=Newname
Is there a way to convert the string "character-name" (or any string for that matter with a particular delineation) to the path in an Array, like $char['character']['name']?
$array = explode("-", $_GET['char']);
$char=json_decode(....); //your json string
$char[$array[0]][$array[1]]=$_GET['val'];
To not only read the value at the specified path, but also update the json, I would suggest something like
<?php
function json_replace_path($json, $path, $newValue)
{
$json = json_decode($json);
$pathArray = explode('-', $path);
$currentElement = $json;
foreach ($pathArray as $part)
{
$currentElement = &$currentElement->$part;
}
$currentElement = $newValue;
return json_encode($json);
}
$json = '{"character":{"name":"Foo","species":"Bar","other":{"first_name":"Jeff","last_name":"Atwood"}}}';
echo json_replace_path($json, 'character-name', 'new name') . "\n";
echo json_replace_path($json, 'character-species', 'new species') . "\n";
echo json_replace_path($json, 'character-other-last_name', 'Bridges') . "\n";
Does not support JSON including arrays, though.
Something like that should work, I guess :
$a = explode("-", $_GET['char']);
$array = ...; //Your json array here
while (is_array($array) && count($a) > 0)
{
$array = $array[array_shift($a)];
}
Why not just use updater.php?character[name]=Newname? Then you can get it with:
echo $_GET['character']['name'];
Makes much more sense. Why concatenate things and then try and separate them into an array when you can just use an array from the start?

How to serialize an array (array to query string) using PHP [duplicate]

This question already has answers here:
PHP function to build query string from array
(4 answers)
Closed 7 months ago.
I have an array of data comes from $_POST and I want to send them by curl to another page.
curl_setopt($s,CURLOPT_POST,true);
curl_setopt($s,CURLOPT_POSTFIELDS,$this->_postFields);
$this->_postFields must be an string like a=2&b=t right?
so if I want to send array of data with curl to another page I must turn array to query string right?
How should I do it with PHP?
♦I tried serialize() and unserialize() but thier format is not same as query string right?
so what should I do? (I need something like .serialize() in jQuery that work on array not FORM)
♦ And the destination path is not under my control and the $_POST in the destination should be as $_POST not as its base64 encoded so I can't use such codes.
$array = array(1,2,3);
$encoded = json_encode($array);
$decoded = json_decode($encoded);
print_r($decoded);
Any Ideas?
thanks in advance.
You can use http_build_query:
curl_setopt($s, CURLOPT_POSTFIELDS, http_build_query($this->_postFields));
NOTICE
It looks beauty, but to use this approach be careful about url encoding .Look next:
$_POST["some value"]='value1'; // " " between
$_POST["next value"]='value2'; // " " between
$url = http_build_query($_POST);
echo $url;
// OUTPUT
some+value=value1&next+value=value2
Of course, after sending this $url we will not get expected variables from $_POST.
I think you can just do this:
curl_setopt($s, CURLOPT_POSTFIELDS, http_build_query($this->_postFields));
If I understand, you can use json.
$array = array(1,2,3);
$encoded = json_encode($array);
$decoded = json_decode($encoded);
print_r($decoded); //Look to it
If is not it, can be it:
$array = array(1,2,3);
echo http_build_query($array); //Look to it

how to parseFloat this?

i have this code :
$wage = array();
foreach ($result3 as $row3) {
$wage[] = '[' . floatval($row3['age']) . ',' . floatval($row3['point']) .']';
}
if ($userid == 0 ) {
$age= "";
} else {
$age = implode(',', $wage).",";
}
echo json_encode("var2"=>$myvar ,"var3"=>$age)); // i didnt write var2 because is same as var3
the above will outputs something like [4,2.3][5,6],[1.7,5],
and in javascript im receiving this value outputed above via ajax which has name var3.
dataType: 'json' ,
success: function(response){
var age = response['var3'] ;
.....
so the question is how can i parseFloat this variable age ?
EDIT .
if i alert the json like that
alert (response);
i get [object Object] // make attention to small o and big O
EDIT2 .
used consol log
and i get this
{"var2":"[2,5],[3.5,5],[6.5,6.5],[8,7],","var3":"[2,46],[3.5,61],[6.5,70],[8,71],","var4":"[2,32],[3.5,41],[6.5,42],[8,43],","var5":"[46,5],[61,5],[70,6.5],[71,7],"}
this returned values i want to parseFloat them as you see they are like strings between two quotes
This is incorrect:
$wage[] = '[' . floatval($row3['age']) . ',' . floatval($row3['point']) .']';
You're building a string, which coincidentally happens to LOOK like a javascript array definition, but it's still just a string. When this gets json_encoded, it'll come out as
"[...,...]"
^-- ^-- string
You need to build NATIVE data structures at all stages while in PHP, e.g.
$wage[] = array(floatval($row3['age']), floatval($row3['point']));
and not this mish-mash of native AND "json-like" strings. json_encode() converts NATIVE datatypes of the equivalent Javascript types. Since your own floatval business is producing a string, you'll get a json-encoded string, not an array.
You are getting this all wrong. You do not need to do this;
foreach ($result3 as $row3) {
$wage[] = '[' . floatval($row3['age']) . ',' . floatval($row3['point']) .']';
}
Perhaps what you want is;
foreach ($result3 as $i => $row3) {
$newRow = $row3;
$newRow['age'] = intval($row3['age']);
$newRow['point'] = floatval($row3['point']);
$result3[$i] = $newRow;
}
And then do this;
// Create JSON data, assuming that $result3 is an array
$jsonData = json_encode($result3);
// This will give you a JSON string, output this and finish to ensure it IS the only thing output
echo $jsonData;
die;
Now in your javascript, open the development console in what ever browser your using and use the following code in javascript
console.log(response)
This will output the whole response variable to the console and enable you to debug how to get specific data out of the response var.
Hope that helps.

Jquery, tablednd and ajax post

So, im using $.tableDnD.serialize() function, to get the current order of the Table TR-s, and want to post to a php function alongside with another variable.
$("#articlestable").tableDnD({
onDragClass: "drag",
onDrop: function(table, row) {
$.post('<?php echo HTML_ROOT; ?>/admin/cikkek/updateOrder/', {
pagesid : "1",
arr : $.tableDnD.serialize()
});
}
});
If i am sending the serialized data only, there is no problem with the access.
According to firebug the sent data:
arr articlestable[]=1&articlestable[]=2&articlestable[]=4&articlestable[]=3
pagesid 1
The main question, how can i get the data in php?
I thought:
$pagesid = $_POST["pagesid"];
$orderarr = $_POST["arr"]["articlestable"];
Thanks for help, and sorry for my english.
I think what you want to do is parse string. I could be wrong.
<?php
$arr = array();
$str = $_POST['arr'];
parse_str($str, $arr);
?>
In doing this, you should be able to then access the array as ->
echo $arr[0]; // outputs 1
echo $arr[1]; //outputs 2
echo $arr[2]; //outputs 4
So on and so forth.
EDIT
I should also note that using this method, you can still access your pageid by using the following:
echo $arr['pagesid'];

Categories