简体   繁体   中英

What am I doing wrong with this AJAX request?

I'm new to AJAX, so sorry if this is simple, but I've looked all other the place and can't see what I'm doing wrong.

When I swap the $_POST['name'] to an actual value, for example - $name = 'apple'; - everything works fine. However when I try to get the value from the AJAX post request in the php file like below, it doesn't work. Help! Thanks in advance.

PHP

$name = $_POST['name'];

$sql = "SELECT * FROM sales WHERE email = 'test' AND item = '$name' ";
$result = mysqli_query($conn, $sql);

    if ($result){

                    $row = mysqli_fetch_array($result);


                    echo json_encode($row);


                } else {
                        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
                }

Jquery

$(document).ready(function(){
    $('.option').on('click', function(){
    var name = $(this).val();
        $.post('ajax.php', {name: name}, function(data) {

            var obj = jQuery.parseJSON(data);
            var desc = obj[7]
            $('#name').val(desc);
        });
    });
    });

HTML

Item: <input type = "text" id = "name" size = "6">
    Description: <input type = "text" id = "name" size = "6">
    Qty: <input type = "text" id = "name" size = "6">
    Price: <input type = "text" id = "name" size = "6">
    Discount: <input type = "text" id = "name" size = "6">
    Account: <input type = "text" id = "name" size = "6">
    Tax Rate: <input type = "text" id = "name" size = "6">
    Amount: <input type = "text" id = "name" size = "6">
    <div class = "option">Apple</div>

Apple is not the value of your div with class option, it is the inner html.

Your code is checking the value of the element clicked when an object with class option is clicked. To see correct behavior with current code, change

var name = $(this).val();

to

var name = $(this).html();

I doubt this is how you will want your final solution to look, but always be careful about what exactly the methods you are using return.

edit: id's should be unique, I would recommend strongly against using the same id for your input objects.

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