putsreq icon indicating copy to clipboard operation
putsreq copied to clipboard

Issue while making ajax call with javascript

Open alaksandarjesus opened this issue 2 years ago • 1 comments

Hi.

I tried all the below code

    <!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="jquery.min.js"></script>
</head>

<body>

  <script src="jquery.min.js"></script>
  <script>
      const url = 'https://putsreq.com/bWVINoAIwR78cl7ajqhX';

      // Using Jquery

      jQuery.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        processData: false,
        data: '{"foo":"bar"}',
        success: function (data) {
          console.error(JSON.stringify(data));
        },
        error: function () {
          console.error("Cannot get data");
        }
      });

      /*
      // Using Vannila JS

      let xhr = new XMLHttpRequest();
      xhr.open("POST", url);

      xhr.setRequestHeader("Content-Type", "application/json");

      xhr.onreadystatechange = function () {
         if (xhr.readyState === 4) {
            console.log(xhr.status);
            console.log(xhr.responseText);
         }};

      let data = '{"login":"my_login","password":"my_password"}';

      xhr.send(data);
      */

      /*
       // Using Fetch

      fetch(url, {
        method: 'POST', // or 'PUT'
        headers: {
          // 'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Type': 'text/plain; charset=utf-8',
          // 'Content-Type': 'application/json',


        },
        body: JSON.stringify(data),
      })
        .then((response) => response.text())
        .then((data) => {
          console.log('Success:', data);
        })
        .catch((error) => {
          console.error('Error:', error);
        });
        */
    
  </script>
</body>

</html>

and i am getting response as

image

alaksandarjesus avatar Feb 22 '23 13:02 alaksandarjesus

@alaksandarjesus I've made some changes to prevent this from happening. Can you try it again?

There's something very confusing going on with these requests. With cURL, the body is received as-is, but for some reason, with the methods above, an addition \" was wrapping the body, and causing the issue.

phstc avatar Feb 26 '23 22:02 phstc