I’m having a problem with connection AJAX with PHP. The main goal is to send an request to PHP where we can execute method to delete an image. Every thing sounds nice and simple but the whole connection is not working properly – basicly it’s not working at all.
The is the simpliest example about what I would like to achive.
jQuery code:
$("span.deleteTmp").live("click", function() {
obj_a = $(this);
if (confirm("Want to delete the file?")) {
$.ajax({
url: "index.php?mode=functions&method=deleteFile",
data: {
pict_name: obj_a.attr("id")
},
dataType: "json",
success: function(data) {
alert(data.msg);
if (data.success == true) {
obj_a.parents("li").remove();
}
}
});
}
});
PHP example code:
/* invoking methods */
if(isset($_GET['method'])) {
$method = $_GET['method'];
call_user_func($method);
}
/* methods */
function deleteFile() {
$result = array('success'=>true, 'msg' => "OK");
echo json_encode($result);
}
Moreover when I type in browser index.php?mode=functions&method=deleteFile I get correct response such as: {"success":true,"msg":"OK"}
What am I doing wrong in this case?
Since you are using JQuery I am going to write this in JQuery.
First off
liveis either deprecated or being deprecated.Another tip is don’t use GET to modify and delete stuff from your server since some one could easily abuse that. Also you are allowing the GET to dictate, without any real validation, what function should be run like:
index.php?mode=functions&method=deleteFile. Someone could easily change that to define a function you DON’T want running directly from the website.So the first thing I would do is change live to on() like:
Something like that should give you the right result. Open up your console with f12 and see what it gives you back and of course make sure the actual event is running when you click the element, I know it sounds stupid but I have made the mistake of sitting there for hours thinking why AJAX wouldn’t run only to find it wasn’t even firing the
clickevent.Edit
however I do see your actual problem. You are defining two GETs for JQuery, first in the url:
Then in the data:
If I remember correctly JQuery in this context will actually fire a AJAX call to:
So try my code above.