My form function is written in PHP and is expecting two variables to be passed. I have to submit the form and the variables using Javascript though. I understand I can use .submit() to actually submit the form using JavaScript but the variables that need to be passed to my form function are stored in two variables within my JavaScript. I'm having trouble understanding how to pass those JavaScript variables when I submit the form using .submit().
One idea that I have is adding hidden fields to my html form and setting the value of those hidden input values to what I have in my JavaScript variables.
I'm wondering if there is a way to to use .submit() and pass the variables via JavaScript?
Checkout FormData for a plain vanilla JS solution without jQuery:
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456);
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
There are examples how to use it with an existing form:
JS:
var docFormElement = document.getElementById('myForm');
var docFormData = new FormData(docFormElement);
docFormData.append("product_license","Enterprise");
var xhrObject = new XMLHttpRequest();
xhrObject.open("POST","postform.cfm");
xhrObject.send(docFormData);
HTML:
<form id="myForm">
<input name="product_name" type="text" value="ColdFusion" />
<input name="product_codename" type="text" value="Zeus" />
</form>
You can either keep a hidden input or a javascript variable to keep track of values. You can then use AJAX to submit values to PHP page :
<input id="name" type="hidden" .....
....
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "yourpage.php",
data: dataString,
success: function() {
//do something
}
});
details:
http://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59
Alternatively you can just update the hidden input values and submit the form:
<script type="text/javascript">
function submitform()
{
document.forms["formID"].submit();
}
</script>
<form id="formID" action="somepage.php">
Search: <input type='hidden' name='email'>
Submit
</form>
Related
What i'm basically trying to do,after clicking on each polygon a popup form appears where the user will input some values,press submit and after the php script and function runs ,it will supposedly show some markers on the map.I'm trying to make this form work as AJAX and execute the function within.
I already ajax successfully a html form before but it seems it needs some work to function properly within leaflet.
The form im trying to AJAX
var htmlformGuest = `
<h2>Search for parking slots</h2>
<form id="parkform" action="/findPark.php" method="post" >
Enter the polygon id:<br>
<input type="number" name="id_P" value="">
<br>
Max radius:<br>
<input type="number" name="Radius" min="50" max="500" value="" placeholder="50">
<br><b>
<input type="Submit" value="Submit">
<input id="form-polygon-id" type="hidden" name="PolygonID">
<input type="reset">
</form>
`;
The function i want to include when submitting the form ( which im not sure it works since i need to first ajax the form!)
function putMultipleMarkers(jArrayId, jArrayLat, jArrayLng) {
for (var i = 0; i < jArrayLat.length; i++) {
var multipleMarker = new L.marker(jArrayLat[i], jArrayLng[i])
.bindPopup(jArrayId[i])
.addTo(geojson);
}
}
What worked for me in a non-leaflet form previously was this code withing the function
$("#parkform").submit(function (e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: "findPark.php",
data: form.serialize(),
success: alert('Marker Map'),
})
});
Any help appreciated!
It's not really clean, but you can do $('body').html(data) on success:
$("#parkform").submit(function(e) {
e.preventDefault();
var dataForm = $(this).serialize();
var url = form.attr('action');
$.post(
url,
dataForm,
function(data) { // on success
$('body').html(data);
}
);
});
Because the data is the code response of your request, then it's the same page with POST array values.
This should be simple, yet it's driving me crazy. I have an html5 form that I am submitting with ajax. If you enter an invalid value, there is a popup response that tells you so. How can I check that the entries are valid before I run my ajax submit?
form:
<form id="contactForm" onsubmit="return false;">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required placeholder="Name" />
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" required placeholder="Subject" />
<label for="email">Email:</label>
<input type="email" name="email" id="email" required placeholder="email#example.com" />
<label for="message">Message:</label>
<textarea name="message" id="message" required></textarea>
<input type="submit" id="submit"/>
</form>
submit:
$('#submit').click(function(){
var name = $("input#name").val();
var subject = $("input#subject").val();
var email = $("input#email").val();
var message = $("input#message").val();
var dataString = 'email=' + email + '&message=' + message + '&subject=' + subject + '&name=' + name ;
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: dataString,
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
If you bind to the submit event instead of click it will only fire if it passes the HTML5 validation.
It is best practice to cache your jQuery selectors in variables if you use it multiple times so you don't have to navigate the DOM each time you access an element. jQuery also provides a .serialize() function that will handle the form data parsing for you.
var $contactForm = $('#contactForm');
$contactForm.on('submit', function(ev){
ev.preventDefault();
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: $contactForm.serialize(),
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
By default, jQuery doesn't know anything about the HTML5 validation, so you'd have to do something like:
$('#submit').click(function(){
if($("form")[0].checkValidity()) {
//your form execution code
}else console.log("invalid form");
});
If you are using HTML5 form validation you'll have to send the ajax request in the form's submit handler. The submit handler will only trigger if the form validates. What you're using is a button click handler which will always trigger because it has no association with form validation. NOTE: not all browsers support html5 form validation.
I prefer using the jQuery submit handler, you will still get the response to your form with the following method.
jQuery('#contactForm').on('submit', function (e) {
if (document.getElementById("contactForm").checkValidity()) {
e.preventDefault();
jQuery.ajax({
url: '/some/url',
method: 'POST',
data: jQuery('#contactForm').serialize(),
success: function (response) {
//do stuff with response
}
})
}
return true;
});
Not exactly sure what you mean. But I assume that you want to check in realtime if the input is valid. If so you should use .keyup instead of .click event, because this would lead to an action if the user presses submit. Look at http://api.jquery.com/keyup/
With this you could check the input with every new character insert and display e.g. "not valid" until your validation ist true.
I hope this answers your question!
U can also use jquery validate method to validate form like
$("#form id").validate();
which return boolean value based on form validation & also u can see the error in log using errorList method.
for use above functionality u must include jquery.validate.js file in your script
This is my form html in my Laravel application:
<button onclick="submitForm()">submit form using jquery ajax</button>
<form name="fbCommentCountform" action="{{ route('blogs.update', ['id'=>$id]) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PUT">
<input type="text" name="commentCount" id="fbFormCommentCount">
</form>
This is the ajax Javascript code I am trying to use:
function submitForm() {
var http = new XMLHttpRequest();
http.open("POST", "{{ route('blogs.update', ['id'=>$id]) }}", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=";
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
I'm a little confused on how I define my params to make it send the data in my id #fbFormCommentCount input box. I simply want the form to submit on button click without reloading the page and using a PUT method because it is for a update request in the controller. Any guidance would be greatly appreciated!
You can do this pretty easily using jQuery's .ajax() like this:
$('form').on('submit', function(e){
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.prop('action'),
method: 'PUT',
data: $this.serialize(),
}).done(function(response){
}).error(function(err){
});
});
The e.preventDefault() will keep the form from submitting and causing the page refresh.
Then just move your button into the form and give it a type of submit
<button type="submit"> Submit form using jquery ajax </button>
You need to prevent the default event of the form submission.
Here's a minimal example of how to do it
https://jsfiddle.net/w208gsj7/1/
HTML
<form>
<button type="submit"id="submit">
Submit
</button>
</form>
JS
document.getElementById('submit').addEventListener('click', submitForm);
function submitForm(ev) {
ev.preventDefault();
// ... code
}
You need to grab the values from your form, like so:
var commentCount = document.getElementById('fbFormCommentCount').value,
params = "commentCount=" + commentCount;
You'll also need to grab and append your _method field, and the csrf token. If they don't have IDs, you can grab them by name:
var method = document.getElementsByName('_method')[0].value,
token = document.getElementsByName('_token')[0].value;
For those interested I was able to submit a form in Laravel without reloading the page. I did this while using AngularJs and so had to put everything in a $(function(){}); like so:
$(function()
{
$('form').on('submit', function(e)
{
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.prop('action'),
method: 'POST',
data: $this.serialize(),
success: function(result)
{
console.log(result);
}
});
});
});
Note: Newer versions of JQuery use "success:" instead of ".done". Hope this helps someone using a newer version.
I have a form with several fields. One of those fields is an input file field where user can upload a JSON file.
My need: When a button is pressed (not to submit form) I need to grab that input file field and pass it to a function executing it, but without submitting the form itself.
<form action=''>
<input type="text" name="abc">
<input type="text" name="cde">
<input type='file' name='import' />
<button class="button" type='submit' name='restore'>
<span class="icon-upload"> </span> Restore
</button>
<input type="submit" value="Submit">
</form>
How can I achieve it?
You can use
var form = document.forms.formName("fileinput"); \\ change the form name and the file input
form.addEventListener('submit', function(ev) {
var
oOutput = document.getElementById("output"),
oData = new FormData(document.forms.formNAme("fileinput"));
oData.append("CustomField", "This is some extra data");\\if you need to...
var oReq = new XMLHttpRequest();
oReq.open("POST", "thepphpfile.php", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Sent!";
} else {
oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>";
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
you need to capture the button click with javascript, preferably jquery, and post it via ajax to a php-script. look up "ajax" on jquery.
include jquery in your file
then change the input and button to somthing like that:
<input type='file' id="myinput" name='import' />
<button class="button" id="ajaxsubmit">restore</button>
after this, add the ajax call (read the sample code from api.jquery.com):
$("#ajaxsubmit").click(function(e){
e.preventDefault();
var formData = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "receiver.php",
data: formData,
cache: false,
contentType: false,
processData: false
});
});
finally set up your php-file receiver.php where you work with your received file data like you would when the form gets submitted.
http://jsfiddle.net/9nfn2Las/
This is my form:
<form id='forma' action="index1.php" method="post">
<input name="name1" type="text">
<input class="s_submit" value="ЗАКАЗАТЬ" type="button" onclick="send1()">
</form>
This is my javascript:
function send1(){
$('#forma').submit(function(event){
var formData = {
'fio' : $('input[name=name1]').val(),
};
$.ajax({
type : 'post',
url : 'index1.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
}
This is my index1.php:
$fio=$_POST['name1'];
$mail_to="_______my_email_________";
$msg="Your name is: $fio
mail($mail_to, $thm, $msg, $headers);
On my e-mail only "Your name is:" message is sent, without the name someone submitted. Code works as expected when I set input type to submit and get rid entirely of send1() function. But input must be the button type and never go to another page on press. I suppose I should get rid of some of variable assignments, but which ones?
Your variable in the POST data is defined in formData object with the key of fio. Your PHP to retrieve it should therefore be:
$fio = $_POST['fio'];
On the form submission, you are overriding the actual form (containing your text field) from being submitted, and submitting your own formData object.
You can quite easily get the data from your HTML form by using
$("#forma").serializeArray()