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.
Related
I have an ajax function that retrieve two values for a given post: one for the number of likes, another one for the div that contains all the people that liked that post.
Everything seems to work fine, the json retrieved is correct, but the printing result is incorrect. Every time I try to get the number of likes (data.numDiLikes) I always get undefined even though the json is saying {"numDiLikes":"1","personeACuiPiace":"div info and stuff"}, how do I fix this?
AJAX with JSON
$.ajax({
dataType: "json",
type: 'POST',
cache: false,
url: "lib/ottieniCose.php",
data: { like: "", id: valCOR, comOrisp: comOrisp },
dataType: "html",
success: function(data, textStatus){
trova.find('.numDiLikes').first().replaceWith('<p class="numDiLikes">' + data.numDiLikes + ' mi piace</p>' + data.personeACuiPiace);
}
});
PHP
if ($_POST['comOrisp'] == 'commento') {
$commento->set_likes($_POST['id'], true);
// number of people that liked the post
$return_data['numDiLikes'] = $commento->get_likes($_POST['id'], true);
// div with all the people who liked the post
$return_data['personeACuiPiace'] = $commento->posso_fare_qualcosa($_SESSION['auth'], 'cancRisp', $_POST['id']);
echo json_encode($return_data);exit;
}
Use dataType: "json" to tell $.ajax that it returns JSON, and that it should parse it. dataType: "html" means that it returns HTML text, and data will be a string, not an object.
I want to get twitter counts of my website and article pages. After getting them I want to store them in database. I tried getting counts and posting them on my query.php using ajax but its showing me Cross Origin Block Error. Is there any way to do this? or am I missing something?
$.ajax({
url: "https://cdn.api.twitter.com/1/urls/count.json?url=<?php the_permalink(); ?>",
crossDomain: true,
crossOrigin: true,
success: function(data) {
var count = JSON.parse(data);
$("#dd").html(count);
$.ajax
({
type: "POST",
url: "post.php",
data: { stats: count, paralink:'<?php echo $rows['link_id'];?>', social:'2' },
success: function(data) {
},
dataType: 'json'
});
}
});
It would probably be more efficient / faster if you just made one ajax call to your server and a request to twitter directly from your php script.
And it would solve your problem as well:
// you should validate the input, but for simplicity:
$link = $_POST['paralink'];
// ^^^^^^^^ I am not sure if this is the page you want, you need to check that.
// get twitter json
$json = file_get_contents('https://cdn.api.twitter.com/1/urls/count.json?url=' . $link);
Now you just need the inner ajax call.
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;
}
});
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);
}
});