PDA

View Full Version : jQuery ajax pass two values



keyboard
02-29-2012, 09:54 AM
Hey everyone,

This code works fine.



<script type="text/javascript">
jQuery(function($){
var field1 = $('#fldrChatWindowInput');
$('#send').click(function(){
if(!field1.html()){
alert("Please enter a value");
field1.focus();
return;
}
jQuery.ajax({
url: 'process.php',
type: 'post',
data: 'field1value=' + field1.html(),
success: function(results){
alert(results);
}
});
});
});
</script>


I am wondering, is there a way to pass two or more variables to the php page, and return two or more variables? If so could someone please post code showing how and the php code for the variables.
Keyboard1333

jscheuer1
02-29-2012, 04:31 PM
The method of retrieving values on the PHP page is the standard method for any POST data. Getting the function to send more than one item of data is easy and can be done at least two basic ways.

The best way in my opinion is to name each field with the name you want it to have at post, collect all the fields you want, and then serialize them. But this will only work with selects, textareas, and certain inputs (text, file, password, and hidden fields). They don't have to be in a form, though if they are you can just serialize the entire form. That saves a lot of coding. If you're sending data from some other kinds of HTML element(s), these cannot be serialized without a custom function for that. They could be added to the serialization of the mentioned elements' data though.

The other way is to concatenate a URL encoded data string -that is name=value pairs separated with the & symbol. This will work for any type of string data from any source. It's more verbose but, as I say more flexible.

Since it's unclear what elements you are using let's stick with concatenating the name=value pairs:


<script type="text/javascript">
jQuery(function($){
var field1 = $('#fldrChatWindowInput'), field2 = $('#idOfSomeOtherElementWith_innerHTML');
$('#send').click(function(){
if(!field1.html()){
alert("Please enter a value");
field1.focus();
return;
}
jQuery.ajax({
url: 'process.php',
type: 'post',
data: 'field1value=' + field1.html() + '&field2value=' + field2.html(),
success: function(results){
alert(results);
}
});
});
});
</script>

You already know how to retrieve and process the field1value on the PHP page. Doing so with the field2value would be the same.

keyboard
02-29-2012, 09:15 PM
Hmmm, that answers that part of the question but what if I want to return two different values back to the html page from the php page? Any help?

jscheuer1
02-29-2012, 10:27 PM
As long as they're both echoed on the PHP page, they'll both be returned in the alert.