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?

4
  • 1
    Possible duplicate of jquery AJAX and json format Commented Jan 13, 2016 at 7: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) Commented Jan 13, 2016 at 7:57
  • Why it's not a valid JSON? Commented Jan 13, 2016 at 8:07
  • Why it's not a valid JSON? Just read the specs Commented Jan 13, 2016 at 8:13

2 Answers 2

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;
   }
});
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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");
     }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.