0

this is probably something very simple to fix. Im posting to a php page that returns the ID of the new element created in the db- (posting via $.ajax)- i have logged the returned value.

The following code is the code i use to post

$.ajax({
               type: "POST",
               url: "<?=base_url()?>events/add_tag_js/",
               data: url,
               success: function(html){

                   $("#tag_list").append('<li><span id="" class="tag">'+formvalue+'<span class="remove_tag"><a class="remove_tag_link" href="#">x</a></span></span></li>');
                   $("#add_tag").val('');
                   console.log(html);
               },
               failure: function(){
                    $('.error').show();
                    $("#add_tag").val('');
               }

            });

The return value from the console.log is

{"error":false,"msg":"Tag added","id":44}

but when i do alert(html.id) i get undefined? do i need to parse the json returned to do this? or is my json incorrect?

2 Answers 2

2

Maybe you didn't set the proper content type on your server side script, so jQuery doesn't know that this is JSON. So either set the content type to application/json on your server script or you could also indicate that you expect JSON in the request using the dataType parameter:

...
type: "POST",
url: "<?=base_url()?>events/add_tag_js/",
data: url,    
dataType: 'json', // indicate that you expect JSON from the server
...

Although it is recommended to have your server side script set the proper content type.

Sign up to request clarification or add additional context in comments.

Comments

0

Try to tell it to handle it as Json, in your case the html is a String, so you would have to to an var myObj = eval(html); which is bad

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

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.