JSON can't read returned ajax value - php

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.

Related

How to get and store Twitter share counts in database?

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.

PHP doesn't receive $_POST

I have a problem with my PHP, I'm doing an ajax post with jquery.
The problem: my PHP doesnt receive any POST, with GET there are no problems.
I'm using the last jquery version.
Ajax doesnt throw any error, I tried with error:function(...) and console.log.
idCat is a number, for example: 3
$nuevaFila and other undeclared variables are previously declared, they aren't constructive.
PHP returns well the HTML because I try any html and I receive it ok
The ajax code is this one:
$.ajax({
cache:false,
type:'post',
url:'admin/categoria_ajax_ad',
data: {id: idCat},
success: function(htmlFila) {
var nFila=$cFilas.find(".fila").size()+1;
$nuevaFila.html(htmlFila);
$nuevaFila.appendTo($cFilas);
},
});
Try using dataType (xml, json, script, or html) setting parameter like this depending on your return data type -
$.ajax({
cache:false,
type:'post',
url:'admin/categoria_ajax_ad',
data: {id: idCat},
dataType : "string"
success: function(htmlFila) {
var nFila=$cFilas.find(".fila").size()+1;
$nuevaFila.html(htmlFila);
$nuevaFila.appendTo($cFilas);
},
});

& Value not appearing with AJAX call

I am working on submitting values into a database through AJAX. It currently uses JQuery Ajax object.My Ajax code basically looks like this:
enter code here
var genre = form.new_album_genre.value;
form.new_album_genre.value="";
$.ajax({
type: "POST",
data: "genre="+genre+"&app="+app,
url: 'apps/PVElectronicPressKitAdmin/ajax_add_album_genre.php',
success: function(data) {
$('#'+divID).html(data);
}
});
In short, it gets a value from a form and then submits the data through a post. Where it fails if the genre is something like R&B. The & symbol is not sumbitting and only the R is. So how do I submit values through AJAX including &, + and = ?
You need to encodeURIComponent to deal with characters which have special meaning in URIs.
(Or pass an object containing key/value pairs to jQuery instead of the query string String you have now)
I've never had a problem with special chars using
$.post('apps/PVElectronicPressKitAdmin/ajax_add_album_genre.php', {
'genre' : genre,
'app' : app
},
function(data) {
$('#'+divID).html(data);
});
Piggybacking off David Dorward's answer
$.ajax({
type: 'POST',
url: 'apps/PVElectronicPressKitAdmin/ajax_add_album_genre.php',
data: { genre : form.new_album_genre.value, app: form.app.value },
success: function (data, textStatus) {
$('#'+divID).html(data);
}
});
Use
$.ajax({
type: "POST",
data: "genre="+encodeURIComponent(genre)+"&app="+encodeURIComponent(app),
url: 'apps/PVElectronicPressKitAdmin/ajax_add_album_genre.php',
success: function(data) {
$('#'+divID).html(data);
Because of the & it is interpreted as a new parameter.
In your case data will look like genre=R&B&app=somethig -> this means 3 parameters: genre, B and app.

How to post array from javascript to php?

I want to post an array using Jquery Ajax to php. Is this possible ?
Thanks
EDIT:
I tried following :
type: "POST",
url: "path",
data: "styles=" + strstyles + "&templateId=" + custTempId, //strstyles is an associative array
dataType: "json",
success: function (data) { .....}
but, styles hold no data. I spent a lot of time, before adding data type to the declaration. What can be the reason for "styles" being posted as null ?
Second Edit
I want to post style sheet dom object and save the class names and properties to DB. With the above edit, adding datatype did not help. I think it is b'coz the string is not in json format as follows -
{"a":1,"b":2,"c":3,"d":4,"e":5}
As the my string has double quotes, it is not following the format, and I think that's the reason, I'm getting an empty array. How can I handle this ?
With jQuery it is very easy:
$.ajax({
type: "POST",
url: location.href,
data: data,//data is array
dataType: "json",
success : function () {
// Something after success
}
});
You can use in following way too
$.ajax({
type: "POST",
url: location.href,
data: ({'data[]' : array}),//array is array
dataType: "json",
success : function () {
// Something after success
}
});
if you don't want to use JSON, PHP can automatically create arrays from Html forms
so you could do something like this:
type: "POST",
url: "path",
data: "styles[key1]=" + strstyles.val1 + "&styles[key2]=" + strstyles.val2 + ... + "&templateId=" + custTempId
...
that is if you want to have an associative array in php, but if you want just an array you could do
data: "styles[]=" + strstyles.val1 + "&templateId=" + custTempId
In POST call you dont use & , So your code should be
something like
type: "POST",
url: "path",
data: {styles: strstyles , templateId: custTempId}, //strstyles is an associative array
dataType: "json",
success: function (data) { .....}
is that point clear?
So coming to my solution,
you should download JSON parser from http://www.mediafire.com/?x6k3su7bbdrcta8.
Create object strstylesOBJ, code: var strstylesOBJ = {};
insert your strstyles array into strstylesOBJ and stringify it then pass to it in your post call
strstylesOBJ.styles = strstyles;
strstyles = JSON.stringify(strstylesOBJ);
In PHP code you refecth your array using $strstyles = json_decode($_POST['styles']);
do var_dump($strstyles) and please tell what was the output.
regards
Ayaz Alavi

serialize function for string values to use in jQuery ajax datastring

how to sanitize user inputs that you gather by jquery .val() so you can write it in a dataString... in the example you see below when user writes
if some text that contains & the rest
of the comment doesn't seem to work
fine because it counts the rest as an
other variable to POST..
is there a sanitaziation or
serialization code? jQuery's
sanitize() function works on forms but
i want something that i can use
directly use on strings...
var id = $("some_id_value_holder_hidden_field").val();
var comment = $("#sometextarea").val();
var dataString = "id=" + id + "&comment=" + comment;
$.ajax({
type: "POST",
url: "write_comment.php",
data: dataString,
dataType: "json",
success: function(res) {
// Success
},
error: function(xhr, textStatus, errorThrown) {
// Error
}
});
Any suggestion will be much appreciated
Regards
Since you're using jquery, you can use the included Form plugin to serialize the array.
serialize() - Creates a url string from form fields (eg, someEle=someVal&anotherEle=anotherVal)
serializeArray() - Returns a key/value array of all the form elements (useful to know)
$.ajax({
url : 'write_comment.php',
type : 'post',
data : $('#form-element').serialize(),
success : function(data)
{
alert('yay!');
}
});
Edit: Edited to remove incorrect escape() part.
there is a built-in encodeUriComponent that does exactly what you're looking for. Besides that, you can provide an object in "data" field, in which case url encoding will be handled by jquery. In your example:
$.ajax({
type: "POST",
url: "write_comment.php",
data: { id: id, comment: comment},
etc...

Categories