Submit form only after API query was successful to populate field - javascript

I've got a form like this:
<h4>Front Page</h4>
<form action="/action_page.php" method="get">
<input value="EC2R 6DA" id="postcode_input">
<input id="admin_district" placeholder="Admin District">
<input type="button" id="get_postcode" value="Check">
</form>
And JavaScript like this:
$(document).ready(function() {
$("#get_postcode").click(function(event) {
event.preventDefault();
var postcode = $("#postcode_input").val();
$.get(encodeURI("https://api.postcodes.io/postcodes/" + postcode))
.done(function(data) {
$("#admin_district").val(data.result['admin_district']);
console.dir(data);
})
.fail(function(error) {
fullResult.html(JSON.stringify(error.responseJSON, null, 4)).slideDown();
});
});
});
I'm wondering how I validate that the JavaScript API call completed before submitting the form, and then if it did, then I submit the form. At the moment it prevents the form from submitting so it can make the API call, but after the API call completed, it then doesn't do anything, when it should then submit the form.

Give your form an id attribute
<form id="myForm" action="/action_page.php" method="get">
Then in your $.get, in the .done function add:
$("#myForm").submit()

Related

Laravel Query Ajax Update

Hello someone can you explain me how to update with Ajax!!
I use laravel
I want html and ajax only
My routes
Route::post('/post/homepage', 'AdminController#HomePage');
First, you should name your route:
Route::post('/post/homepage', 'AdminController#HomePage')->name('post.create');
Then, create your HTML form :
<form id="myForm">
{{csrf_field()}}
<label for="name">Article Name :</label>
<input id="name" name="articleName" type="text" required>
<button type="submit">Save</button>
</form>
Note: {{csrf_field()}} will generate the Form CSRF field. Or you can use instead :
<input type="hidden" name="csrf_token" value="{{csrf_token()}}">
I'll use jQuery to handle ajax:
<script type="text/javascript">
$(document).ready(function (){
$('#myForm').submit(function (e) {
e.preventDefault(); //Do not submit the form
var dataflow=$(this).serialize(); //Get the inputs value
$.post('{{route('post.create')}}', dataflow, function (data){ //post.create is the route name
//The request is done, do something with the server response
});
});
});
</script>

Stop form from redirecting on submit

I'm very aware that this question has been asked several times but I have tried at least 6 solutions and it has not worked. I'm collecting data to send to a google form but on form submission the browser redirects to a success page. I'd like for it to all happen using AJAX but my code isn't working.
HTML:
<form id="userinfo" method="get" action="https://script.google.com/macros/s/xxx/exec" accept-charset="UTF-8" onsubmit="return false">
<input type="text" name="name" id="formname" placeholder="Name">
<input type="text" name="email" id="formemail" placeholder="Email">placeholder="Game Days">
<input type="submit" value="submit" id="upload_data"/>
</form>
JS:
$("#userinfo").submit(function(e) {
var urll = "https://script.google.com/macros/s/xxx/exec"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: urll,
data: $("#userinfo").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
You could use the jQuery Form Plugin to send the form without doing a submit.
Your code should look kinda like this:
$("#userInfo").ajaxSubmit({
success: function(data)
{
alert(data); // show response from the php script.
}
});

jquery AjaxSubmit function how to get result from the form page to display

I'm trying to understand how to use ajaxSubmit() properly and I'm having some difficulties. I want to submit my form with ajax and after change the container value to the result echo by the form. I have an HTML form
<form action="contact.php" method="post" id="contact_form" >
<div id="form-box">
<input type="text" name="name" maxlength="40" >
<input type="submit" name="contact" value="SUBMIT" />
</div>
</form>
And then in JS I use the following code to submit the form to contact.php
$(document).ready(function() {
var options = {
success: showResponse
};
$('#contact_form').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
function showResponse(responseText) {
$("#form-box").html("Thank you message");
}
Now, the #form-box changes with my "Thank you message" ... but how do I grab what is echo from contact.php after the script is executed?
I'm not sure how to do this and make it work.
It would be included in the responseText, assuming your PHP file is actually outputting something.
Try updating your function to
function showResponse(responseText) {
$("#form-box").html("Thank you message"+responseText);
}
The 'responseText' parameter contains the response from php file.
function showResponse(responseText) {
console.log(responseText);
$("#form-box").html("Thank you message");
}

Onsubmit event after javascript form submit

I have an upload file form, and i try to upload the file when it's selected,so i tried something like this:
<form enctype="multipart/form-data" method="POST" onsubmit="return
UploadFile(this);">
<input id="upfile" type="file" onchange="this.form.submit();"/>
</form>
The form.submit() works , but of course i need to do some validation on submit,so i tried to run a function:
function UploadFile(file){
alert('Bleah');
return false;
}
On normal circumstances it should return false, and the form shouldn't reload the page,but this doesn't happens.
If i add a submit input into the form, it works as expected:
<form enctype="multipart/form-data" method="POST" onsubmit="return
UploadFile(this);">
<input type="submit" name="upload" value="Upload">
<input id="upfile" type="file"/>
</form>
Can anyone explain me what is wrong please?
Try this:
function UploadFile(file) {
if (file.value === '') {
alert("Invalid File");
} else {
alert('Form will be submitted now!');
document.getElementById('myForm').submit();
}
}
<form enctype="multipart/form-data" method="POST" id="myForm">
<input id="upfile" name="upfile" type="file" onchange="UploadFile(this);" />
</form>
To upload the file when it's selected, you must call UploadFile() function on the input change, not on the form change tag. If you submit on input change, the page gets reloaded.
So, you'd better use something like this:
$('#upfile').onchange(function(){
if(UploadFile(this.parent('form'))){
this.parent('form').submit();
}
})
And you won't need onchange and onsubmit inside the tags any more.
Solution:
<form id="formname" enctype="multipart/form-data" method="POST" action="test.html">
<input id="upfile" type="file" onchange="sendForm()"/>
</form>
<script>
function sendForm() {
var field = document.getElementById("upfile");
if (field) {
console.log("the is a file and the form will be sent");
document.forms["formname"].submit();
}
}
</script>
OLD--
I dont understand, how would you like to submit the form without a submit button? or at least, handle the submission in javascript "object.addEventListener("keydown", myScript);"
--
ok, I read it once again and I understand the question
You need to handle this on javascript and detect the selection of the file. Look at this thread:
how to check if a file is selected using javascript?

I have form with same name

I am try to send ajax form using jQuery in my html form with same names and deffirent values, but what happen is when I submit the form my ajax won't work and it will submit to #. someone can explain me why?
my HTML form:
<script src="lib/jquery/jquery.1.9.0.min.js"> </script>
<form name="Form" action="#" method="POST">
<input name="idnum" type="hidden" value="somevaluehere1">
<button type="submit">btn 1</button>
</form>
<form name="Form" action="#" method="POST">
<input name="idnum" type="hidden" value="somevaluehere2">
<button type="submit">btn 2</button>
</form>
this is my ajax:
$(document).ready(function() {
$("form[name=form]").submit(function(e){
e.preventDefault()
$.ajax ({
type: "POST",
url: "ajax/post.php",
data: $(this).serialize(),
success: function(data) {
alert(data)
}
});
});
});
sorry to my English guys
Form is not the same as form. Your selector doesn't match the forms because attribute selector values are case sensitive.
Change $("form[name=form]") to $("form[name=Form]").
You can prove this by comparing alert($("form[name=form]").length); to alert($("form[name=Form]").length);
Note, however, that the name attribute for form elements should hold a unique value so you should switch to using the class attribute instead (then you can use the class selector (form.Form).

Categories