Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajax error results in success function call

I was working toward a solution for this recent post: Repeating a function using array of values and in doing so, I stitched together the following piece of code.

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>

	var name_list = ['mike','steve','sean','roger'];
	
	var successAction = function(name) {
		console.log(name);
	}
	
	name_list.forEach(function(name) {
		jQuery.ajax({
			type: "GET",
			url: "https://www.google.com/", 
			dataType: 'html',
			success: successAction(name)
		});
	});
	
</script>

I run this and not surprisingly the following error message is returned:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).


My question is this - If the ajax request results in four failures such as it appears, then why is the success function called four times and correspondingly logging each name in the array?

like image 589
ThisClark Avatar asked Oct 31 '22 13:10

ThisClark


1 Answers

success: successAction(name) 

could be replaced with

xxx: successAction(name)

and it would still print out the 4 times. The correct syntax should be

success: function(name) { successAction(name); }
like image 157
Dukefirehawk Avatar answered Nov 10 '22 00:11

Dukefirehawk