javascript - I am trying to make an AJAX fetch request and I keep getting an error "Uncaught SyntaxError: Unexpected token ')'" - TagMerge
5I am trying to make an AJAX fetch request and I keep getting an error "Uncaught SyntaxError: Unexpected token ')'"I am trying to make an AJAX fetch request and I keep getting an error "Uncaught SyntaxError: Unexpected token ')'"

I am trying to make an AJAX fetch request and I keep getting an error "Uncaught SyntaxError: Unexpected token ')'"

Asked 1 years ago
3
5 answers

This parenthesis is misplaced:

  // console.log(data);
  }); <-- this one
};


  // console.log(data);
  }
}); <-- should be here

Source: link

2

You had two parenthesis misplaced, you can check with the code below:

document.addEventListener('DOMContentLoaded', () => {
  const title = document.createElement('h1');
  title.innerText = 'Online Chatroom';
  document.querySelector('body').appendChild(title);
  // make AJAX call here.... 
  fetch('https://curriculum-api.codesmith.io/messages')
    .then(data => data.json())
    .then(data => {
      const main = document.querySelector('main')
      for (let i = 0; i < data.length; i++) {   
        writeHTML(data[i], main)
      // console.log(data);
      }
    })
    })

Source: link

0

Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:
$.ajax({
     url: 'does-not-exist.php',
     success: function(returnData){
         var res = JSON.parse(returnData);
     },
     error: function(xhr, status, error){
         var errorMessage = xhr.status + ': ' + xhr.statusText
         alert('Error - ' + errorMessage);
     }
});
An example of done and fail being used:
$.ajax("submit.php")
  .done(function(data) {
      //Ajax request was successful.
  })
  .fail(function(xhr, status, error) {
      //Ajax request failed.
      var errorMessage = xhr.status + ': ' + xhr.statusText
      alert('Error - ' + errorMessage);
})

Source: link

0

I'm using XMLHttpRequest in JavaScript. However, it gives me an error, and I don't know what my problem is. I have to parse an XML file and assign its contents to the webpage - here's my code:
<script = "text/javascript">

    window.onload = onPageLoad();
    var questionNum = 0;

    function onPageLoad(questionNum) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET","quiz.xml");
        try {
            xmlhttp.send(null); // Here a xmlhttprequestexception number 101 is thrown 
        } catch(err) {
            document.getElementById("body").innerHTML += "\nXMLHttprequest error: " + err.description; // This prints "XMLHttprequest error: undefined" in the body.
        }
        xmlDoc = xmlhttp.responseXML;
        parser = new DOMParser(); // This code is untested as it does not run this far.
    }
</script>
My XML file is inside the same directory.
<question>
    <query>what is 2+2?</query>
    <option>4</option>
    <option>5</option>
    <option>3</option>
    <answer>4</answer>
</question>
First start by reading how to use XMLHttpRequest.open() because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send(). Here's an example from MDN:
var oXHR = new XMLHttpRequest();

oXHR.open("GET", "http://www.mozilla.org/", true);

oXHR.onreadystatechange = function (oEvent) {
    if (oXHR.readyState === 4) {
        if (oXHR.status === 200) {
          console.log(oXHR.responseText)
        } else {
           console.log("Error", oXHR.statusText);
        }
    }
};

oXHR.send(null);
You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:
var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false); 
request.send(null);

if (request.status == 0)
    console.log(request.responseText);
Solution: assign a callback function to the objects "onreadystatechange" -event and handle the data in that function
xmlhttp.onreadystatechange = callbackFunctionName;

Source: link

0

Example,
fetch(url).then((response) => {
  // Always gets a response, unless there is network error
  // It never throws an error for 4xx or 5xx response 😟
}).catch((error) => {
  // Only network error comes here
});
First lets see, without handling errors,
fetch(url)
  .then(response => {
    return response.json();
  })
  .then(jsonResponse => {
    // do whatever you want with the JSON response
  });
We can rectify it by throwing error and allow only response which has status code between 200 and 299.
fetch(url)
  .then((response) => {
    if (response.status >= 200 && response.status <= 299) {
      return response.json();
    } else {
      throw Error(response.statusText);
    }
  })
  .then((jsonResponse) => {
    // do whatever you want with the JSON response
  }).catch((error) => {
    // Handle the error
    console.log(error);
  });
This will fix the problem, you can even extract out the checking status part as a function which returns a promise or throw error.
function CheckError(response) {
  if (response.status >= 200 && response.status <= 299) {
    return response.json();
  } else {
    throw Error(response.statusText);
  }
}

// Now call the function inside fetch promise resolver
fetch(url)
  .then(CheckError)
  .then((jsonResponse) => {
  }).catch((error) => {
  });
It is same as promises, only the syntax will change. First we will see without error handling,
const response = await fetch(url);
const jsonResponse = await response.json();
console.log(jsonResponse);

Source: link

Recent Questions on javascript

    Programming Languages