I want to use event.preventDefault(); but my form still submitts.
and gives me a page with json response. There isn't any error in my console.
Here is my scripts:
$(document).ready(function() {
$('#add_to_cart ').on('submit', function(event) {
event.preventDefault();
var $form = $(event.target);
var data = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: data,
success: function(response, status, xhr) {
var message = response.message;
showToastMessage(message, 'toast-success');
}
}).fail(function(xhr, textStatus) {
var message = "Error.";
if (xhr.responseText) {
var error = JSON.parse(xhr.responseText);
if (error) {
error = error.message;
if (error) {
message = error;
}
}
}
showToastMessage(message, 'toast-error')
});
return false;
});
});
function showToastMessage(message, type) {
var $toastElem = $("#snackbar");
$toastElem.className = "show";
$toastElem.html(message).removeClass('toast-success').removeClass('toast-error').addClass(type).addClass('show');
}
I have seen most of the question about this problom, but I still have problom.
html:
<form action="{{ route('cart.add', $product->id) }}" method="POST" id="add_to_cart">
<a href="javascript:{}" rel="nofollow" data-nid="4165" class="cart-button ripple add-to-cart has-ripple" onclick="parent().submit();";>add</a>
</form>
This is your problem:
<a href="javascript:{}" rel="nofollow" data-nid="4165" class="cart-button ripple add-to-cart has-ripple" onclick="parent().submit();";>add</a>
Submit events are only triggered by the form submission is triggered by standard submission methods (like submit buttons).
Calling the submit() method of the form using JavaScript will bypass the submit event entirely.
Since the event doesn't fire, the event listener function isn't called, so event.preventDefault() is never called.
Use a submit button instead of a link that doesn't go to a useful URL with some JS attached to it.
Related
I am trying to pass data from Javascript code to a Controller but I cant get the variables data in the Controller Code.
I have a view that has a Js file associated that checks when the submit button is clicked and creates some arrays with data to be sent to the server.
I have tried a lot of solutions (commenting the form and defining a attribute to the button with the URL, using the form post action , using $.post in javascript) but i cant seem to get it working.
I have included code to better illustrate what I am trying to do.
Import View code:
<form id="importar" class="form-horizontal" role="form" method="POST" action="{{ url('/importarLista1') }}">
{{ csrf_field() }}
<input type="text" class="form-control" name="startFrom" id="startFrom" value="">
<div class="col-md-4">
<button class="btn btn-primary" id="importar" data-href="{{ url('/importarLista1') }}">
<i class="fa fa-btn fa-sign-in"></i>Importar
</button>
</div>
</form>
JavaScript Code:
var fdata= "startFrom="+ startFrom;
fdata+= "&idList="+ idList;
fdata+= "&nomeCampos="+ nomeCampos;
fdata+= "&posicaoCampos="+ posicaoCampos;
$.ajax({
type:'POST',
url: $( this ).attr( 'data-href' ) /*$( this ).prop( 'action' ) $( this ).attr( 'data-href' )*/,
data:fdata,
dataType:'json',
cache:false,
success:function (data){
alert(data);
}
});
nomeCampos and posicaoCampos are arrays created using javascript and have values assigned to them so they are not empty
JavaScript Code Edit1 Updated code from answer
$('#importar').submit(function() {
if($('#startFrom').val()=='') {
var startFrom = 0;
}else{
var startFrom = $('#startFrom').val();
}
var nomeCampos = new Array();
var posicaoCampos = new Array();
$('tbody tr').each( function(){
$('td', this).each(function(e){
posicaoCampos[e] = $(this).attr('idc');
});
return false;
});
var idList = $('#idList').val();
var fdata= "_token="+ $( this ).find( 'input[name=_token]' ).val();
fdata+= "&startFrom="+ startFrom;
fdata+= "&idList="+ idList;
fdata+= "&nomeCampos="+ nomeCampos;
fdata+= "&posicaoCampos="+ posicaoCampos;
e.preventDefault();
$.post( // short hand for $.ajax({ type:'POST'
$(this).attr('action'), // url, from form
$(this).serialize(), // form data, name and value
function(data) {
// on success...
alert(data);
}
);
}); // end form.submit
Controller Code
protected function importList1(Request $request){
echo $_POST['startFrom'];
exit();
if($request->ajax()) {
$data = Input::all();
print_r($data);die;
}
print_r($request->all());
}
Route
Route::post('/importarLista1','ContactsList\ContactListController#importList1');
Example Solution
This is what my final code looks like
JavaScript
function preparePostData(){
var token = $( '#importar' ).find('input[name=_token]').val();
var startFrom = 0;
var idList = $('#idList').val();
var nomeCampos = new Array(); // not sure where this is getting used?
var posicaoCampos = new Array();
if($('#startFrom').val()=='' || $('#startFrom').val()<=0 ) {
var startFrom = 0;
}else{
var startFrom = $('#startFrom').val()-1;
}
var nomeCampos = new Array();
var posicaoCampos = new Array();
$('thead tr th').each(function(e){
for(var i = 0; i < nomeCampos.length; i++){
if(nomeCampos[i]==$('select', this).val()){
$.Notification.autoHideNotify('error', 'top right', 'STATUS', 'Não pode selecionar Campos Iguais');
exit();
}
}
nomeCampos[e] = $('select', this).val();
});
$('tbody tr').each( function(){
$('td', this).each(function(e){
posicaoCampos[e] = $(this).attr('idc');
});
return false;
});
var file_data=$('input:file')[0].files;
var postdata=new FormData();
postdata.append('_token',token);
postdata.append('startFrom',startFrom);
postdata.append('idList',idList);
postdata.append('nomeCampos',nomeCampos);
postdata.append('posicaoCampos',posicaoCampos);
postdata.append('file',file_data[0]);
return postdata;
}
$('#importar').submit(function(e) {
e.preventDefault();
fdata=preparePostData();
$.ajax({
type:'POST',
url: $(this).prop('action'), // url, from form
data:fdata,
processData: false,
contentType: false,
success:function(data) {
window.location.replace(data.url);
}
});
}); // end form.submit
Controller
if ($request->session()->token() !== $request->get('_token')) {
return Response::json(array(
'status' => 'error',
'msg' => 'Invalid token'
));
}
$idCompany = $request->session()->get('current_company');
$skipValue = $request->get('startFrom');
$idList = $request->get('idList');
$arrayPos = $request->get('posicaoCampos');
$arrayCampos = $request->get('nomeCampos');
And do what you need to do
This is my approach when using forms for ajax in a laravel application, as I'm sure it is for many others...
You have your form:
HTML
<form id="importar" class="form-horizontal" role="form" method="POST" action="{{ url('/importarLista1') }}">
{{ csrf_field() }}
<input type="text" class="form-control" name="startFrom" id="startFrom" value="">
<div class="col-md-4">
<button class="btn btn-primary" id="importar" data-href="{{ url('/importarLista1') }}">
<i class="fa fa-btn fa-sign-in"></i>Importar
</button>
</div>
</form>
if you're submitting all your data from one form, rather than doing this to prep your data:
var fdata= "startFrom="+ startFrom;
fdata+= "&idList="+ idList;
fdata+= "&nomeCampos="+ nomeCampos;
fdata+= "&posicaoCampos="+ posicaoCampos;
You can instead listen for the form submission (You may need to update/add to the form's button to type="submit") and use the serialize() method to grab all the data. (This would of course only work if everything is in one form and it's not clear to me if that is the case for you.)
So you could do something like this:
JS
$('form').submit(function() {
e.preventDefault();
$.post( // short hand for $.ajax({ type:'POST'
$(this).attr('action'), // url, from form
$(this).serialize(), // form data, name and value
function(data) {
// on success...
alert(data);
}
);
}); // end form.submit
PHP/Controller code
protected function importList1(Request $request){
// return the data back as ajax
return response()->ajax([
'data' => $request->all()
]);
}
Hope that helps!
Some extra advice, when getting started with using laravel and ajax together, if on chrome, you want to get the developer tools open. You can of course use firebug in firefox.
Using the developer tools, before hitting submit on your form, check the network tab then hit submit and see what happens. You should see a new post request. You can then click on the post request your form creates in the network tab to inspect what is going on and what comes back.
In short, the developer tools are invaluable for debugging ajax requests, because you will not get any feedback on the screen. You may also want to check out the chrome extension named postman for testing your ajax requests.
Edit
As you're not solely using the form for the data in your post call, serializing the form data won't be sufficient.
I extracted your code to prepare the data for the post call to a separate function to make it more readble and called the function when the form is submitted.
The data is passed to the $.post method as an object rather than a string.
I wrote the code just in my text editor, I didn't test it out. So there may be some mistakes, try and play around with it if you encounter any.
JS
$('#importar').submit(function() {
e.preventDefault(); // stop the form from submitting data
// prep data for ajax post
var postData = preparePostData(); // call function to get data
// perform ajax post
$.post( // short hand for $.ajax({ type:'POST'
$(this).attr('action'), // url, from form
postData, // form data, name and value
function(data) {
// on success...
alert(data);
}
);
}); // end form.submit
function preparePostData() {
var token = $( this ).find('input[name=_token]').val();
var startFrom = 0;
var idList = $('#idList').val();
var nomeCampos = new Array(); // not sure where this is getting used?
var posicaoCampos = new Array();
if ($('#startFrom').val()=='') {
var startFrom = 0;
} else {
var startFrom = $('#startFrom').val();
}
$('tbody tr').each( function(){
$('td', this).each(function(e){
posicaoCampos[e] = $(this).attr('idc');
});
return false;
});
var postData = {
_token: token,
startFrom: startFrom,
idList: idList,
nomeCampos: nomeCampos,
posicaoCampos: posicaoCampos
};
return postData;
}
so I am loading a portion of a page using jquery/ajax.
On the page the user sees, there is a "menu" where they select the date of the signup form they want to see. All the forms are hosted on another page, each one inside a div id'd with the respective date of the form. When the user clicks and item on the menu, there is an ajax call that displays the correct form on the user's page, pulling it from the other page by it's parent div and id.
The plugin I am using for the signup forms (it is a Wordpress site) has the page reload when you click Sign up, which then takes you to a form to fill out. I have it so that the user's page does not reload, but via ajax shows the form. This all works great - the only problem now is when the user clicks to submit the form. This should be a normal form submit not using ajax, as I am not sure how to modify the plugin code to utilize it. For some reason, the form is never actually submitted although the user's page does reload.
*NOTE: I am currently using the same exact signup form for each date, but once it is functional it will be a different signup form for each. This should not effect any functionality.
link to page user sees: summitsharks.net/volunteer-signup-page
link to page forms are hosted on: summitsharks.net/formhost
jquery/ajax code:
;(function($){
var ahref1;
$(document).ready(function(){
$(document).on('click', '.entry-content li a', function(e){
e.preventDefault();
ahref1 = $(this).attr('href');
$('#formloader').load('/formhost ' + ahref1);
return false;
});
});
$(document).ready(function(){
$(document).on('click', '.entry-content #formloader a', function(e){
e.preventDefault();
var ahref2 = $(this).attr('href');
$('#formloader').load(ahref2 + ' ' + ahref1);
return false;
});
});
})(jQuery);
PHP code of file that (I think) handles form submit:
http://pastebin.com/PeXB4Afi
I am looking for a solution that successfully signs the user up. If somebody knows how to alter the plugin code to accept ajax submission, or normal submission that actually works, either one is perfectly fine with me.
Thanks a lot for looking through and thanks in advance for your help!
The form is expected to be posted from it's original URL, including the HTTP GET parameters ?sheet_id=1&task_id=1&date=2016-06-30. Updating the form's action attribute to make it post to the proper URL can be done by changing
$('#formloader').load(ahref2 + ' ' + ahref1);
to
$('#formloader').load(ahref2 + ' ' + ahref1, function() {
$('#formloader form').attr("action", ahref2 + ' ' + ahref1 );
});
However, using AJAX to post the form, this can be skipped:
var ahref = $(this).attr('href') + ' ' + ahref1;
$('#formloader').load( ahref, function() {
$("#formloader form").on('submit', function(e) {
e.preventDefault();
$.ajax( {
url: ahref,
type: 'POST',
data: $.param( formdata( $(this) ) ),
success:function(data,status,jqXHR) { $("#formloader").html( data ) }
});
return false;
})
})
The utility method formdata (see code snippet below) converts jQuery's serializeArray() result to a proper hash.
In the working example below, I've moved the installation of form click handlers into the .load completion handler, rather than relying on jQuery to fire a second document ready event after injecting the form.
;jQuery(function($) {
$('.entry-content li a').off('click').on('click', function(e) {
var ahref1 = $(this).attr('href');
$('#formloader').load( "/formhost " + ahref1, function() {
$('.entry-content #formloader a').off('click').on('click', function(e) {
e.preventDefault();
var ahref = $(this).attr('href') + ' ' + ahref1;
$('#formloader').load( ahref, function() {
$("#formloader form").on('submit', function(e) {
e.preventDefault();
$.ajax( {
url: ahref,
type: 'POST',
data: $.param( formdata( $(this) ) ),
success:function(data,status,jqXHR) { $("#formloader").html( data ) }
});
return false;
})
});
return false;
});
});
return false;
});
});
function formdata(form) {
var data = {};
for ( var i in d = form.serializeArray() )
data[d[i].name] = d[i].value;
return data;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
UPDATE: Here is a code snippet that can be pasted in the browser's Javascript console:
$ = jQuery;
$('.menu-volunteermenu-container li a').off('click').on('click', function (e) {
loadFormSelector($(this).attr('href'));
return false;
});
$('#formloader').on('load', function(){console.log("FORMLOADER UPDATD")});
function loadFormSelector(ahref1)
{
console.log("Loading form selector");
$('#formloader').load('/formhost ' + ahref1, function ()
{
console.log('form selector loaded');
$('.entry-content #formloader a').off('click').on('click', function (e)
{
e.preventDefault();
loadForm(ahref1, $(this).attr('href') );
return false;
});
});
}
function loadForm(ahref1, ahref2)
{
var ahref = ahref2 + ' ' + ahref1;
console.log('Loading form', ahref);
$('#formloader').load(ahref, function () {
console.log('form loaded', arguments);
$('#formloader form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: ahref,
type: 'POST',
data: $.param(formdata($(this))),
success: function (data, status, jqXHR) {
$('#formloader').html( $(data).find( ahref1 ) )
}
});
return false;
});
$('#formloader a').on('click', function () {
loadFormSelector(ahref1);
});
return false;
});
}
function formdata(form) {
var data = {
};
for (var i in d = form.serializeArray())
data[d[i].name] = d[i].value;
return data;
}
It is refactored to show the 2-layer approach more clearly.
.on('success.form.bv', function(e) {
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
console.log(result);
}, 'json');
});
});
If i comment this code, then form submits.PLease tell me the error.This is the form
I have a form validation run when the submit button is selected but i do not want the default submit function to run. Instead i want to run an ajax post code to store the data in the form along with post the data from server side.
I am having trouble finding where to cancel the default submit and add in the ajax code.
Here is the validate code i have
$("#formEnroll").validate({
errorElement:"p",
submitHandler: function(form) {
var phoneNumber = form.day_phone.value;
var phoneParts = phoneNumber.split("-");
form.dayArea.value = phoneParts[0];
form.dayPrefix.value = phoneParts[1];
form.daySuffix.value = phoneParts[2];
form.submit();
}
});
And here is the ajax code i want to run instead of the default submission
$.ajax({
type: "POST",
url: "/php/localProxy.php",
data: $('#formEnroll').serialize(),
success: function (response) {
document.location = 'http://www.xxxx.com/thank-you';
},
error: function () {
alert('There was a problem!'); // handle error
}
});
you can call the the ajax function instead of form.submit();
form.submit(); will submit your code using default submission.
$('#formEnroll').on('submit', function(e){
e.preventDefault();
$(this).validate({
errorElement:"p",
submitHandler: function(form) {
var phoneNumber = form.day_phone.value;
var phoneParts = phoneNumber.split("-");
form.dayArea.value = phoneParts[0];
form.dayPrefix.value = phoneParts[1];
form.daySuffix.value = phoneParts[2];
submitform();
}
});
})
function submitform(){
$.ajax({
type: "POST",
url: "/php/localProxy.php",
data: $('#formEnroll').serialize(),
success: function (response) {
document.location = 'http://www.xxxx.com/thank-you';
},
error: function () {
alert('There was a problem!'); // handle error
}
});
}
You could wrap your validate plugin into a generic form submit function to stop standard execution.
$('#formEnroll').on('submit', function(e)
{
e.preventDefault(); // stop form submission
// Run validation
$(this).validate({
errorElement:"p",
submitHandler: function(form) {
var phoneNumber = form.day_phone.value;
var phoneParts = phoneNumber.split("-");
form.dayArea.value = phoneParts[0];
form.dayPrefix.value = phoneParts[1];
form.daySuffix.value = phoneParts[2];
submitform(); // call your ajax function here
}
});
});
function submitform(){
$.ajax({
type: "POST",
url: "/php/localProxy.php",
data: $('#formEnroll').serialize(),
success: function (response) {
document.location = 'http://www.xxxx.com/thank-you';
},
error: function () {
alert('There was a problem!'); // handle error
}
});
Instead of using the event object e you can also just return false; at the end of the .on function to stop default events from firing.
You can send the data by ajax using the click event in the jquery by clicking the submit button and that function should return false for avoiding the default submission by the way you can send the data using ajax and avoid the default submission.
New to Jquery, even newer to Jquery Ajax calls - here is my problem:
I have a small form - email address submit - that fires to a PHP file which inserts the email into a table.
I want to do the following:
Handle the form submission through Ajax so there is no refresh
After successfully writing to the table I want to change the submit button's text to "Success!" for 3 seconds and then back to
"Sign Up" with fadeIn and fadeOut effects.
Here is my code for the form:
<form action="" id="registerform" name="registerform" method="post" >
<input type="text" id="email" name="email" value="Email Address" onClick="empty()" onBlur="determine()" />
<button id="join" type="submit" name="join" onClick="validate()">Sign Up</button>
</form>
Here is my terrible attempt at handling the POST request through Jquery:
$('form').on('submit', function(e) {
$.post('register.php', function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});
Can anyone comment on how to make the Ajax request work (doesn't seem to be)?
Thanks in advance!
Update
Alright, the following block of Jquery adds the data to the table, however, my button text does not change:
$('form').on('submit', function(e) {
$.post('register.php', $("#registerform").serialize(), function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});
Any ideas now?
Here is an example of one of my ajax calls
details = "sendEmail=true&" + $("form").serialise();
$.ajax({
url: "yourphppage.php",
type: "post",
data: details,
success: function (data, textStatus, jqXHR) {
if (data == "false") {
console.log("There is a problem on the server, please try again later");
} else {
//Do something with what is returned
}
}
})
And on the server side
if (isset($_POST['sendEmail'])) {
//Do something with the data
}
Of course this is only an example, and you may need to alter this to suit your needs :)
One thing to note is what if (data == "false") does. Well on the server side i can echo "false" to tell the ajax call it was not successful.
You're not actually sending any data to the server. You need to use the 'data' parameter of $.post to send your data.
$('form').on('submit', function(e) {
$.post('register.php', $(this).serialize(), function() {
$('#join').html('Success!');
});
//disable default action
e.preventDefault();
});
Not sure, but does the POST request send anything at all? Try adding the data in the POST request.
$('form#registerform').submit(function() {
var email = $(this).find('input[name=email]').val();
$.post('register.php', {email: email}, function() {
$('#join').html('Success!');
});
return false;
});
Where you're pushing your form data to server in ajax call? change code to this.
var data = {$("#email").val()};
$('form').submit(data ,function(e) {
$.post('register.php', function() {
$('#join').html('Success!')
});
//disable default action
e.preventDefault();
});