jeudi 16 août 2018

Passing parameters from checkboxes with jQuery and ajax() method

I'm trying to get some entries in a JSON Response from https://jsonplaceholder.typicode.com/posts by selecting checkboxes with jQuery and the ajax() method.

I can see with Chrome DevTools that 2 requests are made, one of type "Document" and one of type "XHR". For The first the response is correct but for the second there is no response. This is how they look like:

Request URL: https://jsonplaceholder.typicode.com/posts?userId%5B%5D=3&userId%5B%5D=4 with Query String Parameters: userId[]: 3 userId[]: 4

Request URL: https://jsonplaceholder.typicode.com/posts?userId=3&userId=4 with Query String Parameters: userId: 3 userId: 4

and this how my HTML and JavaScript and jQuery look like:

HTML

<form id="myForm" action="https://jsonplaceholder.typicode.com/posts">
 <input type="checkbox" id="Checkbox1" name = "userId" value = "1" />
<input type="checkbox" id="Checkbox2" name = "userId" value = "2" />
<input type="checkbox" id="Checkbox3" name = "userId" value = "3" />
<input type="checkbox" id="Checkbox4" name = "userId" value = "4" />
<input type="button" id="demo" value = "Demo" />
<input type="submit" id="submit">
</form> 

JavaScript+ jQuery

var url = "https://jsonplaceholder.typicode.com/posts";

$("#submit").click(function() {
    var allVals = new Array();  
    $("input:checkbox[name=userId]:checked").each(function () {
    allVals.push($(this).val());
    console.log(allVals);

      $.ajax({
              url: url,
              data: {
              userId: allVals
          },
              type: "GET",
              dataType: "json",
        })
        .done(function (json) {
          console.log(json);

        }); 
});
    });

In the jQuery Documentation is stated that the "data" option must be an object or a query string. However I have an array. So how can I deal with this situation? I've already tried some things but I can't get it working. How come the first request is correct? (which I actually don't need it) How can I initiate only the XHR Request?




Aucun commentaire:

Enregistrer un commentaire