简体   繁体   中英

passing .php array into a javascript code jquery/ajax

At the moment i have this piece of javascript code:

//Display custom confirm box and delete multiple message

$(document).ready(function () {
    $(".delete_button-multiple").click(function () {
        //Get message id as variable
        var id = $(this).attr("id");
        var dataString = 'id=' + id;
        var parent = $(this).parent();
        //Display custom Confirm box  
        jConfirm('Are you sure you want to delete this message?', '', function (r) {
            if (r == true) { //initiate delete message if agreed

                $.ajax({
                    type: "POST",
                    url: "delete-mail_ajax.php",
                    data: dataString,
                    cache: false,

                    success: function () {
                        window.location = "mail_inbox.php";
                    }
                });

                return false;
            }
        });

    });
});


delete-mail_ajax.php:

if($_POST['id'])
{
$id=$_POST['id'];
$id = mysql_escape_String($id);
$sql = "delete FROM mail WHERE mail_id='$id'";
mysql_query( $sql);
} 

This is a working code for deleting only one mail item. I wrote the following code to delete multiple messages from checkboxes:

        //Multiple delete mail
        if(!empty($_POST['message'])){ 
        $list_mail = $_POST['message'];
        foreach ($list_mail as $messageID){    
        $sql = "delete FROM mail WHERE mail_id='$messageID'";
        mysql_query($sql);
        //deletion complete, refresh the page
        header("Location: mail_inbox.php");
        }
        }//end delete multiple 

The difficulty i'm having is changing the working code above to incorporate the multiple selection, and deletion, of selected mails.

Any help on this issue would be appreciated

-Callum

Assuming you're using checkboxes, your code would look something like:

var messages = new Array();
$("input[name='mail_items[]']:checked").each(function() {
   messages.push($(this).val());
});

$.ajax({
   type: "POST",
   url: "delete-mail_ajax.php",
   data: { message: messages }  //jQuery should translate this to an array that PHP should understand
   cache: false,
   ...
});

You may need to json_decode the input to the $_POST['message'] variable, but I'd do a var_dump() on the stuff first just to make sure what PHP is doing in the background. Can't check at the moment, sorry.

I guess you have trouble submitting the form via Ajax? There is a neat plugin that does that for you: http://jquery.malsup.com/form/

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