简体   繁体   中英

error: AJAX call within AJAX response

I am working with a file to interact with an API. First the API sends some HTML and Javascript to create a search form, then the API can process the query of that search form.

I am having some problems with my second request, which is called within the success function of the first request (this seems to be the problem!). Here's the code I'm working with.

$.ajax({
  type: "POST",
  url: "https://vq3rsgkd94.execute-api.us-east-1.amazonaws.com/deploy",
  crossDomain: true,
  data: JSON.stringify({
    "stage": "load",
    "fields": ["first_name", "last_name", "graduation_year"]
  }),

  success: function(response) {
    response = JSON.parse(response);
    $(response.html).prependTo("#content");
    $(response.scripts).appendTo("body");
  },

  complete: function() {
    //get field inputs
    var fieldInput = {
      "first_name_query": "",
      "last_name_query": "",
      "graduation_year_query": ""
    };

    $('form').find('input[type=search]').each(function(index, value) {
      var variableName = value.name;
      var fieldId = "#" + value.name;

      $(fieldId).keyup(function() {
          variableName = $(this).val();
          fieldInput[value.name + "_query"] = variableName
          console.log(value.name + ":" + fieldInput[value.name + "_query"]);
        })
        .keyup();
    });

    $('#search_form').submit(function(event) {
      event.preventDefault();
      $.ajax({
        type: "POST",
        url: "https://vq3rsgkd94.execute-api.us-east-1.amazonaws.com/deploy",
        data: JSON.stringify({
          "stage": "search",
          "fields": ["first_name", "last_name", "graduation_year"],
          "query": {
            "first_name": fieldInput["first_name_query"]
          }
        }),

        success: function(response) {
          response = JSON.parse(response);
          console.log(response);
        }
      });

    })

  }
});

When trying to parse the response, I get unexpected token: o. If I run this code outside of the first ajax request like this:

$.ajax({
  type: "POST",
  url: "https://vq3rsgkd94.execute-api.us-east-1.amazonaws.com/deploy",
  data: JSON.stringify({
    "stage": "search",
    "fields": ["first_name", "last_name", "graduation_year"],
    "query": {
      "first_name": "Bob"
    }
  }),


  success: function(response) {
    response = JSON.parse(response);
    console.log(response);
  }
});  

I don't have any problem and the code executes normally. So the problem seems to be running one Ajax call inside another's success response, but I don't know why? I can probably do things another way instead, but wanted to see if anyone had some insight into why this doesn't work.

The error you are getting suggests that you are trying to parse an object with JSON.parse since

var x = {}
console.log(x.toString()) //> [object Object]
JSON.parse(x)
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
//    at JSON.parse (<anonymous>)
//    at <anonymous>:3:6

Are you sure that response is a string in the second case

Instead of explicitly converting the JSON allow jquery to parse it for you with dataType: 'json'

$.ajax({
  type: "POST",
  url: "https://vq3rsgkd94.execute-api.us-east-1.amazonaws.com/deploy",
  data: JSON.stringify({
    "stage":"search",
    "fields":["first_name","last_name","graduation_year"],
    "query":{"first_name": fieldInput["first_name_query"] }
  }),
  dataType: 'json'
)}

So the problem ended up being pretty strange. I'm developing an API for Nationbuilder platform (maybe my first mistake). For unknown reasons, Nationbuilder was appending a authenticity token to any request made, which my LAMBDA based API couldn't parse. Just in case anyone else is in the same very tiny boat as I was, I ended up using GET requests instead of POST requests and Nationbuilder stopped appending the authenticity token.

Also, if anyone is using Lambda, I ended up switching to Digital Ocean hosted Express JS and am much happier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM