PHP loses Square Brackets From Sent jQuery form data - php

I'm trying to save form information using jQuery by serializing as an array and adding it into an object. jQuery sends the information fine as such:
action:save
form_data[name]:
form_data[date-requested]:09/23/2014
form_data[purchase-order-requested]:yes
form_data[vendor]:sdf
form_data[item-description[]]:
form_data[item-number[]]:
form_data[cost[]]:
form_data[quantity[]]:
But, when I try to print_r the posted data it appears as this:
Array
(
[name] =>
[date-requested] => 09/23/2014
[purchase-order-requested] => yes
[vendor] => sdf
[item-description[] =>
[item-number[] =>
[cost[] =>
[quantity[] =>
)
What can I do with inputs that have brackets in them?
[EDIT]
Here would be the jQuery:
var form_data = form.serializeArray();
var obj = {};
for(var i = 0, l = form_data.length; i < l; i++) {
console.log(form_data[i].name);
var obj2 = {
value: '"' + form_data[i].value + '"',
label: $("label[for='" + form_data[i].name + "']").html()
};
obj[form_data[i].name] = obj2;
}
And the array is simply printed with print_r
[EDIT]
If you notice the first code block, this is the POST data from jQuery. It sends the objects fine with form_data[cost[]].
But in the second code block, which is what PHP received, and immediately print_r()'ed, it loses a bracket resulting in cost[

Related

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?

Passing php array for use in javascript using json_encode

I know this has been asked plenty of times before but still I have a problem after readaing all the other posts on the subject... Somewhere between my php code -and the javascript it is sitting in- my array is going awol.
In the attached code, I have an echo for debugging of the php. When I cut out the php section from the javascript and run it separately with the echo on, it shows me that it is building my json_encoded array correctly.
In the javascript immediately after the php end I assign the php to a javascript variable, so I can use it for further processing (plotting a graph). Putting in display statements, to display the content of the result of the php call to get the array into javascript, shows the array is empty.
If I cut and paste the output of the php echo and assign this literal to the javascript chartData array then everything works fine. Why is the javascript not getting the php array content?
Here's the code snip:
<script>
...some java script stuff;
<?php
// Define the mySQL db connection
$db = new PDO('mysql:host=localhost;dbname=remets;charset=UTF-8', 'remets', 'remets', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
// Define SQL query to fetch data from mySQL
$stmt = $db->query("SELECT WeekNumber,XAxisCategory,YAxisValue FROM Metric WHERE ReportID = 'Q3' ORDER BY WeekNumber,XAxisCategory ASC");
// declarations
$amData = array();
$amArray = array();
$ctrinner = 0;
$ctrouter = -1;
$prevweek = "9999";
// Fetch data from mySQL and put it in an array in the format we need
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($prevweek !== $row['WeekNumber']) {
$ctrouter++;
$ctrinner = 0;
$amData[$ctrouter]["week"] = "".$row['WeekNumber']; // Prepending (or appending) the empty string makes the json encoding think the week number is a string, which is MUST have for AmCharts
}
$ctrinner++;
$amData[$ctrouter][$row['XAxisCategory']] = $row['YAxisValue'];
$prevweek = $row['WeekNumber'];
}
// Using json_encode puts the data into an array format that we can use in a javascript
$amJSONArray = json_encode($amData);
// Echo is for debugging only.
// echo $amJSONArray;
?>
var chartData = <?php echo $amJSONArray;
?>;
...more javascript stuff;
</script>
#Mahdi: The output of the print_r is: Array ( [0] => Array ( [week] => 1301 [Accepted] => 30 [Failed] => 5 [Passed] => 20 [Planned] => 5 [Skipped] => 5 [Unknown] => 26 ) [1] => Array ( [week] => 1302 [Accepted] => 25 [Failed] => 2 [Passed] => 25 [Planned] => 2 [Skipped] => 3 [Unknown] => 20 ) [2] => Array ( [week] => 1303 [Accepted] => 26 [Failed] => 26 [Passed] => 29 [Planned] => 26 [Skipped] => 26 [Unknown] => 10 ) )
#Mahdi: This is the jscript code immediately after the php (It is commented out because I tried lots of different options that were recommended in other posts in this forum and others - none of them work. I can run the php code and that works fine. If I copy the output of the echo in the php code snip I posted earlier and simply assign that to chartData (ie: chartData = "";
my chart is produced fine. The problem is not with the charting tool but somehow the array content is just not visible to the javascript which is directly below it in the .js file.
Thanks for your time up til now.
//var chartData = "<?php print($amJSONArray); ?>"; // This just returns the literal in the speech marks
//var chartData = '<?php print($amJSONArray); ?>'; // This also returns the literal in the speech marks
//var chartData = "<?php echo($amJSONArray); ?>"; // This just returns the literal in the speech marks
//var chartData = '<?php echo($amJSONArray); ?>'; // This also returns the literal in the speech marks
//var chartData = <?php echo ($amJSONArray) ?>; // This returns empty
//var chartData = <?php echo $amJSONArray ?>; // This returns empty
//var chartData = (<?php echo $amJSONArray ?>); // This returns empty
//alert(chartData); // Returns empty - just showing the contents of the array if I do the json_encode within the php part
//alert(<?php echo $amJSONArray ?>); // Returns empty - just showing the contents of the array if I do the json_encode during the array fetch
UPDATE:
I think there's something fundamentally wrong going on at my side. I used a very simple example which should write "hello world" to the screen but it returns nothing at all. If I substitute the 'write' with an 'alert' then it still shows nothing in the alert popup. Does anyone know why this would not be working? The code is:
<?php
$testvar = "Hello World";
?>
<html>
<head>
<script type="text/javascript">
function hello()
{
// create JavaScript variable, fill it with Php variable
var testvar = "<? print $testvar; ?>";
// output to screen
document.write( testvar );
}
</script>
</head>
<!-- Call JavaScript function to display variable -->
<body onload="hello()" >
</body>
</html>
If you are able to access the data as a string, you can try using the built-in JSON.parse() to convert it into usable javascript.

JSON object to PHP associative array

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.

Php pass array to Javascript

I want an array in Javascript, structure like this
$(function()
{
// prepare the data
for (var i=0; i<50000; i++) {
var d = (data[i] = {});
d["id"] = "id_" + i;
d["num"] = i;
d["title"] = "Task " + i;
d["duration"] = "5 days";
}
I want this array to be created through php.
I already have the array there created by for loop
EDITED:
Is the above data in Javascript a multidimensional array, a simple array or a var?
is the structure saved in "d" or in data[i][id],data[i][title],... ?
ie, $data = array('item' => 'description', 'item2' => 'description2');
json_encode($data);
All you need
Use json_encode() to encode the array.
Access PHP variable in JavaScript
That example works with arrays, too.

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