Han Han - 6 months ago 25
Ajax Question

How do I loop through an array within the data: of an AJAX call

I have an array of courses. I'm using Rapid API for the back-end. I want to loop through the array and equate if "course": [one of those elements in the array].

sendEmail.js

var courses = ["course1", "course2", "course3", "course4"];
var courseLoop;
var dayLoop;
jQuery.ajax({
url: "http://something-something.rapidapi.io/get-day",
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: {
"course":for(i=0;i<4;i++){
courseLoop = courses[i];
if("course" == courseLoop){
alert("found");
break;
}
},
"day": "1",
},
})
.done(function(data, textStatus, jqXHR) {
alert("HTTP Request Succeeded: " + jqXHR.status);
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("HTTP Request Failed");
})
.always(function() {
/* ... */
});


I know I'm way off, but this is where I've got till.

Answer

To evaluate if specific value present in your array or not you could use anonymous IIFE(Wiki). It will be something like this:

var courses = ["course1", "course2", "course3", "course4"];
var courseLoop;
var dayLoop;
jQuery.ajax({
    url: "/echo/json/",
    type: "POST",
    contentType: "application/x-www-form-urlencoded",
    data: {
      "course": (function(courses, courseLoop) {
        //in jquery you can use inArray
        for (var i = 0; i < 4; i++) {
          if ("course" === courses[i]) {
            courseLoop = courses[i];
            //alert("found");//Removing Blocking Call
            if (window.console && console.log) console.log('found');
            break;
          }
        }
        return courseLoop;
      }(courses, courseLoop)), //Douglas Crockford's style
      "day": "1"
    }
  })
  .done(function(data, textStatus, jqXHR) {
    //alert("HTTP Request Succeeded: " + jqXHR.status);
    if (window.console && console.log) console.log(data, textStatus, jqXHR, jqXHR.status);
  })
  .fail(function(jqXHR, textStatus, errorThrown) {
    //alert("HTTP Request Failed");
    if (window.console && console.log) console.log(jqXHR, textStatus, errorThrown);
  })
  .always(function() {

  });