Ajax before HTML form submission (asynchronously) - javascript

<form target="_blank" method="POST" action="somePage.php" id="myForm">
<input type="hidden" name="someName" value="toBeAssignedLater"/>
<button type="submit">Proceed</button>
</form>
At the beginning, the value of someName is not determined yet, I want to execute an Ajax to get and assign the value to it before the form is actually submitted.
I tried:
$("#myForm").submit(function (e) {
var $this = $(this);
someAjaxFunction(function (data) {
$this.find('input[name="someName"]').val(data.value);
});
});
But the form would have already submitted before the Ajax is finished, how can I ensure the form would be submitted after the Ajax is finished.
I want to keep the form submit event initiated by the user instead of code, such as $("#myForm").trigger('submit');, since I don't want the new window tab to be blocked by browsers.

$("#myForm").submit(function (e) {
var $this = $(this);
someAjaxFunction(function (data) {
$this.find('input[name="someName"]').val(data.value);
// submit form without triggering jquery handler
$this[0].submit();
});
// cancel the current submission
return false;
});

Why don't you ajax the value at page load and than submit the data?
$(function(){
someAjaxFunction(function (data) {
$('input[name="someName"]').val(data.value);
});
$("#myForm button").on('click',function(){
$(this).submit();
});
});
or place the ajax call on click event and submit whan the values is updated:
$(function(){
$("#myForm button").on('click',function(e){
e.preventDefault();
$.ajax({
url:url, //other params
success:function(data){
//thing to do before submit
$('input[name="someName"]').val(data.value);
$(this).submit();
}
});
});
});

Related

PHP code doesnt work together with JS function on "onclick"

i have a button in which i want it to perform 2 task; php and js.
The php part : generate different text everytime the button is pressed.
The js part : disabling the button for 5 secs and then enabling it back.
HTML
<button onclick = "disable();" class=btnGenerate type="submit" id="submit" name="submit" >GENERATE</button>
PHP
if(isset($_POST['submit'])){
$num=mt_rand(1,10);
$result=mysqli_query($con,"SELECT * from quote_table where id=$num");
$row = $result->fetch_assoc();}
JS
<script>
function disable(){
document.getElementById("submit").disabled = true;
setTimeout(function() { enable(); }, 5000); }
function enable(){
document.getElementById("submit").disabled = false;
}</script>
The PHP part only works when i delete the "onclick = "disable();" on the html but it doest seem to work when i add it. Can a button carry out PHP and JS at a single click ? Thanks in advance.
A disabled button can't be a successful control.
Don't depend on the name/value of the submit button being submitted in the form data if you are going to disable it.
Replace isset($_POST['submit']) with some other condition.
If you trigger a form submission, unless you're using AJAX the page will simply reload, rendering the enable() method moot unless
you're using it to re-enable the button on fail condition or on
successful return of data via AJAX.
It's sounds to me like you're trying to get data via request to the server, without reloading the page, and then re-enable the submit button after the data is returned. In that case you need to use AJAX.
HTML
<form action="/" method="post" id="form">
<button class=btnGenerate type="submit" id="submit" name="submit" >GENERATE</button>
</form>
JS
<script>
document.getElementById('submit').addEventListener('click', function(event){
event.preventDefault(); // prevents browser from submitting form
var form = document.getElementById('form');
var submit = document.getElementById('submit');
// using JQuery ajax
$.ajax(form.action, {
data: form.serialize(),
beforeSend: function() { // runs before ajax call made
// disable submit button
submit.disabled = true;
},
success: function(response) {
console.log(response);
// deal your return data here
},
error: function(error) {
console.log(error);
// deal with error
},
complete: function() { // runs when ajax call fully complete
// renable submit button
submit.disabled = false;
}
});
});
</script>

Create conditional submit using jQuery event.preventDefault()

Before submitting my form, I wan't to check if inserted dates are available. I have a php script which can perform this check and I want to call this php script via jquery/ajax.
I believe I should use event.preventDefault(); to avoid that the form is submitted. However I somehow cannot combine it with the Ajax call. The action of the form is performed anyway, the user is redirected to test.html.
What am I doing wrong? Anyone any suggestions?
My .html
<form id="checkData" action="test.html" method="post">
<input type="text" id="from" name="from">
<input type="text" id="to" name="to">
<input type="submit" value="Book">
My .js
$( "#checkData" ).submit(function( event ) {
var data = $("#checkData :input").serializeArray();
$.post("check.php", data, function(json){
if (json.status == "fail") { //this works fine without using the "event.preventDefault() statement"
event.preventDefault();
}
}, "json");
Put the preventDefault() on the click event of the submit button instead.
I didn't test the code so it might have some typo.
$( "#checkData input[type='submit']" ).click(function( event ) {
event.preventDefault();
var data = $("#checkData :input").serializeArray();
$.post("check.php", data, function(json){
if (json.status != "fail") {
$(#checkData).submit();
}
}, "json");
event.stopPropagation();
You can prevent the default behavior immediatelly.
Execute the post request.
If everything is ok, off the event submit and execute that the form submission programmatically.
if (json.status !== "fail") {
$self.off('submit', fn);
$self.submit();
}
This is the approach:
function fn(event) {
event.preventDefault();
var data = $("#checkData :input").serializeArray();
var $self = $(this);
$.post("check.php", data, function(json) {
if (json.status !== "fail") {
$self.off('submit', fn);
$self.submit();
}
}, "json");
}
$("#checkData").submit(fn);

jQuery .submit() not working after ajax response

I was trying to call jQuery.submit() function after ajax response. Where ajax response contains a form. But it couldn't call jQuery.submit() function when i submit the form without refresh.
I prepend the form with the existing code after successfull ajax response
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
},
error: function(data) {}
So after adding the form to the existing code. When i tried to submit the form it's got refresh instead of calling the function. How to make jQuery.submit() workable from ajax response?
$(".replyName").submit(function(event) {
alert(event.currentTarget[0].value);
});
You should place the submit event after you prepend the form. Because event's are only binded to the elements after the DOM is loaded.
And because the prepend the form dynamically, jQuery doesn't know which element it has to submit, because it didn't exist at the time it binded the event.
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
$( ".replyName").submit(function( event ) {
alert(event.currentTarget[0].value);
event.preventDefault();
});
},
error: function(data) {}
Since the form is not created in the document, you cant listen to submit event, unless you put the event listener after you prepend form into the dom
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
$(".replyName").submit(function(event) {
alert(event.currentTarget[0].value);
});
},
error: function(data) {}
You can also handle the event from body dom
$('body').on('submit', '.replyName', function(e){
// code here
});
There are two thing you can do:
Either you can rebind the click function like this:
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
$('button').bind('click', function (event) {
event.preventDefault();
alert(event.currentTarget[0].value);
});
},
error: function(data) {}
or you can try this
$('button').on('click', function(e){
// code here
});

[jQuery]Page refreshes after appending html with .html()

So I'm trying to get some data from the server with php but as soon as it's loaded onto the page it seems to reload the page and make it disappear again.
My html:
<form id="searchForm">
<input name="searchValue" type="text" id="search">
<input type="submit" name="Submit" value="Zoek op klant" onclick="getKlanten()">
</form>
<div id="klanten">
</div>
My js:
function getKlanten(){
var value = $("#search").val();
$.ajax({
url:'includes/getKlanten.php',
async: false,
type: 'POST',
data: {'searchValue':value},
success: function(data, textStatus, jqXHR)
{
$('#klanten').html(data);
},
error: function () {
$('#klanten').html('Bummer: there was an error!');
}
});
}
Can anyone help? It gets put into the div but then instantly disappears again.
Firstly, avoid inline click handlers. The page reloads because by default a form submits the form content to the url specified in action attribute.
Instead attach an event to the form and use preventDefault to avoid the page from refreshing. Do something like this
$('#searchForm').on('submit', function(e){
e.preventDefault();
// your ajax request.
});
Or attach an event to input button like this
$('input[type="submit"]').on('click', function(e){
e.preventDefault();
// your ajax request
});
Read more about preventDefault here

jQuery Submit Refreshing Page

The following code is intended to do a purely ajax POST request, instead it seems to do the POST via ajax and then the browser navigates to the response.
The HTML...
<div id="bin">
<form class="add" method="post" action="/bin/add/">
<p>I'm interested! Save for later.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Save">
</form>
<form style="display:none;" class="remove" method="post" action="/bin/remove/">
<p>I changed my mind--I'm not interested.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Unsave">
</form>
</div>
The jQuery...
$('#bin form').submit(function() {
$.post($(this).attr('action'),{
success: function(data) { $(this).hide().siblings('form').show() },
data: $(this).serialize()
});
return false;
})
As far as I understand it, the return false; line should mean that no matter what, any calls to the submit function or clicks on the 'Submit' button or the hitting of enter means that my function will execute and the browser will not navigate to /bin/add or /bin/remove. But for some reason, the browser is changing pages.
Any idea what I'm doing wrong here? Thanks.
It could be your JavaScript is failing, so the default behaviour is being executed.
Try to examine the XHR in a tool like Firebug.
Also, you could try event.preventDefault() (where the first argument to your event callback is event).
my bet it's because of the $(this), try it this way....
$('#bin form').submit(function() {
var $this = $(this);
$.post($this.attr('action'), {
success: function(data) {
$this.hide().siblings('form').show()
},
data: $this.serialize()
});
return false;
});
demo no error
demo with the error
Use event.preventDefault() to prevent the default action of the event. One benefit is that you can place this before the Ajax request, so that if it fails, you will still have prevented form submission.
Your code is failing because the value of this in your success callback is the global window object. Your attempt to hide it fails. You probably want this to refer to the form, like this:
$('#bin form').submit(function(ev) {
var _this = this;
ev.preventDefault();
$.post($(this).attr('action'), {
success: function() {
$(_this).hide().siblings('form').show();
},
data: $(this).serialize()
});
})
See a working example.
Is the $(...).submit(...) inside a $(document).ready(function(){ code here }); ?
should be like:
$(document).ready(function() {
$('#bin form').submit(function() {
$.post($(this).attr('action'), {
success: function(data) { $(this).hide().siblings('form').show(); },
data: $(this).serialize()
});
return false;
});
});

Categories

Resources