Reputation: 433
I've an HTML form where there are some checkboxes. Below this form, there is an empty div with id="area1" and an empty div with id="area2". They are to be filled with the data returned by a PHP function (actually, by now, only #area1 is filled).
To do so, I first retrieve with jQuery the values of the checkboxes (from 1 to n):
var value1 = $('#mybox1').prop('checked');
...
var valuen = $('#myboxn').prop('checked');
Then I pass the "valueX" variables to my PHP script using an AJAX call :
$.ajax({
type: "GET",
url: "process_function.php",
data: { checkbox1 : value1 ... checkboxn : valuen},
success: function(data){
//add to div "area1" the retrieved data
$('#area1').html(data);
})
The AJAX call is triggered when a button is pressed.
Then process_function.php analyzes the data, and calls if necessary other functions located in a function.php file. Those functions always echo something.
Everything works fine, but the problem is that the results are concatenated to the same div : #area1 !
So I wonder if I can chose to what DIV add a given data. That is to say, within the same AJAX call, is there an "elegant" way to add some data to #area1 if value1 is checked, and to add other data to #area2 if value2 is checked, and to both areas if both values are checked, with only one PHP function ?
So far, the only idea I have is to create a jQuery function that tests if value1 is checked, then makes a call to process_function1.php, and so on for the other values. But it multiplicates the PHP functions.
Thanks
Upvotes: 0
Views: 2132
Reputation: 970
<?PHP
// example data. The key values will become part of the jscript object //
$data = ["area1" => "blahblahblah", "area2" => "<i>Something</i>"];
// need this for it to be recognized by jQuery as JSON
header('Content-Type: application/json');
echo json_encode($data);
Jquery Code
$.ajax({...}).done(function(data){
$.each(data, function(key, value) {
$("#"+key).html(value);
});
});
You may also use this code this is more dynamic.
Upvotes: 1
Reputation: 2429
You could have your PHP script return a JSON object, which the jQuery $.ajax
method will automatically translate into a Javascript object.
PHP
<?PHP
// example data. The key values will become part of the jscript object //
$data = ["div1" => "blahblahblah", "div2" => "<i>Something</i>"];
// need this for it to be recognized by jQuery as JSON
header('Content-Type: application/json');
echo json_encode($data);
Javascript
$.ajax({...}).done(function(data){
$("#area1").html(data.div1);
$("#area2").html(data.div2);
});
Upvotes: 2