简体   繁体   中英

AJAX Get isn't working

I'm attempting to pull data from a mysql server with AJAX. This is the AJAX call:

function getAllTasks()
        {
            alert("Getting all tasks");

            $.ajax({
              type: "get",
              url: "ajax.php",
              dataType: "json",
              data: data,
              async: false,
              success: function(data){
                   alert('hi!');
                   //perform operation
                },
                error: function() {
                  alert('Error occurs!');
                }
            });
        }

and this is the PHP it's supposed to run:

header('Content-Type: application/json');



$conn = new mysqli('localhost', 'projectAdmin', 'admin', 'to_do_list')
    or die('Error connection to database');

    getAllTasks($conn);




function getAllTasks($conn)
{
$query = "SELECT * FROM tasks WHERE ID=1";

$result = mysqli_query($conn, $query);

while($row = $result->fetch_assoc())
{
    $tasks[] = $row;
}

echo json_encode($tasks);

}

It's not working. When I run the PHP alone, it works fine, and returns a JSON string in the browser (chrome). When I run the AJAX, nothing happens. I get the "getting all tasks" alert, and then it just doesn't work. The AJAX is called from the $(document).ready() function.

I don't know where I'm going wrong, I've looked at a bunch of posts on here and my AJAX code looks next to identical. Is it an issue with json_encode? The AJAX? Help, please.

Here:

data: data,

It looks that the data variable is undefined. Also I would recommend you removing the async: false option in order to make an asynchronous request instead of blocking the UI.

Looking at the Console in your browser might also reveal some potential problems with your code.

var xhr = new XMLHttpRequest();
xhr.open("GET", "ajax.php");
xhr.addEventListener("readystatechange", function(ev) {
    var xhr = ev.target;
    if (xhr.readyState < 4) { /*not finished downloading yet.*/
        return;
    }
    /*the request is completed. do your stuff with xhr.responseText here.*/
    console.log(xhr);
});
xhr.send();

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