I have the following object that gets created in my javascript application.
poll_data[active_question] = {
'question': $('div.question_wrap textarea').attr('value'),
'answers': [
$('div.answer_wrap input#0').attr('value'),
$('div.answer_wrap input#1').attr('value'),
$('div.answer_wrap input#2').attr('value'),
$('div.answer_wrap input#3').attr('value'),
$('div.answer_wrap input#4').attr('value'),
$('div.answer_wrap input#5').attr('value')
]
};
active_question is set to 'poll', 0, 1, 2, 3, 4, or 5 depending on the question being worked on at the moment. I am trying to post this object to a php script using the following JS code.
$.ajax({
url: '/somewebsite/poll/create?json=show',
type: 'POST',
// dataType: 'json',
data: poll_data,
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert(data);
}
});
My PHP code is very simple.
echo json_encode($_POST); exit;
When I run the script and click the button that triggers the submission of the data, I receive the alert (so the actual ajax code works), but the result from my PHP script is just an empty array. I think that this is an issue with the way the object is constructed, but I am not sure, and have not been able to find a work around.
Thanks in advance.
Okay, a few things:
poll_data is not a valid JSON object. You would have to use poll_data[active_question], which IS a valid JSON object. jQuery should serialize this correctly. Remove the contentType -- I am pretty sure that is for php (not positive) but your code wouldn't work for me until I removed it. Finally, the appending of json=show to the query string doesn't do anything..it will just be ignored.
A couple minor things too: you can use .val() instead of .attr('value'), and have you looked into .serialize() to create your post data for you?
do this on server
$data;
$data->question=$_POST['question']
$data->answer=$_POST['answers']
echo json_encode($data);
do this for ajax request
$.ajax({
url: '/somewebsite/poll/create?json=show',
type:'POST',
//modified data proprty
data:poll_data[active_question],
success: function(data) {
alert(data);
}
});
Related
I'm passing a simple JSON array with 4 words to PHP. I want to store that array in a database after I serialize it. Since it's an Ajax call I can only investigate any echoed values by json_encode and alerting them in AJAX success function.
Here's my code:
var jsonString = JSON.stringify(ans);
//if I alert jsonString - it shows the proper array
$.ajax({
type: "POST",
url: "script.php",
data: jsonString,
cache: false,
success: function(data){
alert(data);
},
error: function(){
alert("error");
}
});
That's what I do in PHP with the array:
$answerAr = json_decode($_POST['data']);
$answers = serialize($answerAr);
If I echo the json_encode($answerAr) it alerts NULL in Ajax and $answers turns into 'N;'
Json_last_error returns 0.
If you're posting data directly to PHP, you'll have to use php://input and parse that; data given in JSON isn't form data, and wont auto-populate the request superglobals ($_GET, $_POST).
$data = json_decode(file_get_contents("php://input"));
Most frameworks do this transparently for you and populate a request object with data in it. You should probably check if the request sends JSON data in the body via headers (Content-Type, Accept: application/json, etc)
Alternatively, you can change your AJAX call to give it an array key:
$.ajax({
data: {data: jsonString},
// etc
});
Which will then be accessible as $_POST["data"]
Change your ajax data attribute to like this and try
data: {json: jsonString}
and in the php script you can access it by
$answerAr = json_decode($_POST['json']);
I want to know when will it be reasonable to pull data from a php page via ajax in form of json array.. Suppose I have this code :
$.ajax({
type: "get",
url: "assets/update_cart_user_fstore.php",
data: up,
cache: false,
success: function(r){
$(#item).html(r);
},
});
and in PHP page I am echoing a variable
$hello = "I am code!";
echo $hello;
And with JSON
$.ajax({
type: "get",
url: "assets/update_cart_user_fstore.php",
data: up,
cache: false,
success: function(r){
var obj = jQuery.parseJSON(r);
$('#item').html(obj.code);
},
});
and in PHP I'm echoing the JSON array
$hello = "I am code!";
$response = array();
$response['code'] = $hello;
echo json_encode($response);
Now I know that in case of echoing more than 1 variable JSON is appropriate...But is it necessary here? And am I using JSON properly..?
Please explain..
Is it necessary in this case? No, it isn't.
But using JSON has some advantages, for example
Your data has a strict, standardized structure. This means, less chance for errors.
You can scale it better.
You can debug it easier. For example, Tools like Firebug support JSON
Two good articles, which will go into more detail:
http://www.revillweb.com/articles/why-use-json/
http://blog.programmableweb.com/2013/11/07/xml-vs-json-a-primer/
I've rarely found a use case where I wouldn't prefer JSON.
I want to manipulate a PHParray in javascript. This is the code i'm using.
Array.php
<?php
$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler";
?>
fx_funciones.js
/*Pre-sentences*/
var js_array=new Array();
$.ajax({
type: "POST",
url: "array.php",
success: function(response) {
js_array=response
}
});
This is what I want to do but it's not working.
I think , the answer for above question is already addressed in below link. please check them out.
Get data from php array - AJAX - jQuery
I hope it will help you
Try this:
<?php
$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler";
echo json_encode($sentido);
And:
$.getJSON('array.php', function(sentido) {
console.log(sentido);
});
You'll need to return the array from your PHP code as JSON, using the json_encode function. Then, in your jQuery code, specify a json dataType so that it's implicitly converted and passed to the callback function as an array:
var js_array=new Array();
$.ajax({
type: "POST",
url: "array.php",
success: function(response) {
js_array=response
},
dataType: 'json'
});
Use the standard JSON notation. It serializes objects and arrays. Then print it, fetch it on the client and parse it.
On the server:
echo json_encode($sentido);
For more on PHP's json_encode: http://php.net/manual/de/function.json-encode.php
On the client, this is specially easy if you use the jQuery function for ajax that expect JSON-encoded objects, and parses them for you:
$.getJSON('address/to/your/php/file.php', function(sentidos) {
alert(sentidos[0]); // It will alert "ver"
alert(sentidos[1]); // It will alert "tocar"
});
It uses GET but this most probably what you need.
For more on jQuery's $.getJSON: http://api.jquery.com/jQuery.getJSON/
I'm not sure if there is any way to do this or not, but this would solve so many of my problems if there is a simple solution to this.
What I need/want to be able to do is return HTML and JSON in my success of ajax request. The reason being, I want to request a file and return all of that page, but I also want to be able to return a specified set of information from the page in json, so I can use it for other things.
This is what I'm doing now:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
}
});
This is what I'd like to be able to do:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
$("title").html(json.PageTitle)
}
});
on the page that is being returned, I would specify what I want the title to be. (For instance, if it's a profile, I would return the user's name)
HTML and data wrapped in JSON
You can do it by returning a 2 element JSON array.
The first element contains HTML and the second element contains another JSON array with the data inside. You just need to unwrap it carefully without breaking anything.
Serverside
$html = '<div>This is Html</div>';
$data = json_encode(array('page_title'=>'My Page'));
$response = array('html'=>$html, 'data'=>$data);
echo json_encode($response);
Clientside
//Ajax success function...
success: function(serverResponse){
$("body > .container").html(serverResponse.html);
var data = JSON.parse(serverResponse.data);
$("title").html(data.page_title)
}
Note 1: I think this is what #hakre meant in his comment on your question.
Note 2: This method works, but I would agree with #jheddings that its probably a good idea to avoid mixing presentation and data. Coding karma will come back to bite.
Trying to mix the retun value to contain presentation and data seems like a potential for confusion. Why not split it into two calls and fetch the data on success of the other?
Something like:
$.ajax({
type: "POST",
url: "inc/"+view_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html) {
$("body > .container").html(html);
$.ajax({
type: "POST",
url: "inc/"+data_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(json) {
$("title").html(json.PageTitle);
}
});
});
You also have the option of including the data in html5 data attributes
For instance, if you're returning a list of Animals
<ul id="ZeAnimals" data-total-animals="500" data-page="2">
<li>Cat</li>
<li>Dog</li>
...
</ul>
You can then collect the data you require using
$('#ZeAnimals').data('total-animals')
Sometimes separating your request into two different ajax calls makes sense also.
You may use a library that does that automatically, like http://phery-php-ajax.net. Using
Phery::instance()->set(array(
'load' => function(){
/* mount your $html and $json_data */
return
PheryResponse::factory()
->json($json_data)
->this() // points to the container
->html($html);
}
))->process();
$(function(){
var $container = $('body > .container');
$container.phery('make', 'load'); // or $container.phery().make('load')
$container.bind('phery:json', function(event, data){
// deal with data from PHP here
});
$container.phery('remote');
});
You may, as well, use phery.views to automatically load a portion of the site automatically, without having to worry about client-side specific code. You would have to put a unique ID on the container, container in this example:
$(function(){
phery.view({
'#container': {}
});
});
Phery::instance()->views(array(
'#container' => function($data, $params){
/* do the load part in here */
return
PheryResponse::factory()
->render_view($html)
->jquery('.title')->text($title);
}
))->process();
I want to compare two values (both are simple strings) on ajax success. Value1 is echo from php, value2 is javascript variable. But when I try something like:
$.ajax({
type: "POST",
url: proccessPage,
data: dataString,
dataType: "text",
success:function(result){
alert (result);
}
});
I will get message "[object Object]". When i try change alert (result); for
var response = $(result);
document.getElementById("div1").innerHTML = result;
then div with id "div1" has proper value. I know I can make the div hidden and use value from it, but is there some way to work with result directly? Or somehow convert result to string? Code in php:
if (isset($_POST['submit']) && $_POST['submit']=="true")
echo "string";
Thanks.
In your script, change the datatype to html.
dataType: "text",
to
dataType: "html",
The dataType of text is perfectly ok. Make certain that your PHP script is setting the mime type for the return to text/plain.
PHP Code:
header('Content-type: text/plain');
jQuery will process the return according to what the server says it is. The dataType field is only a hint. http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
If all else fails use something like Firefox with Firebug. It will give you the ability to place a break pint within your success closure and then you may inspect the value of your result variable.
I am having success by creating a json response from the PHP function, and loading it with whatever I need. Comparing known values from the Json Object handles your [object Object] return issue by giving you known object properties- declared with JSON:
$response = json_encode( array( 'success' => true , 'value1' => $my_result,);
header( "Content-Type: application/json" );
echo $response;
exit;
I use the success bool to ensure that $my_result is a successful response, because AJAX may execute properly, but this allows me to specifically check valid value1
Now, back in your $.ajax:
...
success: function(result){
if(result['success']) {
document.getElementById("removeme").innerHTML = (result['value1'] == value2)? value1 : "Uh-oh. Something went wrong!";
}
}
...
Or you can put whatever is appropriate in your success function body, whatever you need to compare or do. I just gave 1 example to show a complete implementation.
The first A in AJAX means asynchronous, this means that your request will be executed as normal but the callback only gets executed when the requests gets a response. the script doesn't pause waiting for the response.
with that said, if you want to use information from an AJAX request you must use it in its callback, or it will not be available.
something like this:
$.ajax({
type: "POST",
url: proccessPage,
data: dataString,
dataType: "text",
success:function(result){
document.getElementById("removeme").innerHTML = result;
}
});