0

I want to send an array as data, but I get bad request error!

How can I fix it?
Does it need any code else to add?

window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
dataString = [ 'Location Zero', 'Location One', 'Location Two' ];

var jsonString = JSON.stringify(dataString);
$.ajax({
  type: "POST",
  url: "test",
  data: {
    data: jsonString
  },
  cache: false,
  success: function() {
    alert("OK");
  },
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64

3 Answers3

1

My first instinct tells me your URL in the AJAX method is malformed.. is "test" a directory with an index.php file?

var jsonString = JSON.stringify(dataString);

$.ajax({
  type: "POST",
  url: "test", // Should this be test.php or /test or ../test or somethign?
  data: {
    data: jsonString
  },
  cache: false,
  success: function() {
    alert("OK");
  },
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});
silversunhunter
  • 1,219
  • 2
  • 12
  • 32
1

if @silversunhunter 's answer didn't workout try to stringify the array this way. Sent as it is. Code below

dataString = [ 'Location Zero', 'Location One', 'Location Two' ];
$.ajax({
  type: "POST",
  url: "test", // Should this be test.php or /test or ../test or somethign?
  data: JSON.stringify({ 'data': dataString }),
  cache: false,
  success: function() {
    alert("OK");
  },
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

Also make sure that your webmethod is expecting a parameter of type string[] and is named as 'data'

Beingnin
  • 2,288
  • 1
  • 21
  • 37
0

should add these lines:

        dataString = [ 'Location Zero', 'Location One', 'Location Two' ];
         var ourObj = {};
         ourObj.data = dataString;

and ajax data change to this:

       data: {"points" : JSON.stringify(ourObj)},

this link was helpful! http://www.coderslexicon.com/easy-way-to-post-multiple-javascript-values-to-php-using-jquery-ajax/