-1

A function triggers a database call which returns some Json. This CID is then used to stamp the newly added DOM element.

I need to retrieve / return the value of "cid" which exists within ajax success block, it will be used to update attribute.

Error cid is not defined

//Save New Task
$("body").on('click','.icon-facetime-video',function(event){
  var new_entry = $(this).prev().val();
  var thebid = $(this).parents('tbody').prev().find('th').attr('id').split('_')[1];
  $(this).parent().addClass('tk').html('<i class="icon-eye-open"></i> '+new_entry);
  //CALL FUNCTION
  var cid = update_entry('new_tk',new_entry,thebid); //value of cid from update_entry
  $(this).parent().attr('id','cid_'+cid);
});

function update_entry(typeofupdate,new_entry,thebid){

  switch(typeofupdate){
    case 'new_tk': var action = 'new_tk';
    break;
  }

  $.ajax({
        type:'post',
        url: 'posts_in.php',
        dataType: "json",
        data: {cid : thebid, action: action, content: new_entry},
        success: function(data){
            var action = data[0],cid= data[1];
            console.dir(data);
        }
    });

  return cid;  
}
6
  • 2
    Ajax call is not synchronous so you sould wait until it returns that value. Yo might also want to write an error:function() there inside the call just in case. Commented May 21, 2012 at 18:42
  • 2
    possible duplicate of How can I return a value from an AJAX request? Commented May 21, 2012 at 18:43
  • 1
    possible duplicate of Return result from nested asynchronous ajax call Commented May 21, 2012 at 18:43
  • 1
    See also this question on meta Commented May 21, 2012 at 18:44
  • BTW, you might want to switch out parents for closest. Commented May 21, 2012 at 18:49

1 Answer 1

2

Since AJAX is done asynchronously (hence the a in AJAX), your function returns before the AJAX call completes. You should pass a callback function into update_entry, and run it in your AJAX success handler:

var self = this;

update_entry('new_tk', new_entry, thebid, function(cid) {
    $(self).parent().attr('id', 'cid_' + cid);
});

function update_entry(typeofupdate, new_entry, thebid, callback) {

  switch(typeofupdate){
    case 'new_tk': var action = 'new_tk';
    break;
  }

  $.ajax({
        type:'post',
        url: 'posts_in.php',
        dataType: "json",
        data: {cid : thebid, action: action, content: new_entry},
        success: function(data){
            var action = data[0], cid= data[1];
            callback( cid );
            console.dir(data);
        }
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much Joseph, this helps tremendously. :)

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.