How to read JQuery mapping array in PHP?

Viewed 34

I am trying to send data from JQuery to PHP and then post it to database. My JQuery code is:

   var mapArray = $.map(customFieldIds, function(value) {
        return {
        name: value,
        value: customFieldValues[value]
        };
   })

It looks like this:

mapArray = [
 {name: "1", value: "1"},
 {name: "2", value: "50"},
 {name: "3", value: "12"}
]

How can I read that array in PHP?

This is how I send data from Ajax side:

var mapArray = $.map(customFieldIds, function(value) {
    return {
        name: value,
        value: customFieldValues[value]
    };
})

// Submit
$.ajax({
    url: 'updatePositions.php',
    type: 'POST',
    data: jQuery.param({
        "customFields": mapArray, //customFieldValues,
    }),
    dataType: 'json',
    // contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    success: function(response) {
        alert("Success")
    },
    error: function() {
        alert("error");
    }
});

and this is how I try to read data in PHP:

<?php include('db.php'); ?>
<?php
$customFields = $_POST['customFields'];

foreach ($customFields as $key => $value) {
    $n = $key;
    $v = $value;
    $sqlCustom = "UPDATE custom_field_values SET value='$v' WHERE id='$n'";
}
$pdo->prepare($sqlCustom)->execute();
?>
1 Answers

Simply change your &.ajax request as following:

$.ajax({
    ....
    type: 'POST', 
    data:{
         customFields: mapArray
    }
    dataType: 'json', // means that your OUTPUT (not INPUT) will be in JSON format, it's up to you
    ....
});

and then in PHP change your foreach loop:

foreach ($customFields as $pair) {
    $n = $pair['name'];
    $v = $pair['value'];
    $sqlCustom = "UPDATE custom_field_values SET value='$v' WHERE id='$n'";
    $pdo->prepare($sqlCustom)->execute();
}
Related