0

I have a string:

'{format: "json", user: "user", password: "password"}'

and I want to send all this data using jQuery's AJAX. I've tried this way (requestData['data'] is the string) :

$.ajax({
     url: requestData['url'],
     type: requestData['type'],
     data: requestData['data'],
     error: function(xhr) {
         alert("failed");
     },
     dataType: 'json',
     success: function(data, textStatus, xhr) {
        alert("success");
     }
});

Do I have to encode the string somehow?

robertsan
  • 1,591
  • 3
  • 14
  • 26
  • 1
    Possible duplicate of [jquery AJAX and json format](http://stackoverflow.com/questions/17426199/jquery-ajax-and-json-format) – Pavel Pája Halbich Jan 13 '16 at 07:54
  • _Do I have to encode the string somehow?_ It depends on what are you going to do with this data on server. BTW: your string is **not valid** JSON, so you can't decode it on server by standard means (`json_decode`) – hindmost Jan 13 '16 at 07:57
  • Why it's not a valid JSON? – robertsan Jan 13 '16 at 08:07
  • _Why it's not a valid JSON?_ Just read [the specs](https://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example) – hindmost Jan 13 '16 at 08:13

2 Answers2

0

You can send the whole object, its not a problem:

var jsonObj = {format: "json", user: "user", password: "password"};

$.ajax({
     url: requestData['url'],
     type: jsonObj,
     data: requestData['data'],
     error: function(xhr) {
         alert("failed");
     },
     dataType: 'json',
     success: function(data, textStatus, xhr) {
        alert("success");
     }
});
0
var datum = {
   format: "json",
   user: "user",
   password: "password"
};

$.ajax({
   type: "POST",
   contentType: "application/json; charset=utf-8",
   url: url,          // your url
   dataType: "json",
   data: JSON.stringify(datum),
   success: function(response) {
      var result = response;
   }
});
ozil
  • 6,930
  • 9
  • 33
  • 56
  • Thank you. But imagine that I have a string, not a variable. The way you did it is great but it won't help me. I've tried to convert the string to object. Do you have any idea about how should I do it in the correct way? – robertsan Jan 13 '16 at 07:59
  • This may help [javascript string to object](http://stackoverflow.com/questions/13718326/javascript-string-to-object) – ozil Jan 13 '16 at 08:10