I've got some data that will be used as part of an image gallery but I don't want to refresh the page between loading the data (there are interface items that I wish to stay visible). However when I submit the data to the same page via ajax JS registers a successful execution of the code (the alert box shows up) but PHP fails to harvest the data.
My JQuery looks like this
$(".gallery_thumbnail").click(function(){
var id=$(this).attr("data-id");
$.ajax({
type: "GET",
url: "test.php",
data: {newid:id},
dataType: 'text',
success:function(result){
// Test what is returned from the server
alert(result);
}
});
});
And my PHP looks like this\
if(isset($_GET['newid'])){
echo "success";
}
else{
echo "fail";
}
I've seen similar questions and tried copy and pasting the answers but I can't seem to get this to work. I've also tried for the url parameter:
http://localhost/test.php and simply removing the url parameter altogther.
Check if the request is ajax, then do the ajax processing
// this code should go before any of the web page code
if (isset($_GET['ajax'])){
if(isset($_GET['newid'])){
echo "success";
}
else{
echo "fail";
}
exit;
}
set a param to see if it is an ajax request
$.ajax({
type: "GET",
url: "test.php",
data: {newid:id, ajax: 'true'},
dataType: 'text',
success:function(result){
// Test what is returned from the server
alert(result);
}
});
I think the problem is that you're a little mixed up about what you're trying to accomplish here or how you should do it.
Try
if(isset($_GET['newid'])){
// Do whatever you want when the script gets an AJAX request
// You want to exit early to avoid having the whole page show up in the alert()
exit;
}
// Your normal, non-AJAX PHP code goes here
Note that your page is coming back in its entirety in the alert() because you aren't exiting early, which you probably want to do for an AJAX response. The way you have it setup, the whole page is sent back as if you're requesting it from a browser viewport.