July 20, 2011

How to get data from jQuery.post()?

Question by Alwayz Change

My problem is that i wanna use post data outside it’s function, example:

$(function() {
  var s = 'something ';
  $.post('ajax.php', {option: 'test'}, function(data) {
    s += data; // data: 'hello world';
  alert(s); // output: 'something ';

my expected result is ‘something hello world’.
how can i deal with this?

Answer by Nishant

Use $.ajax with async:false, I assume the data is coming as content-type:json/application e.g.

var s = 'something ';
      url: "ajax.php",
      type: "POST",
      data: ({option: 'test'}),
      dataType: "json",
      success: function(msg){
         s += msg.data;//msg={data: "hello world"}

Answer by Starx

You code should be working. Unless the ajax.php is not echoing “Hello World” at the end. Please make sure of it and try to post the results. Errors or output, whatever you can feed us.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!