简体   繁体   中英

Php why doesn't send response to Jquery ajax?

I would like to get data from a mysql database without page refresh. I use jquery ajax in client side and php in server side. The request went but the response is empty(if i go to xhr in Firefox than the request is good,no problem, but when i click answer/response it is empty and the size of the request also 0).There aren't any errors, but nothing happened. Here is my script.js javascript file:

 $(document).ready(function(){
    $.post("ajax.php",
    {
        task: "get_iron"
    },
    function(data)
    {
        $("#iron").html(data);
    }
    );
    console.log("js doesn't have any problem");//it works fine
});

And this is my ajax.php file:

<?php
$method = $_SERVER['REQUEST_METHOD'];
if(strtolower($method)=='post')
{
    if(isset($_POST['task']) && $_POST['task'] == "get_iron")
    {
        $con = mysql_connect('myhost','myusername','mypassword');
        if (!$con) {
          die('Could not connect: ' . mysql_error($con));
        }
        $sql="SELECT iron FROM minerals WHERE username = 'martintamiya'";
        $result = mysql_query($sql,$con);
        $row = mysql_fetch_object($result);
        echo json_encode($row);
    }
}

?>

Should i use $.ajax instead of $.post? Please help me and note that i'm a beginner. Thank you for the responses.

if(isset($_POST['task']) && $_POST['task' == "get_iron"])

That is always going to return false because you don't have a post field called 'task' == "get_iron" and since there isnt an else statemnt it's doesn't do anything.

if(isset($_POST['task']) && $_POST['task'] == "get_iron")

That's what you want.

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