简体   繁体   中英

How can I pass a variable to alert() with $.ajax?

I want to let the user confirm to deletion of a record by letting them click on the button and the button sends the value Yes to a $_POST request so I can delete the record with PHP, instead it's showing me the javascript file that contains the function.

What am I doing wrong, I've been tinkering and searching for 3 hours straight, while in the back of my mind I know it's a easy fix.

Any help is greatly appreciated.

If you think there is a smarter way to be doing this, please let me know.

$(function () {

    $("#DeleteConfirm").dialog({

        buttons: {
                 "Confirm": function() {
                    var DeleteConfirmation = "Yes";                 
                    $.ajax({
                        type: "POST",
                        url: "index.php",
                        data: DeleteConfirmation,
                        success: function(DeleteConfirmation){
                            alert(DeleteConfirmation);
                        },
                        dataType: "text"
                    });

                 },
                 "Cancel": function() {
                     $(this).dialog("close");
                 }
             }
    });

});

You need to assign the YES value to a property name:

data: { "confirmed": DeleteConfirmation},

Then in your PHP you can ready this using $_POST["confirmed"] .

This does seem a little redundant however, as the user has already clicked the button to confirm the deletion, so there seems little value in sending the value in the POST request. Sending the id of the item to delete would make more sense.

Your ajax is misformed, try:

                $.ajax({
                    type: "POST",
                    url: "index.php",
                    data: {answer: DeleteConfirmation }, //what you send to the php
                    success: function(data){ //answer from your php
                        alert(data);
                    },
                    dataType: "text"
                });

             },

Javascript:

if( confirm('Are you sure?')){
    /*proceed?*/
}

That is standard javascript. It wraps your AJAX call within the braces and if the user clicks 'yes' - the ajax call will execute. If he click 'no', then nothing happens. The confirm() prompt pops up an alert on screen with buttons. The resulted is captured by the if . You can also capture the result of that: var res=confirm('are you sure?'); .

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