0

Below is the code I am working on, my goal is to convert string to an actual object and just simply display the data from ajax call. But it seems that the string value cant work this way.

var string = "first: 'George', last: 'Smith'";

$.ajax({
   type: 'POST',
   url: 'ajax.php',
   data: {string}
}).done(data){
   alert(data);
}
4
  • 2
    How you get this string? Commented Dec 27, 2013 at 6:56
  • the json string format is invalid.... can you share how it is created Commented Dec 27, 2013 at 7:00
  • How it is created what? This is my entire code, I am just trying to convert the string to an object Commented Dec 27, 2013 at 7:02
  • @user3135626 i mean how you get this string? it always have this format? Commented Dec 27, 2013 at 7:19

3 Answers 3

1

Try this :

data: Function('return {' + string + '};')()
Sign up to request clarification or add additional context in comments.

5 Comments

Yep, this answer my problem. Thanks!
@user3135626 so also see about JSON.parse, like JSON.parse('{'+string+'}')
@user3135626 I agree with Grundy, but I've chosen the Function() way since the input is not a valid json string.
@wared yep, string with unknown format and code with function also will be work not for all path
@Grundy Well, it's hard to predict from the informations provided currently, I totally agree with you on that point :) Then, we could also discuss about the lack of security due to dynamic code evaluation.
0

Can you try this:

var Params= {first: 'George', last: 'Smith'};

$.ajax({
    type: "Post",
                dataType: 'json',
                url: 'ajax.php',
                data: JSON.stringify(Params),
                contentType: 'application/json',}).done(data){
   alert(data);
}

1 Comment

@user3135626..can you update your question clearly//
0

What you are looking for is:

  1. Do an AJAX call and receive data.
  2. The received data will be a string, but with a special format, what many use is Json.
  3. You'll create your object "manually".
  4. Then, you'll populate your object's fields with the Json values.

There are plenty of examples on the web.

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.