Transfer JavaScript Array to PHP array using ajax? - php

I am trying to transfer a list of data from a javascript array to a php array and I can't seem to get ajax to do the trick. Can someone show me the code on how to do this? So far here is what I have, which is just the array:
JAVASCRIPT
var dates;
// the dates array is then filled up here
// it contains information in the form {'2012-01-01', '2012-03-12', ...}
$.ajax({
type: "REQUEST",
url: "NAMEOFPHPFILE.php",
data: { sendData1 : dates },
success: function() {
alert("Attempting to transfer array -> AJAX");
}
});
var submissions;
// the submissions array is then filled up here
// it contains information in the form {int, int, ...}
// ect ......... with 3 more arrays using { sendData2 : submissions },
PHP
<?php
$bDates = $_REQUEST['sendData1'];
// need to set this array = to the JavaScript dates array
$bSubmissions = $_REQUEST['sendData2'];
// need to set this array = to the JavaScript submissions array
?>
I would prefer to use the REQUEST method to prevent information logging into the URL. This code also doesn't work when trying POST instead of REQUEST
At the very end of the .php page, I am outputting a bunch of arrays onto a CSV page where I iterate through the arrays and place their elements in the file. This already works, but I need to transfer some of these arrays from javascript to PHP so that I can spit out the data. That looks like this:
<?php
$stringData = "Dates, Number of Lines Changed, , Bug Dates, Arrivals, Fixed, Closed, Hold_";
for($i = 0; $i < sizeof($dataXAxis); $i++){
$date = substr($_REQUEST['Dates'][$i+1], 0, 24);
$stringData .= "$date, $dataYAxis[$i], , $bDates[$i], $bSubmissions[$i], $bCompletions[$i], $bDones[$i], $bRejections[$i]_";
}
echo '<BR><BR>Download Your CSV File';
?>
Why doesn't the AJAX work? The arrays appear empty...

One method would be to try sending the data in the form of JSON. Then using json_decode, you can convert it to an array. Example:
var Json = {"User1":"John", "User2":"Joe", "User3","Jerry"};
var data = "data="+Json;
hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
console.log(hr.responseText);
}
}
hr.open("POST", "parsefile.php", true);
hr.send(data);
Then when you get the data in your PHP file it's something like:
$data = $_POST['data'];
$array = json_decode($data, true);
This all will tell php to turn our data into an assosciative array. It can then be manipulated as an assosciative array.

I was literally just working on this.
jQuery
var group_ids = $('.form-elements li').map(function(){
return $(this).data('group-id')
}).get()
$.get('{{ url('group/update_order_by') }}', {group_ids: group_ids});
PHP from the restful Laravel framework
public function get_update_order_by()
{
$group_ids = Input::get("group_ids");
$group_count = count($group_ids);
for ($i = 0; $i < $group_count; ++$i) {
$group = Group::find($group_ids[$i] );
$group->order_by = $i;
$group->save();
}
return true;
}
Raw PHP (ugh...)
$group_ids = $_GET("group_ids");
$group_count = count($group_ids);
for ($i = 0; $i < $group_count; ++$i) {
echo $group_ids[$i];
}
return true;

The simply convert an array to string
var data = [1,2,"hello"];
var data_str = data.join(",");
and afterwards convert the string to array in php:
$array = explode(",", $_REQUEST["data"]);

In PHP, the REQUEST expects arrays to be passed in the following format:
sendData1[]=first&sendData1[]=second&sendData1[]=third
This is automatically converted into an array:
$sendData = $_REQUEST['sendData`];
echo $sendData[0];
echo $sendData[1];

First, for the sake of simplicity, create an array holding both arrays you want to send and parse:
var request = Array(dates, submissions);
Second, make sure you're sending your request as properly formatted JSON. In addition, when testing I recommend returning the output from the remote file in your callback to see how your data was parsed. I recommend the following implementation, as well as sending via POST:
$.ajax({
type: "POST",
url: "NAMEOFPHPFILE.php",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(request),
success: function(data) {
alert(data);
}
});
In your PHP file, get you can parse the contents of the aforementioned request into an array using the following:
<?php
// convert json data read from the input stream to an array
// *note* you MUST set the true flag in the json_decode() function, otherwise it will convert the data into an object
$request = json_decode(file_get_contents('php://input'), true);
var_dump($request);
You should now get an alert containing the var_dump of the array(looks messy, I know!).
This should be enough to get you started, hope it helps!

Related

Get json from php session instead of json file

I have this jquery function
function updateStatus(){
$.getJSON("<?php echo $_SESSION['filnavn']; ?>", function(data){
var items = [];
pbvalue = 0;
if(data){
var total = data['total'];
var current = data['current'];
var pbvalue = Math.floor((current / total) * 100);
if(pbvalue>0){
$("#progressbar").progressbar({
value:pbvalue
});
}
}
if(pbvalue < 100){
t = setTimeout("updateStatus()", 500);
}
});
}
Is it possible to get the JSON from a PHP session variable instead of a json file?
As I have understood I can get the session data from the session like this:
//json test
var jsonstr = $_SESSION['json_status'];
//parse json
var data = JSON.parse(jsonstr);
But I do not know how I can do that with out the getJSON function?
You're reading too much into it. .getjson is just a $.ajax() call that EXPECTS to get a json reponse from the server. That's all.
It doesn't matter WHERE PHP gets data from, as long as it spits out json text.
Whether that json text was just retrieved from a file/db, or dynamically generated with json_encode(), as long as the browser receives json text, things will "work".
Your best bet here is to create a php file that can act as the target of getJSON that returns the json from your session.
<?php
session_start();
if (isset($_SESSION["filnavn"])){
echo $_SESSION["filnavn"];
// Or, if the key contains an object instead of a json string, use
// echo json_encode($_SESSION["filavn"]);
} else {
// echo the json you want here if the session variable is not set
echo "{}";
}
?>
Then in your jquery code change the getJSON to this
$.getJSON("/path/to/php/file.php", function(data){...});

Add data into multi-dimentional array with javascript

[File
{ size=295816, type="image/jpeg", name="img_new3.JPG"},
File { size=43457, type="image/jpeg", name="nature.jpg"}
]
this is the data that i received from the script now i have to send only size and the name of the file with to the php file through ajax.
here is my code
var files = [];
files["file"] = [];
// file is an object that has the above result
for( var i=0, j=file.length; i<j; i++ ){
console.log( file[i].name );
files["file"][i] = file[i].name;
files["file"][i] = file[i].size;
}
// Send Request to Create ZIP File
console.log(files)
i want to access the params for my PHP file:
file(
name=>array(
0=>"name",
1=>"size"
),
size=>array(...)
)
how do i make an array that send the data to PHP file like the above?
First of all you have to use the Object notation, not Array, and then you can pass it to your PHP function via Ajax.
var files = {};
files["file"] = [];
// file is an object that has the above result
for (var i = 0, j = file.length; i < j; i++ ){
console.log(file[i].name);
files["file"][i] = file[i].name;
}
And then use that array with JSON.stringify to pass data to your PHP script like this:
$.ajax({
url: "your url",
type: "POST", //can be get also, depends on request
cache: false, //do you want it to be cached or not?
data: {files: JSON.stringify(files)},
success: function(data) {
//do something with returned data
}
});
Anyway I suggest you changing the way you store your data. Objects are very useful in this case:
var files = [];
// file is an object that has the above result
for (var i = 0, j = file.length; i < j; i++ ){
console.log(file[i].name);
files.push({
name: file[i].name //you can add all the keys you want
});
}
You have js array ready so just use the jQuery post method to send the created array to the php file which then processes the array the way you want it to.
Your multidimensional array can be JSON encoded and sent as a string via ajax to the PHP script, which can decode the JSON back to an array/object:
// assuming the array is in files var
$.ajax({
url : 'page.php',
type : 'POST',
data : { myFiles : JSON.stringify(files) },
success : function(response){
console.log("successfull");
}
});
On the PHP side:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$filesArray = json_decode($_POST['myFiles']);
print_r($filesArray);
}

JSON_decode two dimensional array of objects?

I have a two dimensional array of objects like so:
function test(n){
this.id = n;
}
var testArray= new Array(2);
for(i = 0; i < testArray.length; i++){
testArray[i] = new Array(2);
for(j = 0; j < testArray[i].length; j++){
testArray[i][j] = new test((2*i)+j);
}
}
I then stringify it to post using AJAX like so:
var data = {testA: {testB: testArray[0], testC: testArray[1]}}
var text = JSON.stringify(data);
Once I perform the jquery AJAX call:
$.post("test.php",text,function(data){
alert(data);
});
I cannot work out how to decode and use this object on the PHP side, so far i've tried something like this:
<?php
$data = json_decode($_POST);
if($data == null){
echo "fail";
} else {
echo $data;
}
?>
But I get an error that says it expects a string and I'm passing it an array. I've also tried something like
$data = json_decode($_POST['testA']);
and then error doesn't appear but instead it always outputs "fail".
Does anyone know what I need to do on the PHP side so I access the data?
Why would you run stringify on it? If you just send it like this:
$.post("test.php", data, function(data) {
You should be able to retrieve it like this:
$data = $_POST['testA'];

Split POST array into multiple variables

I'm coding a form right now using jQuery .post and the file responsible for processing has the code:
print_r($_POST);
Which returns the following dynamic output:
Array ( [data] => capacity=50-1000+people&bookingdate=17%2F04%2F2012&grade=1+star )
I am trying to split up this array into three variables namely capacity, booking date and grade but don't really know how to. Any idea how? I've tried using echo $_POST["capacity"]; but it doesn't work.
Thanks in advance!
Edit
This is the jQuery I'm using:
<script type="text/javascript">
$(document).ready(function() {
$("#postData").click(function() {
$("#last-step").hide(600);
$.post('resources/process2.php', { data: $("#task5_booking").serialize() }, function(data) {
$("#result").html(data);
});
return false;
});
});
</script>
which is working with the following form:
http://jsfiddle.net/xSkgH/93/
I think you should change this line:
$.post('resources/process2.php', { data: $("#task5_booking").serialize() }, function(data) {
To
$.post('resources/process2.php', $("#task5_booking").serialize(), function(data) {
Notice that I changed the second parameter from an object literal to a (url-encoded) string. This posts each variable in your form as a separate variable (as if it were posted directly). On the server side, each variable should be available separately inside $_POST array.
Have a go with parse_str()
Something like:
parse_str($_POST['data'] , $output);
$capacity = $output['capacity'];
$bookingdate = $output['bookingdate'];
$grade = $output['grade'];
You have to use explode for this.
$data = array(); // A array to store the extracted value
$temp = explode("&", $data); // First of all explode by "&" to get the each piece
foreach($temp as $tval) {
$t = explode('=', $tval); // Next explode by "=" to get the index and value
$data[$t[0]] = $t[1]; //Add them to the array
}
Another alternative is to use parse_str():
$data = array();
parse_str($_POST['data'], $data);
After this all the values will be mapped to the $data

Sending JSON via AJAX to PHP using jQuery

I am trying to send JSON to a PHP file using jQuery AJAX, basically what I am trying to do is get the values and id's of a bunch of child elements and then assign them to a JSON object and then send that object via ajax to the PHP file which would then process it and enter it into a database.
Here is my code,
Javascript/jQuery:
function test(){
var selects = $('#systems_wrapper').find('.dropDowns');
var newArray = new Array();
selects.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
var o = { 'id': id, 'value': val };
newArray.push(o);
});
$.ajax({
type: "POST",
url: "qwer.php",
dataType: 'json',
data: { json: newArray }
});
}
PHP:
<?php
$json = $_POST['json'];
$person = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $person);
fclose($file);
echo 'success?';
?>
It creates the file, but it is completely blank, any idea what it could be?
Thanx in advance!
You could try using the JSON.stringify() method to convert your array into JSON automagically. Just pass the output from this.
data: { json: JSON.stringify(newArray) }
Hope this helps
Don't use an array.
use a simple string like this:
var o = '[';
selects.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
o += '{ "id": "'+id+'", "value": "'+val+'" },';
});
o = o.substring(0,o.length-1);
o += ']';
and in the ajax just send the string 'o'
data: { json: newArray }
in the php file just make a json_decode($json, true);
it will return an array of array that you can access by a foreach
if you want to see the array, use var_dump($person);
You should set a contentType on your ajax POST. I would use contentType: "application/json";
You should use json_encode() not json_decode()! This way you will get the json string and be able to write it.
No need to use json_decode if you're saving it to a text file. jQuery is encoding your array in JSON format, PHP should then just write that format right to the text file. When you want to open that file and access the data in a usable way, read its contents into a variable and THEN run json_decode() on it.

Categories