Reputation: 724
I am trying to send a name:value pair to a php script using the $.post object in jQuery where both name and value are variables. I have sent the variables to the console in FF, so I know they are being set correctly, but when I view the headers being sent, only the value variable is being evaluated correctly, the name is being sent as a literal string of the variable name. Here is the function in its entirely:
$(document).ready(function() {
$('#formS form fieldset > input').blur(function() {
if($(this).val()=='' && $(this).prev().is('img')) {
$(this).prev().remove();
return;
}
if((($(this).is('#formS form fieldset > input[id*=mail]')) ||
($(this).is('#formS form fieldset > input[id*=sername]'))) &&
($(this).val()!="")) {
var email_field = $(this);
if(!$(this).prev().is('img')){
$('<img src="" alt="" style="width: 16px; height: 16px;" />').insertBefore(this);
}
var type = ($(this).is('input[id*=sername]'))?'username':'email';
var value = $(this).val();
$.post('checkemail.php5', {type:value}, function(data) {
if(data == "free") {
email_field.prev().attr('src','/images/greentick.png').attr('alt','available');
} else if(data == "taken") {
email_field.prev().attr('src','/images/redcross.png').attr('alt','taken');
} else {
console.log('hmmm'+data);
}
});
}
});
});
So, the headers being sent are the literal string type, and whatever value evaluates to. Anybody have any ideas why?
Upvotes: 1
Views: 5452
Reputation: 11237
exactly what I was looking for Dark Falcon, thanks!
was difficult to find this solution, BTW. I assume most people are just serializing the form data and sending that as the post param, but in some cases it's nice to use variable-name => variable-value pairing, which was driving me nuts as nothing I tried when using name as a variable was working
Upvotes: 0
Reputation: 44181
Because the syntax {} takes a set of name:value where the names become the property on the object. This is a literal and cannot be a variable, as you see. Use this:
var params = {};
params[type] = value;
and pass params instead of {type:value}
Upvotes: 10
Reputation: 2708
I'm not sure of what your problem is, it's not so clear to me. I don't much knowledge in php also but you might want to try it like this:
var type = ($(this).is('input[id*=sername]'))?'username':'email'; var value = $(this).val(); var data= type+"="+value;
$.post('checkemail.php5', data, function(data) {.......
Very best,
Upvotes: 0