简体   繁体   中英

AJAX jquery json sending array to php

I'm trying to send a associative array via AJAX $.post to php. Here's my code:

var request = {
        action: "add",
        requestor: req_id,
        ...
    }

    var reqDetails = $("#request_details").val();

    switch(reqDetails){
        case 1: 
            request[note] = $("#note").val();
            break;

        ...

    }

    if(oldRequest()){
        request[previousID] = $("old_id").val();
    }

    $('#req_button').toggleClass('active');
    $.post("scripts/add_request.php", {
        request_arr: JSON.stringify(request)
        }, function(data){
            console.log(data);
            $('#req_button').toggleClass('active');
    }, 'json');

And i'm simply trying to read the received data in my php script:

echo json_decode($_POST["request_arr"]);

But it's not working. I'm a newbie to js, I can't figure out what I'm doing wrong.

Check below link for your reference

Sending an array to php from JavaScript/jQuery

Step 1

$.ajax({
    type: "POST",
    url: "parse_array.php",
    data:{ array : JSON.stringify(array) },
    dataType: "json",
    success: function(data) {
        alert(data.reply);
    }
});

Step 2

You php file looks like this:

<?php 



  $array = json_decode($_POST['array']);
    print_r($array); //for debugging purposes only

     $response = array();
     if(isset($array[$blah])) 
        $response['reply']="Success";
    else 
        $response['reply']="Failure";

   echo json_encode($response);

Step 3

The success function

success: function(data) {
        console.log(data.reply);
        alert(data.reply);
    }

You are already using " json " as dataType, so you shouldn't apply 'stringify' operation on your data.

Instead of request_arr: JSON.stringify(request) , can you try request_arr: request directly?

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