how to pass javascript array to php - php

I want to pass array myWorkout to 'play_workout.php'.
I want 'play_workout.php' to open and display the contents of myWorkout (for this example).
(Once I see that this is working I will parse the data from myWorkout and write it back to a database).
I'm not getting any errors in firebug, but play_workout is not being opened nor is is capturing the array object myWorkout.
I would appreciate a second glance at this.
Thanks as always!
page workout_now.php
<div id="playworkout"><button onClick="playWorkout()">Play Workout</button></div>
JAVASCRIPT
function playWorkout(){
var arr = $("#dropTargetframe > li").map(function(){
return $(this).attr('data-id');}).get();
var myRoutine = arr;
var myWorkout = new Array();
for (var i in myRoutine){
if (myRoutine[i])
myWorkout.push(myRoutine[i]);
}
//array appears like ["4", "5", "1", "4"]
JSON.stringify(myWorkout);
encodeURIComponent(myWorkout);
var url = "http://localhost/RealCardio/play_workout.php";
$.get(url, myWorkout);
page play_workout.php
<?php
...
$arrayWorkout = json_decode($_REQUEST['myWorkout']);
print_r($arrayWorkout);
...
?>

Assuming, that as in your comment the array elements doesn't contain any special chars, just numbers, simply do
var myWorkoutPost=myWorkout.join('x');
Transport this to the server the way you want (form hidden field, AJAX, ..) and in PHP do
$myWorkout=explode('x',$_REQUEST['myWorkoutPost']);

Both PHP and Javascript use JSON encoding so I would say the best way would be to JSON encode the array and then POST it as a hidden field to the PHP page and use JSON decode.
http://www.php.net/manual/en/function.json-decode.php

Encode this array to JSON, send it to php script and recieve it with $_POST.
Finally, decode JSON in php script.

A work flow for almost every structured values 99% of the time it will do.
Use JSON.stringify([1,2,3]) it will give you a string "[1,2,3]".
Encode it with encodeURIComponent("[1,2,3]") you'll have something like this "%5B1%2C2%2C3%5D"
Now it's save to be sent to PHP or any other server side language try to use XMLHttpRequest or better jQuery.get() to send the values to PHP.
In php you'd do this:
- $arrayOfValues = json_decode($_REQUEST['name_of_parameter']);
- print_r($arrayOfValues);
Normally you'd need to include JSON library to support old browsers. More info on JSON.

Related

Is it possible to send variables back from PHP to AJAX after AJAX to PHP request?

I have an AJAX request that fetches some info from a SQL database in PHP.
The problem is, I need to send it back to AJAX in variables. Not to just echo it all out on screen.
Is this possible? If so, how would I go about doing something like this?
Thanks.
Yes, you could json_encode the variable you want to send back to client.
echo json_encode( array('variable' => 'your value' ) );
The client will receive the data through a callback when the request is completed. Without more clarification on specifics that's all i can offer, with some more details i can provide code samples depending on whether you're using a JavaScript library such as jQuery or doing a raw XHR request.
Edit: so in jquery to retrieve the variable above you would do the following.
$.getJSON('yourfile.php', function(data){
console.log( data.variable );
});
If I understand you right, you'll want to build a php array and use json_encode to dump the array out as your response. Then in JS you can use the resutling JSON text to form an object.
ajaxpage.php
$resultArray = buildArrayOfItems('Select * from products order by price');
//I usually have my sql records returned directly as an array.
//that's all buildArrayOfItems does
die(json_encode($resultArray));
The PHP should yield something like this
results
{[
{
"id" : "2643",
"name" : "Leather Jacket",
"price" : "249.99"
},
{
"id" : "2645",
"name" : "Suede Jacket",
"price" : "289.99"
},
...
]}
and your JS will look like this (if you're using jQuery)
JS
$.getJSON('ajaxPage.php', {'someVariable':'someValue'}, function(obj){
console.log(obj.count); //will show number of resulting items
console.log(obj[0].id); //will show id of first item (2643)
});
//If you do not use jQuery, you'll need to use eval() or something evil like that
//to convert the string to an object
This site has a great example regarding what you're trying to achieve. http://ditio.net/2008/07/17/php-json-and-javascript-usage/
In short you'll want to use php's json_encode() to convert an array into a json compatible string and each that back to the client.
If you're using jQuery then you'll need to dataType property of $.ajax() to "json", from there you can interact directly with the response as a json object.
If you're using the standard XmlHttp.
var json = JSON.parse(xmlHttp.responseText);
You can always return something like:
echo "code you need to send back to AJAX &&& response text"
Then you can subdivide it into 2 variables with text.split("&&&").

decode json as html

So I'm building a web application and I have an ajax request that pings a database (or database cache) and echos back a big thing of json. I'm totally new to json, and when the php pulls from the database I echo json_encode($databaseResults), then it shows up in my html page as a long string. My question is, how do I convert it and pull out the pieces I need into a nice format?
Thanks!
The Json result that was in the page looks like:
"[{\"currentcall\":\"1\",\"timecalled\":\"15:30\",\"etaTime\":\"15:35\",\"departmentID\":\"1\",\"memberID\":\"1\",\"callinnum\":\"1\",\"location\":\"Fire House\",\"billed\":\"N\",\"date\":\"2\\/12\\/11\",\"firstName\":\"Phil\",\"lastName\":\"asdf\",\"email\":\"pasdf#gmail.com\",\"homephone\":\"+19111111111\",\"cellphone\":\"+11234567891\",\"cellphone2\":null,\"workphone\":null,\"phonenumber5\":null,\"phonenumber6\":null,\"streetAddress\":\"10 asdfnt Dr\",\"city\":\"\",\"username\":\"pgsdfg\",\"password\":\"0623ab6b6b7dsasd3834799fbf2a08529d\",\"admin\":\"Y\",\"qualifications\":\"Interior\",\"rank\":null,\"cpr\":null,\"emt\":null,\"training\":null,\"datejoined\":null,\"dateactive\":null,\"state\":\"DE\",\"zip\":\"51264\",\"pending\":\"NO\",\"defaultETA\":\"7\",\"apparatus\":\"asdKE-286\"}]"
There can be multiple results... this is only one result
EDIT:
Basically, I'm trying to pass a bunch of rows in an array into an html file, and take out only the data I need and format it. I don't know if json is the best way to do this or not, just one solution I came up with. So if anyone has a better solution that would be awesome.
Edit2:
This is the jquery I have that makes the request, the php just has echo json_encode ($DBResults);
function getResponder(){
var responders = $.ajax({
type : "POST",
url: "/index.php/callresponse/get_responders",
success: function(html){
$("#ajaxDiv").html(html);
}
});
setTimeout("getResponder()", 10000);
}
As you flagged this as jquery I assume that you're using jQuery. If you're only going to get the one string you can skip the json part and use jQuery .load() like this $('#result').load('ajax/test.php'); that will load the contents from ajax/test.php into #result
However if you want to use json you can take a look over at getJSON on the jQuery documentation. You can also use the jQuery parseJSON function which will return the json an javascript object containing the jsonData.
Here's an example how you can use parseJSON
var object = $.praseJSON(jsonString); //jsonString is the string containing your actual json data
alert(object.location) //Will alert "Fire House" with the given json string
Here's an example of how you can use getJSON in the same way
$.getJSON('ajax/test.php', function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
});
If you want to pass parameters as well you can do it like this
$.getJSON('ajax/test.php',
{
Param1 : "Value1",
Param2 : "value2"
},
function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
}
);
If you are trying to send json from javascript to php you can use
$jsonArray = jsonDecode($_GET['key']);
Of course if you're using post you'll write $_POST instead.
You have to parse the data into a JSON object, then you can use properties of the object as you wish.
Without seeing the specifics, I can tell you that you'll need to use the JSON object to parse the text. See more here: http://www.json.org
var obj = JSON.parse(ajaxResponseText);
You should use php function json_decode which will give you an object or array with all the properties.
Then you should iterate recursively through this object and add the content of the properties to a string, which should be your final HTML.
Normally to display JSON response in an html element after jquery(for example) by web request, try this:
$("#box-content-selector").append(
"<pre>"+
JSON.stringify(JSON.parse(data), null, 4)+
"</pre>"
)

How exactly do you use json_decode to pass a javascript array to php?

This is how I got my php array to javascript
echo 'var daysofweek = '.json_encode($daysofweek).';';
Now I am aware that json_decode can do the opposite, however the problem is I don't know the syntax to do so.
I tried:
<script>
var array_days = new Array();
array_days[] = "psdfo";
array_days[] = "bsdf";
<?php
$array_days = json_decode(?>array_days<?php);?>
</script>
yes im clueless.
I forgot to mention that I want to send an array through post, having all my information regarding all the form values dynamically created by javascript. Otherwise, I wouldn't know which name="" to look for as it will be decided by the user. Unless someone else has an alternative solution...
PHP is a pre-processor and can't do what you're asking. You would need the PHP engine to be able to process the javascript on the page. json_decode is for decoding a json string in PHP.
To do that you would have to pass the javascript array to a PHP script using something like Ajax so your PHP script can process it anyway you would need, then pass back the result to your Javascript code.
<script>
var array_days = new Array();
array_days[] = "psdfo";
array_days[] = "bsdf";
<?php
$array_days = json_decode(?>array_days<?php);?>
</script>
I'm clueless in this part... is this javascript? if so, you need to use a JSON Parser like the JSON2.js https://github.com/douglascrockford/JSON-js
this file creates a Javascript JSON Object which allows you to parse a JSON string to a Javascript object. (you can always use eval() but it won't prevent against possible malicious code...) or the other way around... from a Javascript Object transform into a JSON string.
After converting to a JSON string you just need to send the data through AJAX to a PHP file, like:
var data = {
key: value,
key2: value2
},
JSON = JSON.stringify(data);
$.ajax({
url: 'php_file.php',
type: 'POST',
data: JSON,
success: function(data){
alert(data)
}
});
(I'm using jQuery to save some lines...)
Then on the php_file.php you would have something like this:
<?php
$json = json_decode($_POST['data']);
foreach($json as $value){
//Do something with it!
}
?>
Yes as the Wajiw said, PHP is pre-processor. But I think it might be possible with the ajaxed request.
Send the Javascript array as an argument request to the other page and process it with the php, and again display back the results.
Note: Never tried this :)
Thanks
First of all:
array_days[] = "psdfo";
array_days[] = "bsdf";
These lines are valid PHP but not valid JavaScript. The correct equivalent would be:
array_days.push("psdfo");
array_days.push("bsdf");
On to passing the resulting array of strings (that's what I am assuming) to PHP. To send it as form data in pure JS, we can create hidden input elements when the form is submitted (try it):
<form id="myform" method="POST" action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi">
<input type="submit" value="Submit">
</form>
<script>
document.getElementById('myform').onsubmit = function() {
for(var i = 0; i < array_days.length; ++i) {
var inputElement = document.createElement('input');
inputElement.type = 'hidden';
inputElement.name = 'array_days[]';
inputElement.value = array_days[i];
this.appendChild(inputElement);
}
};
</script>
PHP will interpret each input having the name of array_days[] as an array element of $_POST['array_days']. For example, you can access $_POST['array_days'][0] in PHP.
For AJAX, jQuery 1.4 and above will automatically achieve this effect when you pass an array as a data parameter to $.ajax.
Why not json_decode()? The answer is that older versions of web browsers do not support the JavaScript function JSON.stringify() that is equivalent to PHP's json_encode(), although there is a library to add support. One might consider it for a more complex case, but for such a simple case, it should not be necessary.

How to return and process an array returned by a php file using ajax?

I've a php file which processes a query and returns an array.
How do i get these and array and parse them and display them using ajax.
I call the file using ajax. Its used to display the matching products while typing a text box with the price...
responseText doesn't return anything...
Your data needs to be encoded in a format that JavaScript can understand, like JSON. You want to serialize the PHP array and return that as the HTTP Response, more information on how to JSON serialize data can be found here. Once the data is serialized, you can parse it in the ResponseText as though it were a JavaScript object (i.e. you can pull data like this: ResponseText[0].some_key)
I should note that jQuery makes this very, VERY easy. Like... this easy:
var url = '/json-data.php?id=2';
$.getJSON(url, function(data) {
$("#target").text(data.some_key);
}

What's the best way to send JavaScript array to PHP script using GET?

I have an interactive web application powered by jQuery where users can manipulate visual objects on the screen. When done, the "state" of JavaScript objects should be sent to PHP to store into database. I'd prefer to use GET for this, but solution that uses POST to submit the data is also viable.
I'm currently thinking to serialize all JS objects using something like base64 encoding and just use something like:
var str = encode_objects();
document.location = 'result.php?result='+str;
However, something tells me there has to be some, more elegant, way than writing my own base64 encoding function in JavaScript. Isn't there something already built into JavaScript that can do the job?
Update: decoding in PHP is not the problem. I know how to decode base64, JSON, whatever in PHP. The problem is how to encode data on JavaScript side.
AJAX is out of the question. It has to be a clean GET or POST with page reload.
json_decode() should serve you well here.
If you simply append a string containing the JSON representation of your javascript object to your HTTP request, you can json_decode() it in PHP and have a PHP object ready to go.
Edit: I should mention that this page has a link to a Javascript JSON stringifier, which will convert your JS objects into the necessary JSON.
first of all, if you're updating the objects state, it should be a POST. try to keep all your GET idempotent.
second, even if you don't want to do any AJAX, JSON is still your friend. the easiest way would be to serialize your objects into JSON and send the resulting string in the POST dataload. there are many ways to decode JSON in PHP, and you're all set.
You can use this serialize function, and then unserialize it on the PHP end.
GET or POST will probably depend on the size of your data : there is a limit on the amout of data you can pass through GET (something like 2000 bytes ; more, depending on the browser).
There is also an other thing to take into account : if you are modifying data, you should use POST ; not GET, which is used to... get... data.
About the format, I would really not go for anything like a custom function doing any kind of stuff like base64 : I would definitly go for JSON, which is a native Javascript notation.
You can for instance have a look at :
wikipedia
http://www.json.org/
There are many JS libraries that can generate JSON (probably every JS Framework can ; and there are standlone libraries like this one) ; and since PHP 5.2 there are functions in PHP to encode/decode it (see json_encode and json_decode)
If it's just a simple flat array you don't need to do anything fancy, as PHP has a built in feature to parse array syntax from GET/POST variable names. Rough example below.
Javascript side:
// Do the parameter-building however you want, I picked the short/messy way
var arrayvalues = [1, 2, 'a'];
var querystring = "var[]=" + arrayvalues.join("&var[]=");
querystring += "&var[something]=abcdef";
// querystring is now "var[]=1&var[]=2&var[]=a&var[something]=abcdef"
PHP side:
var_dump($_POST);
// Remember to validate the data properly!
if ( is_array($_POST['var']) ) {
count($_POST['var']);
echo $_POST['var']['something'];
array_map('do_something_interesting', $_POST['var']);
}
I've used Jquery/JSON.
var jsonArray = $.toJSON(jsArray);
Then sent it via JQuery/Ajax

Categories