Post data-attribute with php - 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']

Related

working with ajax and php as front and backend

var insertValue= $.ajax({
url: "handle.php",
type: "POST",
data: text,
dataType: "text"
});
insertGroupData.done(function(msg){
alert(msg);
});
This is the first half, I'm stuck in the 1st line of my backend.php
I think it should be catch the POST value, but what should I catch?
<?php
if(isset($_POST["_____??_____"])){
echo "test";
}
Jquery: if your data should be like
data: {test:text},
Then in PHP you can use to get like below,
if(isset($_POST["test"])){
echo "test";
}
Explanation about data:
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting .
Ref: http://api.jquery.com/jQuery.ajax/
change your code to this
var insertValue= $.ajax({
url: "handle.php",
type: "POST",
data: {text:text},
dataType: "text"
});
in backend page you can check it like
echo $_REQUEST['text];
or
echo $_POST['text];
A lesson in jQuery
$(function () {
var
url = 'your/target/script.php',
data,
fn = function (text) {alert(text);},
// fn will expect text, so set return as text
dataType = 'text';
// this POST data will populate $_POST as $_POST[key] = 'value'
data = {
ajax : 1,
key : 'value',
key2 : 'another value'
};
// shorthand notation is convenient sometimes
$.post(url,data,fn,dataType);
});
Your php now has access to your key value pairs
<?php
// in my example the 3 are set
if (isset($_POST['ajax'])) {
$_POST['key'];
$_POST['key2'];
}
Happy coding

How to send two inputs with jQuery

ok, i have these two input fields where a user puts in two twitter names. When the submit button is pressed, both names should be send to a .php file with the POST method that checks if both usernames exsist on twitter.
Sending and receiving the answer for one value already works, but how can i also add the second? I already have this:
<script type="text/javascript">
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
**data: {'user1' : $('#user1').val() },** //how to append user2?
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
</script>
the fields in the form:
<td><input type="text" name="user1" id="user1"/></td>
<td><input type="text" name="user2" id="user2" /></td>
and this is how the values should be able to be cathed in the .php:
$user1 = $_POST['user1'];
$user2 = $_POST['user2'];
So the question really is: how can I append the second username to the above jQuery POST function?
p.s. I am starting with javascript and jQuery, how do you guys work with this as no error messages are shown ever.. is there an environment/programm where I get debugging help with javascript?
data: {
'user1' : $('#user1').val(),
'user2' : $('#user2').val()
},
It's a simple enough extension-- just follow the same pattern.
<script type="text/javascript">
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: {
'user1' : $('#user1').val(),
'user2' : $('#user2').val()
},
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
</script>
That said, jQuery does also have a .serialize() function that you could apply on the containing form, which automatically serializes the whole form. This could prove useful for you.
EDIT: It's worth mentioning that the jQuery selectors above look on the id for the name "user1" (etc.), whereas the PHP script expects the form elements' name to be "user1" (etc.). Here you have them as the same thing.
A more reliable jQuery selector that would allow you to always use the name in both jQuery and PHP is simply to use an attribute selector in jQuery:
$('input[name="user1"]').val()
This will catch any <input> element with the name attribute set to "user1".
You're probably looking for serialize. Your code would look something like this:
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: $("#your_form").serialize(),
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
If you're sure you don't want serialize you could try this:
data: {'user1' : $('#user1').val(), 'user2' : $('#user2').val() }
As for your PS, check out Firebug and Webkit developer tools.
You actually don't even need the serialize function. If you just select your form, all form elements will be passed. This way if you just add another form element, like another textbox, it will all be passed in your ajax call.
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: $("#your_form"),
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}

& 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