PHP:
header('Content-Type: application/json');
//Some code
$files_arr['BadIMG'][$i] = $fileName;
//Some code
$files_arr['GoodIMG'][$i] = $path;
//Some code
echo json_encode($files_arr);
JS:
success: function(response) {
console.log(response.BadIMG);
console.log(response.GoodIMG);
for (var i = 0; i < response.GoodIMG.length; i++) {
var src = response.GoodIMG[i];
$('#fast-reply_textarea').focus().val($('#fast-reply_textarea').val() + '\n[img]https://url/' + src + '[/img]\n');
}
}
If from PHP received only GoodIMG, all it`t ok and in #fast-reply_textarea successfully added links for images:
console.log(response.BadIMG);
undefined
console.log(response.GoodIMG);
Array [ "1_Good.jpg", "2_Good.jpg" ]
But if from PHP received GoodIMG + BadIMG nothing inserted in #fast-reply_textarea:
console.log(response.BadIMG);
Array [ "1_Bad.jpg", "2_Bad.jpg" ]
console.log(response.GoodIMG);
Object { 2: "1_Good.jpg", 3: "2_Good.jpg" }
And if from PHP received onlly BadIMG:
console.log(response.BadIMG);
Array [ "1_Bad.jpg", "2_Bad.jpg" ]
console.log(response.GoodIMG);
undefined //With error:
Uncaught TypeError: can't access property "length", response.GoodIMG is undefined
How to parse this data if received BadIMG together with GoodIMG and add GoodIMG links in editor?
For BadIMG I will add alert, like as: From (Count all images) images (Count or Names of BadIMG) not uploaded.
You could remove the $i index in your arrays in PHP.
$files_arr['BadIMG'][] = $fileName;
$files_arr['GoodIMG'][] = $path;
In this case, both will be arrays, not objects.
Also, in JS, you should test if the variables are defined or not.
success: function(response) {
if (typeof response.GoodIMG !== "undefined") {
for (var i = 0; i < response.GoodIMG.length; i++) {
var src = response.GoodIMG[i];
$('#fast-reply_textarea').focus().val($('#fast-reply_textarea').val() + '\n[img]https://url/' + src + '[/img]\n');
}
}
}
Related
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
[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);
}
I am working on extjs 4 project. In this project I have to communicate back and fourth between js and php files. So to call php from js, I am using Ext.Ajax.request.
var dirs = [];
Ext.Ajax.request(
{
url: 'text.php',
method: 'GET',
success: function(response)
{
dirs = JSON.parse(response.responseText);
},
failure: function(response)
{
alert('server-side failure with status code ' + response.status);
}
});
// Creating dropdown list menu
document.write("<select class='select'>");
for (var i = 0; i < dirs.length; i++)
{
document.write("<option>" + dirs[i] + "</option>");
}
document.write("</select>");
php code is the following:
<?php
$filepath = "scenarios";
$dirs = array();
$files = array();
$scenes = array_diff(scandir($filepath), array('..', '.'));
for ($i = 2; $i < count($scenes)+2; $i++)
{
if (strpos($scenes[$i], '.'))
{
array_push($files, $scenes[$i]);
}
else
{
array_push($dirs, $scenes[$i]);
}
}
if (count($dirs) > 0)
{
echo json_encode($dirs);
}
else
{
echo json_encode("You do nat have any projects. Please create new project.");
}
?>
Now the problem appears in the part where I want to generate list menu from the resulting dirs object. In the firebug DOM dirs = ["google","yahoo"], but in the loop, dirs.length returns 0???
Also when I put alert(dirs.length) before the for loop, it shows 0, then correctly generates the list menu...weird????
The request call is asynchronous which means, that after calling Ext.Ajax.Request, the next instruction is your loop. But you haven't received the data from the server yet. You need to put the loop in the success callback to make sure that you'll execute it after getting the data from the server.
var dirs = [];
Ext.Ajax.request(
{
url: 'text.php',
method: 'GET',
success: function(response)
{
dirs = JSON.parse(response.responseText);
// Creating dropdown list menu
document.write("<select class='select'>");
for (var i = 0; i < dirs.length; i++)
{
document.write("<option>" + dirs[i] + "</option>");
}
document.write("</select>");
},
failure: function(response)
{
alert('server-side failure with status code ' + response.status);
}
});
Also when I put alert(dirs.length) before the for loop, it shows 0,
then correctly generates the list menu...weird????
This is because the alert stop the execution flow of your program until you click on "ok". The data are probably coming from the server during this time, and the dir variable is populated with them.
I can't see any headers being sent out - which is required by most browsers:
header('content-type: application/json; charset=utf8;');
if(sizeof($dirs) > 0){
echo json_encode(array('success' => true, 'data' => $dirs));
}
else {
echo json_encode(array('success' => false, 'error' => 'You do not have any projects.' ));
}
The JavaScript:
var xhr = new Ext.data.Connection();
xhr.request({
url: '/text.php',
method: 'GET',
headers: {'Accept':'application/json'},
success: function(response, opts) {
var obj=Ext.decode(response.responseText);
var html='';
Ext.each(obj.data, function(v,i){html+='<option>'+v+'</option>';});
html='<select>'+html+'</select>';
console.info(html);
}
});
The HTML generation has to reside in the callback function - else it makes no sense at all.
Without having seen the JSON which is being returned - it's hard to tell what's wrong with it.
Down-voting without leaving a comment why exactly is really lame.
How do I submit an array from dojo to php.
I'm submitting these values:
["a", "b", "c"]
Here's what I got so far:
btn_send.onclick(function(){
var name_array = name_looper();
console.log(name_array);
dojo.xhrPost({
url: "dojo_phpform.php",
content: {names: name_array},
load: function(result) {
var x = dojo.byId('results');
x.innerHTML = result;
}
});
});
function name_looper(){
var names = dojo.query('input[type=text]');
var name_array = [];
names.forEach(function(element, index, array){
name_array[index] = dojo.attr(element, 'value');
});
return name_array;
}
I tried to echo $_POST['names'] from the php file(dojo_phpform.php) and it didn't return any errors. It seems like the array isn't actually submitted. The only thing that's returned is the last item in the array. What do I do?Please help, Thanks in advance!
I just tested this with grails and php. In grails I have no problem getting an array submitted through a dojo xhrPost : I retrieve the array properly parsed with all its values as expected.
If I post :
dojo.xhrPost({
content : {
names : ['foo', 'bar']
},
url : "mygrailscontroller"
});
I get an array param on the other side. Which proves the problem hasn't to be solved on the dojo side, but on the php side.
In php, if a form input has a variable of type array, its name parameter has to be set with square brackets, like : "names[]" rather than "names".
So... in your case the solution is not to flatten the array into a string (sorry), but to name your array argument with brackets. So it would be :
dojo.xhrPost({
content : {
"names[]" : ['foo', 'bar']
},
url : "myphpcontroller"
});
As far as I've been able to see, dojo's xhr functions don't support it. I'm using a helper function to "flatten" parameters myself.
_flattenXhrParams: function(params)
{
var newParams = {};
for(var key in params)
{
if(dojo.isObject(params[key]))
{
for(var innerKey in params[key])
{
newParams[key + "[" + innerKey + "]"] =
params[key][innerKey];
}
}
else if(dojo.isArray(params[key]))
{
for(var i = 0, l = params[key].length; i < l; i++)
{
newParams[key + "[]"] = params[key][i];
}
}
else
{
newParams[key] = params[key];
}
}
return newParams;
}
It's butt ugly, I know, and obviously only works on one dimensional arrays/objects. In your case, you'd do:
dojo.xhrPost({
url: "dojo_phpform.php",
content: _flattenXhrParams({names: name_array}),
load: function(result) {
var x = dojo.byId('results');
x.innerHTML = result;
}
});
.. and you'd get POST parameters like names[]=a&names[]=b&names[]=c. For objects, you'd get names[somekey]=a&names[otherKey]=b etc. PHP handles both nicely.
I'm pretty sure the values of the content object only take strings. If you want to submit an array, you'd have to turn it into JSON and then json_decode it on the server.
First off sorry if I'm missing something simple just started working with AJAX today. I have an issue where I'm trying to get information from my database, but different records have different amounts of values. For instance, each record has a "features" column. In the features column I store a string. (ex: Feature1~Feature2~Feature3~Feature4... ) When I'm building the object I take apart the string and store all the features into an array. Some objects can have 1 feature others can have up to whatever. So... how do I return this values back to my ajax function from my php page? Below is my ajax function that I was trying and I'll provide a link with my php file. [ next.php : http://pastebin.com/SY74jV7X ]
$("a#next").click(function()
{
$.ajax({
type : 'POST',
url : 'next.php',
dataType : 'json',
data : { nextID : $("a#next").attr("rel") },
success : function ( data ) {
var lastID = $("a#next").attr("rel");
var originID = $("a#next").attr("rev");
if(lastID == 1)
{
lastID = originID;
}
else
{
lastID--;
}
$("img#spotlight").attr("src",data.spotlightimage);
$("div#showcase h1").text(data.title);
$("div#showcase h2").text(data.subtitle);
$("div#showcase p").text(data.description);
$("a#next").attr("rel", lastID);
for(var i=0; i < data.size; i++)
{
$("ul#features").append("<li>").text(data.feature+i).append("</li>");
}
/*
for(var j=1; j < data.picsize; j++)
{
$("div.thumbnails ul").append("<li>").text(data.image+j).append("</li>");
}
*/
},
error : function ( XMLHttpRequest, textStatus, errorThrown) {
$("div#showcase h1").text("An error has occured: " + errorThrown);
}
});
});
First replace the below in your next.php file:
for ( $i=0; $i < $arraySize; $i++ )
{
$return['feature'.$i.''] = $features[0];
}
With:
$return['features'] = $features;
P.S: the current code is wrong you should have ... = $features[$i]; anyway, you don't need that just send the array as is. and then in the JS part replace:
for(var i=0; i < data.size; i++)
{
$("ul#features").append("<li>").text(data.feature+i).append("</li>");
}
With:
$.each(data.features, function(k,v){
var li = '<li>' + v + '</li>';
$("ul#features").append(li);
});
This way, don't need the data.size anymore.