Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 10 of 10
  1. #1
    New to the CF scene
    Join Date
    Nov 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    $.ajax returns JSON but not storing in variable

    I'm looking to pull the responseText from this AJAX request, nothing complicated, right? Well as soon as I set my dataType to "json" or "jsonp" then my script fails to grab any responseText, when I know for a fact (using Firebug) that I have JSON as a response. It fails to even get to the success function. If I take out the dataType, then the success function fires but I get nothing as responseText. It's been two days and I can't seem to figure out what the heck is going on. My code below does everything I want it to, except store it to the variable (and call the success.) If I call the variable after doing this AJAX call, it simply tells me that the variable is undefined.


    <script language="javascript" type="text/javascript">
    var tempJSON = $.ajax({
    type: "GET",
    dataType: "jsonp",
    processData: false,
    url: "http://www.kylematheny.com/siteground.php?jsoncallback=?",
    success: function() {
    alert('Success!');
    }
    });
    </script>

    *I've tried to add $.ajax({...}).responseText and still nothing. Using Firebug, the response is {"GEM":"25"}, which is exactly what I want, but I can't figure out how to store the json and recall it later in my script.

    Please help!

  • #2
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    Keep in mind I'm a hack at this stuff, but I've been doing a lot of ajax via jquery and I've also found it difficult to debug, because if the server script dies, or returns non-json code, things just stop without any clue what's going on.

    So, being a hack, I've hacked out a debugging process where in my server script I echo return values to log files and doing this has given me enough information to determine what the problem is. Typically the problem is my return value isn't valid json format (because PHP echos a warning, or some other unexpected output happens) which halts the whole process.

  • #3
    New to the CF scene
    Join Date
    Nov 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts
    @Fumigator:

    If you go to the page that I'm requesting, then it outputs valid JSON code, and when running my script, it's responding with valid JSON code, so the only real problem is how do I get the response as a variable?

    I know what you're saying about PHP echoing warnings, and I'm not getting any errors or warnings from my PHP, it's all valid. I just don't get it...

  • #4
    New to the CF scene
    Join Date
    Nov 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I've updated my PHP file to include "application/json" headers, and I'm getting a JSON response back, but it just refuses to trigger a Success or Complete action- not to mention it won't store the object as a variable.

    PLEASE HELP! I've got less than 2 weeks to make this work or my project is going to be in some serious trouble. You can copy and paste this code directly and see what I'm talking about (using Firebug you can see the JSON response.)

    Code:
    var dummyVar = $.ajax({
          type: "GET",
          dataType: "jsonp",
          url: "http://www.kylematheny.com/siteground.php?callback=?",
          success: function() {
              alert('Success!');
          },
          complete: function() {
              alert('Completed.');
          }
      });

  • #5
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    I saw the apparently valid JSON return value back on Nov 5th, but then I started reading up on that jsonp business and fell into a vortex of confusion. And as I lay there in the fetal position, unable to move or think, I forgot to reply back.

    So anyway... I don't know what "jsonp" is doing for you; have you tried "json" only as the return type? Have you tried using the $.get() function? That works pretty well and is a bit simpler...

  • #6
    New to the CF scene
    Join Date
    Jun 2010
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I know this post is really old but I'm curious if anyone has figured this out? I'm trying to do pretty much the same thing. Here is my code and ill walk through what it is supposed to do.

    Code:
    function getMore(from){
    	var initData = "&start-index=";
    	initData += from;
    	$.ajax({
    		type:"POST",
    		url: '', //removed the URL
    		data: initData,
    		dataType: 'json',
    		success: function(result) {
    			return result;
    		},
    		error: function(errorThrown) {
    		
    		}
    	});
    	
    	return result;
    }
    Its a google base query; I have another function that makes the initial server call and gets the first 250 items. I then have a running counter and as long as the results = 250 it calls the server again, but starting at "start-index=" of the current amount of items pulled off. This part all works correctly and with firebug I can also see that the server response is proper JSON.

    The trouble I'm having is trying to return the JSON from this function to the function that called it. I do not want to call the original function again because it will clear the arrays of data already pulled from the server. Each time it returns to the parent function it's null.

    Does anyone know how i can go about returning the data using "return"?

  • #7
    Senior Coder Spudhead's Avatar
    Join Date
    Jun 2002
    Location
    London, UK
    Posts
    1,856
    Thanks
    8
    Thanked 110 Times in 109 Posts
    Hi. Two things:

    1. Don't paste questions onto the end of existing threads. It makes stuff hard to find. And nobody will see your question.

    2. You need to rethink your code structure. Your function is firing an an asynchronous request: by the time the request returns, your function has completed.

    It's a little hard to say what to do without seeing your full code, but I think you've got two options. One is - whatever these arrays of data are, think about expanding them globally to store the results of successive ajax calls. But that might not be too economical, and in any case you're still going to have to fire something when the ajax completes, to let your application know the data has been updated: in effect, you've not solved the problem, you've just pushed it downstream a bit. The other approach is to do a synchronous http request, but that'll only work if you're calling a url on the same domain as the originating page.

    Sorry, that was a bit rambly. Post your code and we might be able to work out a solution. But start another thread for it.

  • #8
    New to the CF scene
    Join Date
    Sep 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I just found the solution to it.
    May be, the original person who asked the question doesn't need it anymore, but future google searchers will have the solution when they need it.

    Just put an extra option of "async: false" in the options hash. What's actually happening is that, since Ajax is "Asynchronous" Java Script and XML, it doesn't wait for the actual json value to get stored, but rather it returns immediately ( possibly with a null value ). So by the time the "success" routine gets called your mother function has moved on to the next line of execution ( and "success" is possibly running in a different thread ). To unset this asynchronous behaviour and make it wait just specify async:false

    Code:
    		   var myVariable = $.ajax({
    		   	   
    			   url: '/path/to/url',
    			   dataType: 'json',
    			   beforeSend: function(xhrObj){
    	                xhrObj.setRequestHeader("Accept","application/json");
    	           },
    			   async: false,
    			   success: function(data){
                                   // do whatever
    			   }
    		   });
    Hope this helps the next person.
    Cheers !

  • #9
    New to the CF scene
    Join Date
    Oct 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Thanks Shafayet

    @Shafayet_Ahmad,

    Thanks for posting your solution.

    You saved me a ton of debugging time with the 'async: false' suggestion.
    I couldn't figure out why my hidden field value wasnt updating from the ajax call.

    Thanks again.

    Jeff O

  • #10
    New to the CF scene
    Join Date
    Feb 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Answering this because it took me a few days to figure it out; hopefully this will help some other diligent soul who is struggling to process remote JSON data via JSONP JQUERY .ajax processing.

    The key issue is to match the format of the function on the server side, in the .json file, with the processing function in the client-side webpage. Your data format on the server side must match the function on the client side:

    For example, server file "ticker.json" should look like this:

    test(
    {
    "msgOne": "Remote One",
    "msgTwo": "Remote Two",
    "msgThree": "Remote Three"
    }
    )



    Your client-side web-page functions should look like this:

    $.ajax({
    cache: 'false',
    type: 'GET',
    url: 'http://www.you.com/yours/ticker.json',
    dataType: 'jsonp'

    }); // Close Ajax Function

    function test(data)
    {
    var tickerOne = document.getElementById("test");
    tickerOne.appendChild(document.createTextNode(data.msgTwo));
    }

    With the client side function above, the output on the webpage in the "test" div is "Remote Two"

    Pretty cool, huh?


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •