santa
santa

Reputation: 12512

How to test AJAX post with jQuery

I have the following function that opens jQuery UI's dialog warning about the delete of an entry. Everything works fine, except the POST with AJAX. I get response on "success" but I don't believe I am hitting the .php page that is supposed to execute the query. Am I missing anything here?

var $dialog = $("#dialog").dialog({ autoOpen: false, resizable: false, modal: true });

    $(".delProj").click(function(){ 
        var delURL = $(this).attr("href").split("#");
        var projID = delURL[1];
        $dialog.dialog("open");
        $("#dialog").dialog({
            buttons: {
                "Yes, delete this test": function() {
                    $.ajax({
                        type: "POST",
                        url: "http://www.example.com/inc/db_actions.php",
                        data: "op=DeleteProject&delete="+projID,
                        success: function(){
                          //  alert( "Test Project deleted successfully." );
                          $("#"+projID).remove();
                        }
                    });
                    $(this).dialog("close");
                },
                "No, keep it.": function() {
                    $(this).dialog("close");
                }
            }
        });
    });

Upvotes: 0

Views: 30974

Answers (2)

Marc Bouvier
Marc Bouvier

Reputation: 702

Make your php page called echo something

PHP

echo 'hello world';

Javascript

Add the return value of the callback (here data), and try to show it with js.

[..]

success: function(data){
    alert(data);
}

[...]

Upvotes: 6

Demian Brecht
Demian Brecht

Reputation: 21378

I'll usually send some form of a response through JSON-formatted data so that my AJAX queries know whether or not they've accomplished what they've set out to do. Something like:

Script:

$.ajax({
    type: "POST",
    url: "http://www.mydomain.com/inc/db_actions.php",
    data: "op=DeleteProject&delete="+projID,
    success: function(data){
        if(data.success == true)
        {
            $("#"+projID).remove();
        }
});

PHP:

// do something
echo json_encode(array('success'=>true));

Edit:

It's also usually a good thing to trap your ajax errors:

$.ajax({
    type: "POST",
    url: "http://www.mydomain.com/inc/db_actions.php",
    data: "op=DeleteProject&delete="+projID,
    success: function(data){
        if(data.success == true)
        {
            $("#"+projID).remove();
        }
    },
    error: function(){
        alert('something bad happened');
    }
});

Upvotes: 4

Related Questions