We help IT Professionals succeed at work.

response from ajax call within a function

impressionexpress
impressionexpress used Ask the Experts™
on
I have an ajax call within a function and when I return the result of the ajax call from the function it comes back undefined, what am I doing wrong here ?
	function get_applications(){
		var application_list = "";
		
		$.ajax({
			url: '../ajax/some_file.php',
			contentType: false,
			processData: false,
			type: 'POST',
			success: function(data){
				application_list = data;
			//	console.log(data);
			},
			error: function() { 
			//	console.log('NOT updated'); 
			}			
		});
		return application_list;
	}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Scott FellDeveloper & EE Moderator
Fellow 2018
Most Valuable Expert 2013

Commented:
Open your browser, hit the f12 key to get to dev tools and view the network tab. Now run the the page and look for some_file.php.  Click on that and you can view what is being posted to the page and what is being returned.

If you are not sure how to do that, then create a test environment for us and post a link to your test page using fake data.

Author

Commented:
If I reactivate line 11 in my code above, I get the result Im looking for in the console. so the link to the php script is working. I need to get the value that im getting on line 11 (the data variable) and return it from the get_applications() function if I return at line 11, I get undefined.

Author

Commented:
Maybe you can suggest a better way to do this

Step 1: Get The current contents of a div (html included)
Step 2: Do the ajax call and get the results from the php script
Step 3: append the results of step 2 to the results of step 1

This is why I created the ajax call within a function, also because eventually I will have to pass some arguments

I also want to count the instances of a class from step 1 and compare with the results of step 2
	function get_applications(){
		return $.ajax({
			url: '../ajax/some_script.php',
			contentType: false,
			processData: false,
			type: 'POST',
			success: function(data){
				application_list = data;
			//	console.log(data);
			},
			error: function() { 
			//	console.log('NOT updated'); 
			}			
		});
	}

	setInterval(function() {
        get_applications().done(function(value) {
            console.log(value); //waits until ajax is completed
        });
	}, 1000);

Open in new window

Scott FellDeveloper & EE Moderator
Fellow 2018
Most Valuable Expert 2013

Commented:
ok, it was a scope issue. In your original code, you just needed to return the variable in the success function.

Glad you have it figured out.