jQuery Serializing Brackets [ ] From Form Name Post to PHP - php

I'm serializing form data, the input names have brackets in them i.e.
when I serialize it with jquery to POST it to my php file for processing, it looks like this - test%5Btesting%5D=some input. My php file on the backend is not seeing these names when I try to grab it with:
echo $_POST['test[testing]'];
if I try just getting the info using the name test it shows it as an array. How do I tell php that the brackets are part of the field name?
<input name="test[testing]">
echo $_POST['test[testing]'];
My php file on the backend is not seeing these names when I try to grab it

PHP special cases square brackets in POST and GET data.
Access it with:
$_POST['test']['testing']
This allows you to construct a form with data that PHP will deserialize into a nested array / associative array structure that your server-side code can iterate over.
Some other form handling libraries have adopted this format, e.g. Express.js's body-parser library has an optional extended mode which supports this.
PHP has no native support for constructing a flat data structure (where $_POST['test[testing]'] would work), but you could read the raw data with:
$post_body_string = file_get_contents("php://input");
… and then write your own URL encoded form data parser.

Related

Parsing Form JSON output with PHP

How do I go about parsing the json request below in PHP to extract specific values (in value ) like the following: studentName, studentemail and courseName? There will be only one entry per request and I will not need the rest of the values. I need to store these as PHP variables to be written to MYSQL. The parsing is where I am having trouble
See json below
{"count":7,"data":[{"name":"Timestamp","ordinal":0,"value":"3/5/2013 2:45:31 PM"},{"name":"studentName","ordinal":1,"value":"mikejones"},{"name":"studentEmail","ordinal":2,"value":"mikejones%40gmail.com"},{"name":"courseName","ordinal":3,"value":"Grade%20Test"},{"name":"cpQuizInfoPassFail","ordinal":4,"value":"Fail"},{"name":"cpInfoPercentage","ordinal":5,"value":"75"},{"name":"institutionCode","ordinal":6,"value":"1212"}]}{"count":0}{"subject":"Course Transcript","footer":"Thank you for your participation!","footerURL":"https://sites.google.com/site/test393223837/googleformsdemotranscript/footerLogo.jpg","correctURL":"http//abc.com,"enabled":true,"correctResponseText":"Correct Response","showCorrectAnswers":true,"description":"Please keep this for your records as proof of course completion and certification.","incorrectURL":"https://sites.google.com/site/test3232393837/_/rsrc/1342229575450/googleformsdemotranscript/redX.png","fromName":"The Training Team","replyTo":"","headerURL":"https://sites.google.com/site/test3938232337/googleformsdemotranscript/CaptivateDev.jpg","isHTML":true,"title":"Course Transcript","to":"joe#gmail.com","userResponseText":"Your Response"}
You can use json_decode function, that parse json code to php objects and arrays. See documentation for more info.
One problem is your json is invalid. Check with:
http://jsonlint.com/ or
http://jsonformatter.curiousconcept.com/

Beginner to creating and reading JSON objects

Using http://objectmix.com/javascript/389546-reading-json-object-jquery.html as a starting point, I have been reading lots about JSON. Unfortunately I am a total beginner and can't get my head around the basics of creating JSON objects.
I have created a PHP page called getContact.php
<?php
"Contact": {
"ID" : "1",
"Name" : "Brett Samuel"
}
?>
And a javascript file with the following code:
$.getJSON('getContacts.php', function(data) {
var obj = (new Function("return " + data))();
alert(data.Contact.Name)
});
This page http://msdn.microsoft.com/en-us/library/bb299886.aspx suggests I have the basic approach correct. Can anyone tell me why this does not work? Absolutely nothing happens.
Thanks in advance.
Your PHP file contains JSON, which is not valid PHP, and will therefore error.
If you're working with PHP the easiest way to build JSON is to first prepare your data as an array (associative or indexed, as required) then simply convert it via json_encode(). (You can also decode JSON, with the corresponding json_decode().
[EDIT - in response to comment, just have a look at the PHP docs for json_encode() - it's very self explanatory. You take an array, pass it to json_encode(), and you get a JSON string.
$arr = array('one', 'two', 'three');
echo json_encode($arr); //JSON string
JSON is not a programming language, and it's certainly not executable as PHP. It's just a file format. If you want your web server to serve up a static JSON file, just drop it in the file system as filename.json, without any <?php tags. (Of course, as with HTML, you can also make it a .php file and just not have any PHP in it, other than something to set the Content-Type since the file suffix won't do it automatically. But that's wasteful.)
If you want to dynamically generate some JSON with PHP, then you have to write PHP code to print it out, e.g.:
<?= json_encode( array(
'Contact' => array('ID' => 1, 'Name' => 'Brett Samuel' )
) ); ?>
Also, note that a JSON document has to be a complete object; yours requires another set of curly braces around the whole thing (as output by the above snippet).
you need to use json_encode and json_decode
refer this json php manual

Show php print_r in Flash?

Trying to figure out a way to get ActionScript to print out a php object. In PHP, I can just do print_r, and I'm able to successfully get the object into Flash, but now can't figure out how to print out the object using ActionScript 3?
Well, when the request first comes over, there is always URLLoader.data, which is data in its raw form. If you're looking to get the data from a JSON-style object, there is for( var i:String in obj ). If you're looking for things more obscure than that, there is the ability to use describeType. My favorite example of the last one is in the JSONEncoder class.
From PHP, you can encode most objects to JSON using json_encode() (PHP5+). Using the AS3 JSON decoder from as3corelib you can then convert that encoded string into an oject that AS3 con read. After that you can iterate over the object as key/value pairs and output it however you wish.
I think I know what you mean, I had the same need, so I made this
http://www.actionscript.org/forums/showthread.php3?t=266979
scroll to the bottom, there is a description and an .AS file called trace_r that I wrote

Push JSON Encoded Data To Website in what format?

I need to push some JSON data to my website which I would like to read in PHP. What type of file should I make this? A PHP file with the JSON inside of a variable? I understand how to make a text file with JSON encoded data in it, but how do I get this into PHP? Should I use a PHP include with the JSON-encoded data in it assigned to a variable? Or should I read the file from PHP and put the contents into a variable?
Save your json string as plain text, then you can use:
$file = yourfile
$data = file_get_contents($file);
$parsed = json_decode($data);
// compacted:
$parsed = json_decode(file_get_contents($file));
See file_get_contents() and json_decode().
The advantage of doing this (versus storing it in a PHP file then including it) is that now any program or language that understands JSON can read the file.
The question is too vague for a definite "do this" answer, but here are some options and what they might be most suitable for:
Turn the json data into a PHP data structure. If this is a one-time thing (meaning you won't be getting a new json file every day or week or hour), then reading a file (file_get_contents) and parsing JSON (json_decode) for every request is a pretty big waste of resources since that data isn't changing on a regular basis. Just turn JSON key/value objects into PHP associative arrays, JSON strings into PHP strings, etc.
Just serve the json file. If this is data that will just wind up going to the client to be used in javascript anyway, there's no need to do anything special with it on the server, just parse the json on the client.
Put it in a database. This may be a little heavy-handed, but if you really need it in PHP and not just the client, and it is going to be changing or growing on a regular basis, it may be worth it to have something that handles this use case appropriately.

dump xml string verbatim to mysql db

I need to dump an xml string (coming into a web service as a POST param), directly into a Mysql DB. The column into which I am writing is currently of type 'text', though I have tried blob as well.
Right now, when I save the string and retrieve it later on using sql, it comes back in a serialized like format, like this:
a:1:{s:14:"<?xml_encoding";s:1502:"UTF-8?><record>
<nodes></nodes>
</record>";}
Whereas, I need to parse that xml as a simplexml object, and hence need it to be better formed.
This is what I am doing codewise:
Accept Post Param in web service
Serialize and store it in DB using doctrine ORM, kind of like
$record->xml_rec = serialize($_POST)
Retrieve it and echo it.
Oddly enough, if I unserialize and echo is upon retrial, I get an array. The array looks like this upon print_f
Array
(
[<?xml_encoding] => UTF-8?><record>
<nodes></nodes>
</record>
)
Still not parse-able by simplexml.
Is this a mysql storage problem or am I doing something wrong with the POST params? I've tried htmlspecialchars to save the string in the db, but similar problems remain.
any help is appreciated, thanks
What you have is a "serialized" php array that you can unserialize by using ... PHP's unserialize function.

Categories