Asked  7 Months ago    Answers:  5   Viewed   37 times

I have a form with a lot of form fields (12 x n rows). The first field in each row (which represents a product) is a checkbox that resembles this:

<input type="checkbox" class="ids" name="ids[]" value="1">

The value of each checkbox is unique.

What I am trying to do is send checked values to a PHP script for processing via Ajax. What I am am having issues with is getting the IDs to the server properly. I have tried using several things including:

$('.ids:checked').serialize();

and

var ids = [];
$('.ids:checked').each(function(i, e) {
    ids.push($(this).val());
});

$.ajax({
    url: "stub",
    type: "post",
    dataType: "json",
    data: {
        'ids[]': 'ids[]='+ids.join('&ids[]=')
    },
    success: function(data) {
        // stub
    }
});

But these both result in getting this on the server:

ids[]=104&ids;[]=105

I could serialize the whole form and send it over but that could result in a lot of data being sent that is going to be unused.

How do I send only the values of delete[] to the server? Ideally in a way that PHP recognizes it as an array?

(I have worked around it by sending the IDs over as a comma delimited string but would like to know how to accomplish this since I spent enough time trying to figure it out).

 Answers

70

This worked fine for me

<input type="checkbox" class="ids" name="ids[]" value="2">
<input type="checkbox" class="ids" name="ids[]" value="3">
<input type="checkbox" class="ids" name="ids[]" value="4">
<input type="checkbox" class="ids" name="ids[]" value="5">
<input type="checkbox" class="ids" name="ids[]" value="6">

<div id="response"></div>
<button id="submit">Submit</button>

<script>

$('#submit').click(function() {

$.ajax({
    url: "stub.php",
    type: "post",
    data: $('.ids:checked').serialize(),
    success: function(data) {
    $('#response').html(data);
    }
});


});
</script>

Then on stub.php

var_dump($_POST);
Wednesday, March 31, 2021
 
radmen
answered 7 Months ago
77

I see you are using jquery, if you want data to come back to you as a json object you need to do 1 of 2 things.

  1. add header("Content-Type: application/json") to your php file, this will tell jquery to convert it to a json object instead of as text

  2. Add a forth parameter to your $.post,

$.post('/ajax-database.php', function (data) {
    console.log($.parseJSON(data));
    $.each(data, function (key, value) {
        console.log(value);
    });
}, "json");

that will tell jquery to call your error handler if its NOT json, like if your php code fails and outputs html instead. You really should use $.ajax, i have no idea why anyone uses $.post, you can't do ANY meaningful error handling.

Wednesday, March 31, 2021
 
Kemrop
answered 7 Months ago
20

Recommended (reduce with default value)

Array.prototype.reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.

console.log(
  [1, 2, 3, 4].reduce((a, b) => a + b, 0)
)
console.log(
  [].reduce((a, b) => a + b, 0)
)

Without default value

You get a TypeError

console.log(
  [].reduce((a, b) => a + b)
)

Prior to ES6's arrow functions

console.log(
  [1,2,3].reduce(function(acc, val) { return acc + val; }, 0)
)

console.log(
  [].reduce(function(acc, val) { return acc + val; }, 0)
)

Non-number inputs

If non-numbers are possible inputs, you may want to handle that?

console.log(
  ["hi", 1, 2, "frog"].reduce((a, b) => a + b)
)

let numOr0 = n => isNaN(n) ? 0 : n

console.log(
  ["hi", 1, 2, "frog"].reduce((a, b) => 
    numOr0(a) + numOr0(b))
)

Non-recommended dangerous eval use

We can use eval to execute a string representation of JavaScript code. Using the Array.prototype.join function to convert the array to a string, we change [1,2,3] into "1+2+3", which evaluates to 6.

console.log(
  eval([1,2,3].join('+'))
)

//This way is dangerous if the array is built
// from user input as it may be exploited eg: 

eval([1,"2;alert('Malicious code!')"].join('+'))

Of course displaying an alert isn't the worst thing that could happen. The only reason I have included this is as an answer Ortund's question as I do not think it was clarified.

Tuesday, June 1, 2021
 
exxed
answered 5 Months ago
27

You should return the data as JSON from the server.

PHP

$arr = array();
$arr[0] = "Mark Reed";
$arr[1] = "34";
$arr[2] = "Australia";

echo json_encode($arr);
exit();

JS

$.ajax({
    type: "POST",
    url: "/returndetails.php",
    data: 'id=' + userid,
    dataType: "json", // Set the data type so jQuery can parse it for you
    success: function (data) {
        document.getElementById("name").innerHTML = data[0];
        document.getElementById("age").innerHTML = data[1];
        document.getElementById("location").innerHTML = data[2];
    }
});
Wednesday, July 28, 2021
 
codingb
answered 3 Months ago
28

Try converting the inner arrays to a string, then filter the dupes and parse the string again.

let x = [[1, 2], [3, 4], [1, 2]];

var unique = x.map(ar=>JSON.stringify(ar))
  .filter((itm, idx, arr) => arr.indexOf(itm) === idx)
  .map(str=>JSON.parse(str));

console.log(unique);
Tuesday, August 17, 2021
 
Nate
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share