简体   繁体   中英

How can I pass a value through AJAX to alter SQL search query and return the result to HTML?

I'm attempting to create a web page that will take in a users preference (via checkboxes) for the category of quote they'd like. Upon submission, I use ajax to access a PHP file which, in turn accesses a SQL database and spits back a quote from the category.

My goal is to allow the user to select one or more categories and have their selection return a random row from the database that falls into their categories. I've gotten to the point where a random row is returned from the database but am unsure of how to pass a value to the SQL query in order to change the query based on their preferences.

Here's the AJAX:

$.ajax({                                      
   url: 'php/function.php', data: "", dataType: 'json', 
   success: function(data)
   {
       var quote = data[0];
       $('#content').html(quote); 
   } 

Here's the PHP:

$result = mysql_query('SELECT * FROM motivators WHERE Category LIKE "%success%" ORDER BY RAND() LIMIT 1');   
$array = mysql_fetch_row($result); 
echo json_encode($array);

How could I pass in a value and/or values to replace %success% ?

You can pass variables like so:

$.ajax({
    type: 'POST',
    url: 'php/function.php',
    data: { 
        'foo': 'bar', 
    },
    success: function(data){
       var quote = data[0];
       $('#content').html(quote); 
    }
});

Then in your PHP Script you can access $_POST['foo'] which should be populated with bar .

That's what the data: portion of the .ajax() call is:

data: 'formfield=somevalue'

then in PHP:

$formfield = $_GET['somevalue'];

Note that you do NOT use this value directly in an SQL query, which would leave you open to SQL injection attacks. I strongly suggest you stop using the deprecated mysql_*() function library and switch over to the modern mysqli or PDO libraries. Once using those, a simple prepared statement with proper placeholders with your life a lot easier.

To get the data from the ajax call, pass it in the data parameter of the call like so:

var param_value;
var param2_value;

$.ajax({                                      
   url: 'php/function.php', data: {param: param_value, param2: param2_value}, dataType: 'json', type: "POST",
   success: function(data)
   {
       var quote = data[0];
       $('#content').html(quote); 
   } 

Note the type: POST above, this means the passed data values will be stored in the $_POST array's keys: $_POST['param'], $_POST['param2']

Then just take the query in double quotes ("" instead of '') and insert the desired php variable into it.

$result = mysql_query("SELECT * FROM motivators WHERE Category LIKE '%$success%' ORDER BY RAND() LIMIT 1");

Be sure to escape anything you insert into the query to avoid SQL-inject vulnerabilities.

You can send a value as url parameter like http://mysite.com/search.php?q=some parameter .
Here is an example:

//AJAX functionality for search
function search(str){
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            resp = xmlhttp.responseText;
            document.getElementById("resultBox").innerHTML=resp;
        }
    }
    //Set URL parameters here
    xmlhttp.open("GET","search.php?q="+str,true);
    xmlhttp.send();
}

On server side:

//Search query
$search_q = $_GET["q"];
//Searching
$result = mysqli_query($con, "SELECT * FROM persons WHERE FirstName LIKE '%$search_q%'");
while($row = mysqli_fetch_array($result))
{
    echo '  <p>' . $row[FirstName] . '</p>';
    echo '  <p>' . $row[LastName] . '</p>';
}

This is very simple but what you want. (Security is not mentioned. Be careful!)
Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM