Back

Technologies:

javascriptjavascript
htmlhtml
avatar
Tolerim
a month ago

How do I send a post request to an API using JavaScript?

I am facing an issue with my Angular form, which contains two button tags. One button is used to submit the form on ng-click, and the other button is for navigation using ng-click. However, when I click the second button, the page refreshes and triggers a 404 error. I have verified that the function is being executed. Interestingly, if I remove the ng-click or comment out the code in the function, the page does not refresh. Another solution is to replace the button tag with an anchor tag (<a>) with a href="" attribute. However, it seems like a bug since the function executes even after causing a page refresh. Here is the code for the form and the controller method:
$scope.showChangePassword = function() { $scope.selectedLink = "changePassword"; };
Answers(1)
avatar
Tolerim
a month ago
Verified Answer
It sounds like the issue is with the default behavior of the button tag within an HTML form. When you have a button inside of an HTML form, without specifying a type, it defaults to type="submit" which will cause a page refresh when clicked. To fix this, you can either change the type of the navigation button to "button" explicitly by adding type="button" to the button tag like this:
Alternatively, you can call event.preventDefault() inside the showChangePassword() function to prevent the default behavior of the button from occurring. Here is how you can update the code:
$scope.selectedLink = "changePassword";
  event.preventDefault();
};
By adding the parameter event to the function, you can access the event object and call preventDefault() on it to stop the page refresh from happening.
;