简体   繁体   中英

XHR call using plain JavaScript

I am having issue with XHR call made to GitHub domain from localhost.

Upon clicking on the button Click to get User Profile with Ajax+JS , a JS function getUser() gets called. Code works as expected, ie, gets a particular GitHub user details(full name and avatar) and displays on the page.

## Code for "Click to get User Profile with Ajax+JS" button
<input type="button" value="Click to get User Profile with Ajax+JS" onclick="getUser()" id="jsBtn" />

BUT, when I call the same JS function on form submission using submit button (or return), it does not return the expected result ie, user details.

## Code for "Submit" button
<form id="myForm" onsubmit="getUser()">
    #...
    <input type="submit"/>
</form>

Upon inspecting under Network , I see the difference in the way Request URL is formed in Request Headers Section:

## With GitHub username input as kirtithorat
## First Case With "Click to get User Profile with Ajax+JS" button
Request URL:https://api.github.com/users/kirtithorat

## Second Case With "submit" button
Request URL:http://localhost:3000/html_file_name?username=kirtithorat

Why the difference in behavior? The same JS function works for onclick but not for onsubmit.

NOTE:

  1. I am looking for a Pure JS Solution. I know how to do it in jQuery.
  2. I don't actually want the form to be submitted, only the onSubmit event should be triggered.

Here is my JSFiddle

Your second URL looks like the form submission, NOT the result of calling getUser() (the getUser() ajax call probably came right before the form submission).

If you don't want the form to actually submit (which it appears is how you want it) and only want your onSubmit handler to be called, then you need to make sure the default behavior of submitting the form is prevented.

You can block form submission by just adding a

return false;

to the end of your getUser() onsubmit handler function.


Or, you can block the form submission by passing the event into the getUser() function and using e.preventDefault() .


The other reason to block the form submission is that the page will reload with the results of the form submission and your javascript will not still be active to receive the results of the getUser() ajax call. So, you must use one and only one of the Ajax call or the form submission (it looks like you just want the ajax call so you can prevent the form submission).

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