How to post array from javascript to php? - 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

Related

JSON can't read returned ajax value

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.

Post data-attribute with php

I'm having troubles with posting the value of a data attrubute e.g. data-fruit="orange" I basically want to do it with jQuery ajax and I imagine it would look something like this
var fruit = $(".fruit img").attr("data-skin");
$('.box').click(function() {
$.ajax({
url: 'fruits.php',
type: 'post',
data: fruit
});
});
Should the php $_POST look like this:
$friutType = $_POST['data-friut']
Cheers
You need to send key/value pairs to data, not just a value.
$.ajax({
url: 'fruits.php',
type: 'post',
data: {fruit: fruit}
});
Then in PHP:
$friutType = $_POST['fruit']

sending increment value from jquery to php file with for loop help

I have this for loop in jquery
$(document).ready(function() {
for(i=0; i<counter; i++)
{
dataCounter = i;
$.ajax({
url: 'file.php',
dataType: 'json',
data: dataCounter,
error: function(){
alert('Error loading XML document');
},
success: function(data){
$("#contents").html(data);
}
});
}
});
And then I want to bring in my dataCounter into the file.php as a variable and have it change each time so I can get different records in mysql in file.php, am I doing this right? How would the php portion look like? I know how pass variables to a php file with this method if I had a form, but I don't have a get or a post form to work with. Also, my variables are going to change.
Can someone help me? Thank you!
While I don't recommend running an ajax query inside of a loop, I am wiling to explain the data option for $.ajax(). Ideally, you pass an object as the data option, and it is translated by jQuery into a query string where each object property name is a key and its value is the value:
data: {
count: dataCounter
}
becomes
?count=1
in the query string of the ajax request if datacounter is equal to 1.
In PHP you would access it as $_GET['count'].
data needs to be a key-value pair, not just a value as you have it here. Try something like: (not tested)
$.ajax({
url: 'file.php',
dataType: 'json',
data: ({dataCounter : dataCounter}),
error: function(){
alert('Error loading XML document');
},
success: function(data){
$("#contents").html(data);
}
});

& 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.

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