0

I got a quick script working with HTML and JS, but I can't for the love of me get the response from the POST request. Here is what I have currently have:

<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="something()">Click Me!</button>
<script>
function something(){
  const Url = 'https://somelink.com';
  const date = 'somedata'
  var V
  
  $.post(Url,date,function(data) {
  V = data
  });
  
  alert(V)
}
</script>
</body>
</html>

I did try having the alert in the function(data) part but it would not register for some exact reason so I moved it out. Now it registers the alert but it can not get the response from the request.

I am testing it in JS Fiddle and the console log is

50:9
Uncaught ReferenceError: V is not defined

Any and all help/nudges will be greatly appreciated. My goal is to get the response from the request and use it further down the line, so I am just testing as a proof of concept/correct coding with the alert.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
lewism205
  • 33
  • 1
  • 6
  • Rewrite it like this and the alert will show the data https://jsfiddle.net/zkoxd6s3/ (one way to do this) –  Dec 09 '21 at 08:58
  • @ChrisG I am still unfortunately getting the variable V as "undefined" even though my server noted the request and sent a response. I suspected that the issue could be that the response was text/plain (e.g Hello), so I changed it to come as a json (e.g {"hel":"lo"} and still V is "undefined". Was the response from your test in a different format? – lewism205 Dec 09 '21 at 10:05
  • Here's example code that actually works: https://jsfiddle.net/khrismuc/wx0bhLtc/ –  Dec 09 '21 at 10:14
  • Yes the GET request works as intended even in my tests, for some reason it's the $.post that just wont return/show the response. – lewism205 Dec 10 '21 at 06:04
  • You need to post a [mre] so I can find the issue. Did you test your server using postman? You can check the request and response in the browser's dev tools (F12 -> console tab) –  Dec 10 '21 at 13:53
  • Yes, prior to writing the code I tested it in Postman to ensure we actually receive a response. Went so far as to set it to send any response even if the body is empty. I am not quite sure what it is because it works on a native app, postman, and just putting the request into the url bar in chrome, but not the JS or react web apps. It must be something with my backend. If I do find out what, I'll post an update here – lewism205 Dec 13 '21 at 06:01
  • Figured it out, I did not have CORS enabled on my end so I think the request was registering with an unverified SSL certificated whereas Postman it can run unverified requests. To all who may be having this issue, CORS is something to look into just in case – lewism205 Dec 13 '21 at 10:18

0 Answers0