Reputation: 3
I have two inputs that are tied up with an On Change ajax call.
<input type="email" id="lookupemail" style="width: 225px;" placeholder="[email protected]">
<select id="type" style="width: 150px;">
<option value="member"> Member </option>
<option value="lead"> Lead </option>
</select>
The ajax call works fine, but it seems to not be passing my lookup type.. Did I format my variables incorrectly?
<script>
$("#lookupemail").keyup(function () {
var lookuptype = $('#type').val();
var lookupinput = $('#lookupemail').val();
$.ajax({
type: "POST",
url: "includes/dbsearch.php",
data: {lookuptype: lookupinput},
success: function(server_response)
{
if(server_response != 0) {
//
} else {
//
}
}
});
});
</script>
It passes:
lookuptype:"conner@asdsafsdf"
Instead of.. member:"conner@asdsafsdf"
Upvotes: 0
Views: 52
Reputation: 24638
Instead of:
data: {lookuptype: lookupinput},
Use something like:
data: {lookuptype: lookuptype, lookupemail: lookupinput},
When using an object for the data
value of the ajax call you must supply key/value
pairs. In your case, you're supplying a key = lookuptype
and a value = whatever-the-user-types-in-email-field
. You are not sending a key/value
pair for the email
.
On the server side you'd retrieve the data using the keys:
$lookuptype = $_POST['lookuptype'];
$lookupemail = $_POST['lookupemail'];
NOTE
If you intention is to make the lookuptype
selected the key for your single key/value
pair, then you must declare an object an manipulate it:
var lookuptype = $('#type').val();
var lookupinput = $('#lookupemail').val();
var fData = {}; //<<<<<======
fData[lookuptype] = lookupinput; //<<<<<<======
$.ajax({
type: "POST",
url: "includes/dbsearch.php",
data: fData, //<<<<<<<=========
Upvotes: 1
Reputation: 1512
If you want to pass an object as the data parameter with a variable as the property name, you would have to do this:
var ajaxData = {};
ajaxData[lookuptype] = lookupinput;
So, overall, you should do this:
$("#lookupemail").keyup(function () {
var lookuptype = $('#type').val();
var lookupinput = $('#lookupemail').val();
// Create the data object
var ajaxData = {};
ajaxData[lookuptype] = lookupinput;
$.ajax({
type: "POST",
url: "includes/dbsearch.php",
data: ajaxData,
success: function (server_response) {
if (server_response != 0) {
//
} else {
//
}
}
});
});
Now that you know how to do this, let me tell you that it's a bad idea since the server won't know what properties to look for in the data that is passed to it. It's better to do what PeterKA suggests.
Upvotes: 0