nzrnfourtwenty nzrnfourtwenty - 2 months ago 6
jQuery Question

How to pass multiple #div id in the ajax for advanced search feature

index.php

$('#search1, #search2').change(function() {
var value = $(this).val();
$.ajax({
type:"post",
url:"php/search.php",
data:'task1='+value,
success: function(response){
$('#result').html(response);
}
});
});

<select id="search1" name="task1">....</select>
<select id="search2" name="task2">...</select>

<div id="result"></div>


search.php

if (isset($_POST['task1']) ? $_POST['task1'] : false) {
$option = isset($_POST['task1']) ? $_POST['task1'] : false;
$sql = "SELECT * FROM <tablename> WHERE <columnName>='$option'";
if (isset($_POST['task2']) ? $_POST['task2'] : false) {
$pilihan = isset($_POST['task2']) ? $_POST['task2'] : false;
$sql = "SELECT * FROM <tablename> WHERE <columnName>='$option' and <columnName>='$pilihan'";
}
}


My question is how can i pass multiple #div into one ajax. In other word, how to make sure that #search2 and #task2 can pass and query their process same as #search1 and #task1.

Answer

You can get the name of select tag while change the options and make new variable, then pass that too data.

index.php

$('#search1, #search2').change(function() {
     var value = $(this).val();
     var str = $(this).attr('name')+'='+value; //added
     $.ajax({
       type:"post",
       url:"php/search.php",
       data: str,//added
       success: function(response){
        $('#result').html(response);
       }
      });
    });

    <select id="search1" name="task1">....</select>
    <select id="search2" name="task2">...</select>

    <div id="result"></div>

search.php

if (isset($_POST['task1'])) {
   $option = isset($_POST['task1']) ? $_POST['task1'] : false;
   $sql = "SELECT * FROM <tablename> WHERE <columnName>='$option'";
}
if (isset($_POST['task2']) {
    $pilihan = isset($_POST['task2']) ? $_POST['task2'] : false;
    $sql = "SELECT * FROM <tablename> WHERE <columnName>='$option' and <columnName>='$pilihan'";
   }

I hope this will help to achieve your goal

Comments