am trying to handle an array comes from php file after submitting the form data , the value of data after submitting the form is = ARRAY but i cant use this array in any way , any idea how can i handle this array !!!!
Javascript :
$('#file').live('change',function(){
$('#preview').html('');
$('#preview').html('<img src="loader.gif" />');
$('#data').ajaxForm(function(data){
$(data['toshow']).insertBefore('.pic_content').hide().fadeIn(1000);
}).submit();
});
PHP :
....
....etc
echo json_encode(array('toshow'=>somedata,'data'=>somedata));
JSON String come from server
{"toshow":"\r\n\t\t\t\t\r\n\t\t<table class=\"out\">\r\n\t\t\t<tr ><td class=\"img\"><a title=\"2012-06-02 01-22-09\" rel=\"prettyPhoto\" href=\"img\/2012-06-02 01-22-09.284.jpg\"><img src=\"img\/thumb\/2012-06-02 01-22-09.284.jpg\"\/><\/a><\/td><\/tr>\r\n\t\t\t\r\n\t\t\t<td>\r\n\t\t\t\t<table cellSpacing=\"1\" cellPadding=\"0\">\r\n\t\t\t\t\t<tr><td class=\"data\"><span class=\"click\">2012-06-02 01-22-09<\/span><\/td><\/tr>\r\n\t\t\t\t\t<tr><td class=\"data\"><span class=\"click\">Download<\/span><\/td><\/tr>\r\n\t\t\t\t\t<tr><td class=\"data\"><a href=\"img\/2012-06-02 01-22-09.284.jpg\"><span class=\"click\">View<\/span><\/a><\/td><\/tr>\r\n\t\t\t\t<\/table>\r\n\t\t\t<\/td>\r\n\t\t\t<\/tr>\r\n\t\t<\/table>","span":"<span class='text'><img src='greencheck.png'\/>2012-06-02 01-22-09 Uploaded ,File Size =152Kb <\/span>"}
better to convert array to json format using json_encode($array). json data can easily be handled by Javascript
You can't echo array directly, it will output Array only.
You need to use json_encode.
echo json_encode($your_array);
You can handle the array via PHP also with jQuery
for jQuery use - jQuery each
for PHP use - foreach or for loop
or try
echo '<pre>';
print_r($array);
echo '</pre>';
In your PHP side you have to insert json_encode($array) AND in the JS side instead of using data['toshow'] use data.toshow.
Hope it helps!
Send out a JSON response, like this from PHP:
<?php
echo json_encode($yourarray);
?>
Then to adapt your AJAX function, do this:
$('#file').live('change',function(){
$('#preview').html('');
$('#preview').html('<img src="loader.gif" />');
$('#data').ajaxForm(function(data){
var jsonData = jQuery.parseJSON(data);
//acess it like
alert(jsonData.toshow); //alert for your testing
$(jsonData.toshow).insertBefore('.pic_content').hide().fadeIn(1000);
}).submit();
});
EDIT *
Changes, update according the plug-in docs.
Having never used the .ajaxForm jQuery plug-in, I went after the documentation, I'm going to put the code here, as clear as possible from what I read, I'm even letting the plug-in parse the response automatically into json.
I didn't see any .ajaxForm().submit(), and there's no need to it according to the docs.
$('#file').live('change',function(){
$('#preview').html('');
$('#preview').html('<img src="loader.gif" />');
$('#data').ajaxForm({
dataType: 'json',
success: function(data){
alert("json string response from php: "+ data.toshow);
$(data.toshow).insertBefore('.pic_content').hide().fadeIn(1000);
}
});
});
dataType makes the plugin parse the response to json alone.
and the success: function(data) happens if there was a response from PHP only.
Implement it carefully, and give link if you still didn't get it right.
Related
I am using jquery iframetransport (for blob uploading) and am forced to access my responses via data.responseText. I am able to embed simple JSON from my PHP such as
echo json_encode(array("response"=>"hello"));
And my console log will return
{"response" : "hello"}
But I need divs and to concat data from my PHP requests. I fail right away if I try to embed this:
echo json_encode(array("response"=>"<div>hello</div>"));
I end up with
{"response":"hello<\/div>"}
What can I do to have this kind of json data in a resposneText?
Alternatively you could cast htmlentities() to the response array. Like this:
echo json_encode(array('response' => htmlentities('<div>hello</div>')));
// {"response":"<div>hello<\/div>"}
exit;
On retrieving responses, since you're expecting JSON, add the dataType: property:
$.ajax({
url: 'blahblah.php',
dataType: 'JSON', // this one
});
I have a PHP file myFile.php that echoes a random string from an array of strings into the screen. I want to run that php file and have the output pop up in a javascript alert. I took a crack at the syntax with alert($.ajax({ url: 'getRejection.php' }));
But it is not quite right , it alerts [object Object].
How do I do this?
According to the jquery documentation for ajax: http://api.jquery.com/jQuery.ajax/
You want to use the success callback to run when the ajax call succeeds.
$.ajax({
url: 'getRejection.php',
success: function(data) { alert(data) }
});
Also, a note of advice: use full paths for urls, not relative url paths. Like this url: '/getRejection.php' not like this url: 'getRejection.php'
You may use JSON by making your php file to echo its output in JSON format as follows:
echo "{\n";
echo "\"txt\":";
echo $TheRandomText;
echo "\n";
echo "}";
The previous step may be easily done as Joe Frambach suggestion like the following:
echo json_encode(array('txt' => $TheRandomText));
And then using Jquery do the following:
$(document).ready(function(){
$.getJSON('getRejection.php',{
format: "json"
}).done(function(data){
alert(data.txt);
});
});
However you have to get assured from the path to getRejection.php. In this case it is supposed to be at the same directory with your file.
Also you have to be sured that getRejection.php does not echo anything else text in JSON format to void the corruption of JSON query.
I am trying to get data from an SQL Database through jQuery, Ajax and PHP.
Here is the jQuery Code
$.ajax({
url: 'OpenQuiz.php',
data: '',
dataType:'json',
success: function(data) {
var one = data[0];
}
}
$(document).ajaxComplete(function(event,request,settings) {
alert("check");
}
Here are the json encode lines at the end of the PHP file called "OpenQuiz.php"
echo json_encode($QuizName);
echo json_encode($options);
echo json_encode($votes);
echo json_encode($row_num);
echo json_encode($percentage);
echo json_encode($TruncPercentage);
Please note:
$options, $votes, $Percentage and $TruncPercentage are all two-dimensional arrays.
$row_num is an integer.
$Quiz_Name is a single-dimensional array.
I find that the jQuery runs fine and the ajax request is called because the alert box for "check" shows up. The problem is that I dont know how to access the variables after they have been transferred. I know that it has something to do with data[0] but I don't really understand what "data[0]" means or what it represents. Basically how to I access the variables that I have sent using json_encode in the PHP file?
data[0] is the first json_encoded item in the array returned. You shouldn't json_encode everything separately, you should build an array and json_encode this.
$items = array('QuizName'=>$QuizName,'options'=>$options, ... ,'TruncPercentage'=>$TruncPercentage);
echo json_encode($items);
Then you retrieve with:
success: function(data) {
var qn = data.QuizName,
opt = data.options;
}
And so on for each item, with data.[whatever], and [whatever] being the name of the item you gave it in the array. I know I originally said to retrieve by index (data[0]), but I prefer to retrieve explicitly so that the code is more maintainable.
As a side note, you can eliminate the datatype:'json' declaration in your ajax call by simply setting the header correctly on the PHP side:
header('Content-type: application/json');
Placing that at the top of the document will force the server to recognize the page as json. Far more consistent and explicit than having jQuery look for it.
///////UPDATE - I already have jquery library included to my code so if its easier with jquery than javascript let me know please.
OK. There are loads of questions on here that are sending a JavaScript array to php but only 1 which is the same as mine. Unfortunately I didn't understand the answer.
So, at the moment I have an associative array in php. I then used this code,
echo json_encode($this->_inputErrors);
I don't actualy know why i'm using it, just was mentioned a lot in other examples like this. So that then sends the data to javascript (via ajax) and if i do this code,
alert(requestText);
I get a long line of text. As I imagine i should.
So how do i then in javascript get the text back to an array?
Or Is there a better way to do this?
Many Thanks For Your Time,
Chris
var o = JSON.parse( requestText );
Include this ( https://github.com/douglascrockford/JSON-js/blob/master/json2.js ) to support old browsers.
requestText is a JSON string. You need to parse the string into an object.
You can use JSON.parse to convert the string to JSON.
var obj = JSON.parse(requestText);
If your browser doesn't have JSON, include this:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
You need to set the return type as JSON
or if using jQuery, you can use jQuery's method getJSON() to get the JSON object from the url
Somedays before, I faced the same problem. Check my solution :)
array.html
$(document).ready(function(e){
//This array is where I'll receive the PHParray
var js_array=new Array();
$("#btn").click(function(e){
$.ajax({
type: 'POST',
url: 'vector.php',
cache: false,
success: function(data){
js_array=data;
//I use this "for" to print each array item into a div called "data".
for(var i=0;i<js_array.length;i++){
$("#data").append("<p>"+js_array[i]+"</p>");
}
},
dataType: 'json'
});
});
});
vector.php
<?php
$array = array(1,2,3,4,5,6);
/*As you, I use "json_encode" to serialize the array
echo json_encode($array);
?>
I hope it can help (:
The simplest way to transform that long line of text in Javascript is using eval:
alert(eval('(' + requestText + ')'));
I am getting ajax response in array format from php url. How to extract array response values in jQuery?
FYI:
PHP array is:
$response = array('msg' => 'Hello', 'html' => '<b>Good bye</b>');
I am getting $response array in my ajax response. i.e.
var promo = "promo=45fdf4684sfd";
$.ajax({
type: "POST",
url: baseJsUrl + "/users/calc_discount",
data: promo,
success: function (msg) { // I am getting $response here as ajax response.
//alert(msg);
// Here I want to check whether response is in array format or not. if it is in array format, I want to extract msg here and want to use response array values.
}
});
Let me know answer pls.
Thanks.
You should echo that $response with json_encode().
You should probably set dataType: 'json' too inside the object literal you send to $.ajax().
Then you can access it natively with JavaScript using the dot operator inside your success callback...
function(msg) {
alert(msg.html);
}
BTW, this line...
$response = array(['msg'] => 'Hello', 'html' => '<b>Good bye</b>');
... isn't valid PHP. Remove the brackets from the first key.
My favorite solution for this is to encode array with PHP's function json_encode() so jquery will be happy to parse it.
I presume that you mean a JSON response, like this:
{"msg":"Hello","html":"<b>Good bye<\/b>"}
This is actually a native JS object, so you can use it right away like this:
success: function(msg){
alert(msg.msg);
alert(msg.html);
}
You can also use the jQuery.each() function to loop over all properties of the JSON object if you need to:
jQuery.each(msg, function(key, val) {
alert(key + "=" + val);
});
and If you do not have control over the PHP output then you can use another method to get the result.
Another solution is using http://phpjs.org/ library. Here you can find many functions available in JS as available in php. Usage is also same as that of PHP. So I feel if you get the json_encode/json_decode from there and use that then it can solve your problem easily.
Remember you can compile your needed functions only. In your case, it is json_encode and json_decode. No need to download whole library. Url to compile your library: http://phpjs.org/packages/configure