简体   繁体   中英

Sending and processing an associative array from jquery to php

I have a filter for some devices in a webpage, made of checkbox. Whenever one of the checkbox is clicked, i call a function which add to an object the value of the checkboxes checked. I want to send this object to a php file, via ajax, and use it to perform some MySQL query, then return the results from the php and display them on the page. The problem is, i'm missing something, since i kept getting a parseerror in my js.

Here's my code: device-filter.js

$(document).ready(function(){
$(".ez-checkbox").click(function() {
    console.log("ok");
    var re = {Brand: "", Cost: "", OS: ""};
    $("#Brand :checkbox:checked").each(function(){
        re.Brand += $(this).val()+" & ";
    });
    $("#Cost :checkbox:checked").each(function(){
        re.Cost += $(this).val()+" & ";
    });
    $("#OS :checkbox:checked").each(function(){
        re.OS += $(this).val()+" & ";
    });
    if(re.lenght==0){

    }
    else{
        $.ajax({
            method: "POST",
            dataType: "json", //type of data
            crossDomain: true,
            data: re,
            url:"./php/filtered-device-query.php",
            success: function(response) {
            //display the filtered devices  
            },
            error: function(request,error)
            {
                console.log(request+":"+error);
            }
        });
    }
});
});

filtere-device-query.php

<?php
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_db");

if (mysqli_connect_errno()) { //verify connection
echo "Error to connect to DBMS: ".mysqli_connect_error(); //notify error
exit(); //do nothing else 
}
else {
//echo "Successful connection"; // connection ok
    $devices =json_decode($_POST['re']);
    echo var_dump($devices)."<br>"; 
    $myArray = array();//create an array
    $brand = rtrim($devices["Brand"], " &");
    $cost = rtrim($devices["Cost"], " &");
    $os = rtrim($devices["OS"], " &");

    $query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND 'Cost' = '$cost' AND 'OS' = '$os' ";
    $result = $mysqli->query($query);
    //if there are data available
    if($result->num_rows >0)
    {
        while($row = $result->fetch_array(MYSQL_ASSOC)) {
            $myArray[] = $row;
        }
        echo json_encode($myArray);
    }

    //free result
    $result->close();

    //close connection
    $mysqli->close();
}
?>

Thanks in advance for any help!

You have some typos, first in the jQuery:

if(re.lenght==0){

should be:

if(re.length==0){// note the correct spelling of length

Then in your PHP you're using quotes on column names in the query. Those should be removed or better yet, back ticked:

$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND `Cost` = '$cost' AND `OS` = '$os' ";

More importantly...

An object, as you've described it, has no length. It will come back as undefined . In order to find the length you have to count the keys:

if(Object.keys(re).length == 0){...

The object re , as you've declared it, already has 3 keys, a length of 3. Checking for length of 0 is a waste of time.


Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi . Even escaping the string is not safe!

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