简体   繁体   中英

JQuery Ajax $_GET request received an incorrect response from PHP

Something wrong going on:

I am sending data to php through an ajax request. There it checked that received an empty or non-empty GET and for each of these options it return different answers. The problem is that on the php page the answer is correct, but it becomes incorrect when it returns to the page from which it was sent.

When GET is empty, php returns 'empty' (as expected), but ajax prints 'not empty' (expected 'empty')

I absolutely do not understand why this is happening. I tried returning various with both exit and return

AJAX:

 $(".rate_form.submit").click(function() { var rate_form = $(this).parents().find('.rate_form'); var rate = rate_form.serialize(); $.ajax({ type: "GET", url: "rate.php", data: { "rate": rate }, cache: false, success: function(response) { console.log(response); } }); return false; });

RATE.PHP:

header("Content-type: text/html; charset=utf-8");

if(empty($_GET)){
    exit('empty');
}elseif (!empty($_GET)){
    exit('not empty');
}


UPD: I tried @Barmar suggestion

Unfortunately, this is not related to the problem. I completely got rid of "cache", but the situation has not changed. I even tried checking only one $ _GET argument for empty() (trying isset() also).

The result is the same as before: in rate.php the answer is correct (depending on whether the request is empty or with arguments), and on the page with the form there is always only one answer: "empty". Moreover, even stranger, if you return the $ _GET array, then it returns correctly (when $ _GET is not empty, it returns "empty" and not empty array)

if (!empty($_GET['rating'])){
    print_r($_GET);
    exit('not empty');
} else {
    print_r($_GET);
    exit("empty");
}

Console answer on page returns "empty" and not empty array

Array
(
    [rate] => rating=1
)
empty

$_GET will never be empty when you use cache: false . This works by adding an extra _=(timestamp) parameter to the query string, so that the URL will always be different, in order to prevent it from being cached (this is called a "cachebuster"). As a result, $_GET['_'] will always be set.

You should remove that element before checking.

unset($_GET['_']); // remove cachebuster
if (empty($_GET)) {
    echo "empty";
} else {
    echo "not empty";
}

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