To retrieve json data in jquery request succeeds - php

I have a little funny problem:
I get json data like this:
{"answer0":"IMG_0793.JPG not allowed file size","answer1":"sajty-mira.jpg uploaded","answer2":"\u0433
\u0432\u0441.txt unsupported File type"}
using jquery $.ajax
here I have
success: function(resp)
{
var numFiles = $("#file").get(0).files.length;
for(i=0; i < numFiles; i++){
var answ = "resp.answer"+i;
$('#response').append(answ).css('color', 'black').html('<br>');
}
}
to show each upload status.
So can't make resp.answer0,resp.answer1,resp.answer2 ...
var answ = "resp.answer"+i; not working!
I can do this with php
<?php
for ($i = 0; $i < $numFiles; $i++){
echo"
$('#response').append(resp.answer".$i.").css('color', 'black').append('<br>');
";
}
?>
please help to solve the problem!

You cannot use append() this way (just appending a string):
$('#response').append(answ).css('color', 'black').html('<br>');
Inside append should have a valid html tag:
$('#response').append('<div>' + answ + '</div>').css('color', 'black').html('<br>');

You need to parse json response using
var response = $.parseJSON(resp);
Than you can use response variable.

You can do this by using the eval() function
Like below:
resp = {"answer0":"IMG_0793.JPG not allowed file size","answer1":"sajty-mira.jpg uploaded","answer2":"\u0433\u0432\u0441.txt unsupported File type"}
var i = 1;
var answ = eval("resp.answer"+i);
console.log('answ:'+answ); // This will print answ:sajty-mira.jpg uploaded

Related

Send Multiple images with one JSON request

I was working on building rest API,
Where I want to upload multiple images with one post request.
So here.
I am trying to make an array of base64 string of selected images.
That array is JSON.stringify(images_to_upload) to convert to string.
and send that string as JSON post.
and on server side use json_decode() to decode the string array and save the images.
Is my approach correct?
i am not able to execute JSON.stringify(images_to_upload) as this returns nothing.
is there any better way to handle this?
JAVASCRIPT
$("#UploadImage").click(function(){
var filesSelected = document.getElementById("filesToUpload").files;
var images_to_upload = new Array();
//Loop through each image
for(var i=0;i<filesSelected.length;i++)
{
var fileToLoad = filesSelected[i];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var img_string = fileLoadedEvent.target.result;
//push base64 string in arrray
images_to_upload.push(img_string);
};
fileReader.readAsDataURL(fileToLoad);
}
console.log(JSON.stringify(images_to_upload)); //this doesnt work
data = {
"images_data":JSON.stringify(images_to_upload) ,
};
url = "http://app.com/api/customer/uploadmultipleimg";
$.ajax({
type: "POST",
url: url,
data:data,
success: function(result){
console.log(result);
},
failure: function(errMsg) {
console.log(errMsg);
}
});
});
HTML
<input type="file" name="filesToUpload" id="filesToUpload" multiple="" accept="image/x-png,image/jpeg">
<input type="submit" value="UploadImage" id="UploadImage" name="submit">
I think you might be hitting a race condition. I've updated the code to only make the call to the API when the final image has been processed by the FileReader. This is reliably showing the array and its contents in the console in my test version.
$(document).ready(attach_upload_button_click_handler);
function attach_upload_button_click_handler() {
$("#UploadImage").click(upload_images);
}
function upload_images() {
var selected_files = document.getElementById("filesToUpload").files;
var images_to_upload = new Array();
for (let i = 0; i < selected_files.length; i++) {
var fileReader = new FileReader();
fileReader.onload = function (event) {
images_to_upload.push(event.target.result);
if (i == selected_files.length - 1) {
post_data_to_api(images_to_upload);
}
};
fileReader.readAsDataURL(selected_files[i]);
}
}
function post_data_to_api(images_to_upload) {
console.log(JSON.stringify(images_to_upload));
// CALL API
}

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);
}

Transfer JavaScript Array to PHP array using ajax?

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!

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'];

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