ajax call doesn't work when a submit button is used - javascript

I'm trying fetch a live currency rate using the following API.
"http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj"
When I click on a button, it alerts the rate and works just fine. I'm using the following Ajax code.
<script type="text/javascript" language="javascript">
function testCurrencyRate()
{
$.ajax({
datatype:"html",
type: "GET",
url: "ajax/LiveCurrencyRate.php",
data: "t="+new Date().getTime(),
success: function(response)
{
alert(response);
},
error: function(e)
{
alert('Error while fetchig the live currency rate.');
}
});
}
</script>
The Ajax request goes to the LiveCurrencyRate.php page which is as follows.
$url="http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj";
$result = file_get_contents($url);
echo $result;
and the <form></form> which contains the only button which when clicked makes an Ajax request on this URL ajax/LiveCurrencyRate.php.
<form id="testForm" name="testForm" action="" method="post">
<input type="submit" id="btnTestCurrencyRate" name="btnTestCurrencyRate" value="Test" onclick="testCurrencyRate();"/>
</form>
Everything is fine. The problem however arises when I change the button type from type="button" to type="submit", it doesn't work. The alert box in the error part of the Ajax function shows the alert box just for a while and all of a sudden it disappears. I can't find any reasonable cause that may prevent this request from being completed. The same thing worked for me in my previous project but I was using XMLHttpRequest for making Ajax requests. What's going wrong here?

type="submit" causes the web browser to submit the form via a postback (because your method attribute is set to "POST"), which causes the page to refresh. The action attribute of the <form> tag determines where the data gets sent to, and then that page loads with the data provided. When this happens, all javascript on the page terminates because you are effectively going to a different page or reloading the current one.

The page is submitting because you are not cancelling the default action of the click. You need to stop that event from happening. With your code, you can add a return false to the onclick, but it is better to add the events in an unobtrusive manner.
$("#btnTestCurrencyRate").on("click",function(e){
testCurrencyRate();
e.preventDefault();
});
better to catch it on the form submission and not onclick
$("#testForm").on("submit",function(e){
testCurrencyRate();
e.preventDefault();
});

When you click the submit button your form is being posted to you web server. You need to prevent the form from posting by using something like:
$("#testForm").submit(function(e){
e.preventDefault();
});

because your page is submitting. you need to return false from the onclick handler if you want to prevent the submit.
HTML:
<input type="submit" id="btnTestCurrencyRate" name="btnTestCurrencyRate" value="Test"/>
JS:
document.getElementById('btnTestCurrencyRate').onclick = testCurrencyRate;
function testCurrencyRate() {
... snip ...
return false;
}

Related

Javascript Console Commands Not Working After Ajax Sending Back in Page

I'm controlling a website in Chrome developer console. There is a form and a submit button for sending the form via ajax (I guess) without refreshing the page. The form is resetting after sending information.
I assigned some attributes to a form element in the page with Javascript. There are some processes that do not matter, and I'm sending the form but the attributes of the elements are resetting in the new form. I am forced into calling the same scripts again.
Is there anyway for global valid command with console coding, because the webpage isn't mine? (In pure-JavaScript)
there are a couple ways to achieve this.
the easiest: will probably be to create a snippet in the web developer tools, and run it from there.
Another manner would be to create a google extension (with 'declarativeContent' and 'activeTab' permissions) that can inject content script or execute script on a page.
you can find more information on developing chrome extensions and background page events here: https://developer.chrome.com/extensions/background_pages
While using the form in a html page the values inside the form get submitted to the url given in the form action without checking the javascript if some callback functions are defined.
<form method="post" action="your_url">
....
</form>
If you doesn't provide the action then the form get submitted to the same page, and no javascript action will take place.
If you want to submit the form using the javascript action then you can use one of the following methods.
Method 1: Calling javascript function from action
<form method="" action="Javascript:your_function()">
....
</form>
<script>
function your_function(){
...
}
</script>
In this method all the form validation and ajax submission should be carried out manually inside the function. URL and METHOD should also be defined inside the ajax call.
Method 2: Using JQuery form onSubmit
<form id="target" method="" action="">
....
</form>
<script>
$( "#target" ).submit(function( event ) {
event.preventDefault();
alert( "Handler for .submit() called." );
});
</script>
In this method the form validation is handled and callback to submit function will take place only when the form is validated. The ajax url should be given inside the ajax call.
Method 3: Using JQuery Ajax Validation Submit
<form id="target" method="post" action="your_url">
....
</form>
<script>
$("#target").validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
dataType: 'json', //optional
success: function(data) {
...
}
})
}
})
</script>
In this method the URL and METHOD are defined in the form. The validate function will check whether the form is valid and submitHandler will execute when the form is valid. $(form).ajaxSubmit callback function will handle the ajax call to the URL and METHOD given the the form. This method will well suit for your question. Also try other methods in you need so
NOTE: Refer https://jqueryvalidation.org/validate/ for documentation.
Remove any submit listener on the form. Then attach your own submit listener with js event.stopPropagation() break.

How to stay on same position after submitting an html form?

I have a simple html form:
<form action="addToCart" method="post"><br><br>
<input name="productId"
value="${product.id}" type="hidden"> <input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>"
type="submit">
</form>
Every time I click on "submit", it brings me straight back to top which creates a poor user experience because the user would have to scroll back down where he was browsing the products... Can I do this without using a script?
-Every time I click on "submit", it brings me straight back to top.
Yes that is what default functionality when submitting forms, it always repaints the dom so it causes a jump and page's top position is rendered.
-which creates a poor user experience because the user would have to scroll back down where he was browsing the products
To make a good user experience you can use ajax for this functionality, as you tagged jQuery in your question then you can try with jquery ajax:
$('form').submit(function(e){
e.preventDefault(); // stops the form submission
$.ajax({
url:$(this).attr('action'), // action attribute of form to send the values
type:$(this).attr('method'), // method used in the form
data:$(this).serialize(), // data to be sent to php
dataType:"text",
success:function(data){
alert(data); // you can alert the success message.
},
error:function(err){
console.log(err);
}
});
});
I have used a dataType:"text", just assuming if you are going to echo "Added in the cart."; kind of message from the php.
Ajax is your best bet if you want to achieve what you want
$('.submit').on('click',function(event){
event.preventDefault(); //this is important else page will get submitted
$.ajax({
url:'where you want to process data',
dataType:'html',
data: your form data as json or whatever type
success: function(result){
//here you can update any thing on the frontside
}
});
});
Since you're using onclick attribute on your button, you have to change type attribute from submit to button. That way you can get your addedCart() method to fire. Then handle form submission inside that method (if your submit handler isn't already there).
<input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>" type="button">
Script:
function addedCart(){
// ... your method on click
// $.ajax({...});
};
If you're not using jQuery, you can handle form submission with XMLHttpRequest :
How to make an AJAX call without jQuery?

Ajax Request dont work without alert statement

I have a problem with a AJAX call. I am trying to access the inputs of a HTML
form element and write this to a database with a PHP script.
My JS code looks like this....
function getWriteValues() {
var x = document.getElementById("eingabemaske");
var jqxhr = $.post( "source/form_handler.php",
$( "#eingabemaske" ).serialize() );
alert( 'Eintragung erfolgreich durchlaufen' );
}
The PHP part isn't interesting because there nothing except the database insert happens.
Now to my Problem. The Function makes what it should do. But when I delete the alert() statement, nothing works any more. That means that nothing is written to the database and the ajax call could not be made. I can't figure out where the problem is.
I use jQuery in Version 2.1.1.
When you click the submit button you:
Run the JS
Send the Ajax HTTP request
Submit the form
Leave the current page
Cancel the Ajax HTTP request because there isn't going to be anything left to handle it.
Either:
Prevent the default action of the submit button so you don't leave the page or
Get rid of the JS and do your database insertion in the program you specify in the action of the form
Do you call getWriteValues(), if the the form is submitted?
If so, don't forget to return false;
Check in your html "name" attribute is defined for each form elements or not as serialize() takes element name and its value.
Check whether you're getting the values in getWriteValues()
Verify these values are passed to form_handler.php script.
sample:
<form id="eingabemaske">
<input id="abc" name="abc" value="test" />
<input type="button" id="submit" name="submit" value="Submit" />
</form>
<script type="text/javascript">
$(function(){
$('#submit').on('click',function(e){
e.preventDefault();
getWriteValues();
});
});
function getWriteValues() {
console.log($( "#eingabemaske" ).serialize());
var jqxhr = $.post( "form_handler.php",
$( "#eingabemaske" ).serialize() );
//alert( 'Eintragung erfolgreich durchlaufen' );
}
</script>
in php script
print_r($_REQUEST);
It may be due to that alert message is giving time to ajax to perform its work. please check all the process that happens before and after the ajax. Also, as you are calling ajax from submit button (i suppose that that u have called this function from "onsubmit" attribute of the form), may be its submtting the form before ajax is completed. Please return false at the end of function in order to stop function processing further.

How do you use twitter bootstrap button with jquery?

What I want to do is when a user clicks on the submit button in a forum, it should send the data collected to the php script and ideally, stay on the same page. Currently, I have in the form(I have other tags in the form but these are the two things I need to focus on)
<form name = "reply" id="replyForm" action="sqlinserter.php" method = "POST">
<button id = "newThread" class="btn btn-primary" type="submit">Submit</button>
As you can see, I use a form that sends the data to sqlinserter.php when the user clicks the submit button. Basic form stuff. Right now, when it clicks submit it goes to the actual sqlinsert.php page which is blank because it is just sending data to the database.
However, I would like to create a simple jquery script where you click the button it sends the data using ajax. I have been noticing that twitter bootstrap works differently with buttons and I am not sure how to use their buttons with jquery. Any help with this would be great.
So,
I need to figure out how to use twitter bootstrap buttons with
jquery. Specifically, I need to figure out how to use the submit
button.
How to send data using ajax?
I need to figure out how to use twitter bootstrap buttons with jquery. Specifically, I need to figure out how to use the submit button.
Bootstrap can be used together with jQuery, no additional steps required. Actually even bootstrap itself use jQuery in their framework.
You can still use jQuery like usual, and bootstrap like usual. Both will work, without any conflicts.
How to send data using ajax?
It can be done by using one of jQuery AJAX function, for example $.ajax.
Just add new event, click, on your button #newThread. Write the AJAX inside the event handler. Example based on your code can be seen in below.
HTML
<form name = "reply" id="replyForm" action="sqlinserter.php" method = "POST">
<button id = "newThread" class="btn btn-primary" type="submit">Submit</button>
</form>
JS
$(function() {
$('#newThread').on('click', function (e) {
e.preventDefault(); // disable the default form submit event
var $form = $('#replyForm');
$.ajax({
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize(),
success: function (response) {
alert('response received');
// ajax success callback
},
error: function (response) {
alert('ajax failed');
// ajax error callback
},
});
});
});
There isn't any specific way to use a twitter bootstrap button. Just grab the id of this submit and submit the data via ajax like below:
$.ajax({
type:'GET',
dataType:'xml',
url:'path/to/phpfile.php',
success:function(data) {
// Do the handling here
},
error:function() {
alert("Sorry, Ajax call Failed");
}
});
There is nothing specific to form submission with bootstrap. You just need to make sure the button is insde the form (which you should want even if it wasn't bootstrap).
<form name = "reply" id="replyForm" action="sqlinserter.php" method = "POST">
<button id = "newThread" class="btn btn-primary" type="submit">Submit</button>
</form>
you are missing the closing </form> tag

How can I make a submit button issue a post of the form but have the result coming back placed into an element HTML?

I am working on a single page web application. I added the following code for login:
$('#loginLink, #registerLink')
.click(function () {
var $link = $(this);
var href = $link.attr('data-href');
$('#article').load(href);
}
return false;
});
This works and populates the #article section with the following HTML. Note that I
stripped out some of the code for this question:
<form action="/User/Account/Login" method="post" novalidate="novalidate">
...
note there's client side validation on the page but I just don't show it here
...
<ol>
<li>
<input id="UserName" name="UserName" type="text" value="">
</li>
</ol>
<input type="submit" value="Log in">
</form>
When the form appears if I click on the submit then it sends a request to
the browser and this returns with a new page. Is there a way I can still
keep the submit action (for client side validation which is on my page)
but have the result of the submit bring back a page that again displays
in the #article section?
Is there a way I can still keep the submit action (for client side
validation which is on my page) but have the result of the submit
bring back a page that again displays in the #article section?
Not sure I understand this correctly but if you want to load article content without a page re-fresh on submit you could bind to the submit event and execute an ajax call similar to this:
I'm using on in the example below which was only added in jQuery 1.7. If you are using jQuery 1.6.x or lower you can use bind instead.
$("form").on("submit", function() {
var $form = $(this);
// if there are validation errors do not continue.
if(!$form.valid()){
return false;
}
// get the form data
var myData = $form.serialize();
// get the url to post to from the form's action attribute.
var myUrl = $form.attr("action");
// execute the post
$.ajax({
url: myUrl,
data: myData
success: function(data) {
// on success, write the returned article content into the article element
$('#article').html(data);
}
});
return false;
});​
You're looking for event.preventDefault() to avoid sending form and reloading the entire webpage. See this Fiddle.

Categories

Resources