I added to my form a special id which I would like to track. If this id is available in the form, an AJAX request should be initialised.
Form
{!! Form::open(['data-remote', 'action' => 'IncidentsController#store', 'id'=>'incidentEntryForm']) !!}
<div class="form-group">
{!! Form::label('city', 'Name:') !!}
{!! Form::text('city', null, ['class' => 'form-control']) !!}
</div>
(...)
Therefore I wrote this helper script:
Helper Script
(function() {
console.log("Helper OK");
var submitAjaxRequest = function(e) {
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function() {
console.log("Submit OK");
$.publish('form.submitted', form);
}
})
e.preventDefault();
};
// forms marked with the "data-remote" attribute will submit, via AJAX.
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
The $.publish is a short script for PubSub Functionality I included as well.
PubSub
(function($) {
console.log('PubSub OK');
var o = $({});
$.subscribe = function() {
o.on.apply(o, arguments);
};
$.unsubscribe = function() {
o.off.apply(o, arguments);
};
$.publish = function() {
o.trigger.apply(o, arguments);
};
}(jQuery));
But when I press the submit button, the last line of the helper script does not seem to react. The function submitAjaxRequest is never called.
The script is included in my head section. For checking if this is loaded, I included the console.log at the beginning. I see the output. So it is running I think. But it does not react to the submit press in the form.
Update 1
When I try calling submitAjaxRequest() I get the error: Uncaught TypeError: Cannot read property 'preventDefault' of undefined
Update 2
The Form Code that is generated is this:
<form method="POST" action="http://dev.server.com/incidents" accept-charset="UTF-8" data-remote="data-remote" id="incidentEntryForm"><input name="_token" type="hidden" value="<TOKEN>">
<div class="form-group">
<label for="city">Notrufort:</label>
<input class="form-control" name="city" type="text" id="city">
</div>
<!-- Latitude Form Input -->
<div class="form-group">
<label for="street">Straße:</label>
<input class="form-control" name="street" type="text" id="street">
</div>
<!-- Notruftyp Form Input -->
<div class="form-group">
<label for="type">Notruftyp:</label>
<select class="form-control" id="type" name="type"><option value="1">CPR</option></select>
</div>
<!-- Notruf erfassen Form Input -->
<div class="form-group">
<input class="btn btn-primary form-control" type="submit" value="Notruf erfassen">
</div>
</form>
Update 3
I inserted a console.log at the beginning of the closure:
var submitAjaxRequest = function(e) {
console.log("submitAjaxRequest OK");(...)
And the function is being called. The console prints the message. So I think something is wrong with the event.
Update 4
So I tried to use the pubSub System to listen to this event. Therefore I
function reverseGeoCode() {
$.subscribe('form.submitted', function() {
console.log("OK");
})
}
But there is no reaction when I hit the submit button in the console. I used this function in a different script somewhere else on the page. Shouldn't it still react to the publish?
Related
I have been battling with what is wrong on this code since. It so happens that the form is not submitting on this button. The button is of type button and not in the form tag.
$("#step1Btn").click(function () {
var userForm = $("form[name='step1Form']");
if (userForm.valid()) {
userForm.submit(function () {
console.log('submitted o!')
$("#spin1").show();
$("form[name='step1Form'] > span").remove();
$('input[name="emailInput"]').prop('name', "id")
$('input[name="fullNameInput"]').prop('name', "full-name")
$('input[name="phoneInput"]').prop('name', "phone-number")
$.ajax({
type: 'POST',
url: "api/v1/user?" + $(this).serialize(),
success: (result) => {
localStorage.setItem('user', JSON.stringify(result))
localStorage.setItem('authToken', result.authToken);
$("form[name='step1Form'] > span").remove()
$('#step1, #step2').toggle();
$('#step1Title, #step2Title').toggle();
},
error: function (request, exception, errorThrown) {
$("form[name='step1Form'] > span").remove();
$("form[name='step1Form']").prepend('<span class=\'error\'><p>' + request.responseJSON.message + '</p></span>')
},
})
});
} else {
return false;
}
});
Below is the complete form
<div id="step1" class="col-12 col-md-6">
<form name="step1Form">
<div class="home-icon d-flex justify-content-center align-items-center flex-column">
<img src="images/new-icons/user.png" alt="User Registration logo" height="80" />
<p class="my-3">User Registration</p>
</div>
<div class="form-group">
<label for="fullNameInput">Contact full name</label>
<input name="fullNameInput" class="form-control custom-input" placeholder="First name Last name" id="fullNameInput">
</div>
<div class="form-group">
<label for="emailInput">Contact email address</label>
<input name="emailInput" type="email" placeholder="example#email.com" class="form-control custom-input" id="emailInput">
</div>
<div class="form-group">
<label for="confirmEmailInput">Confirm contact email address</label>
<input name="confirmEmailInput" type="email" placeholder="example#email.com" class="form-control custom-input"
id="confirmEmailInput">
</div>
<div class="form-group">
<label for="phone">Contact phone number</label>
<input name="phoneInput" placeholder="08012345678" class="form-control custom-input" id="phone">
</div>
</form>
<button type="button" class="btn red-btn user-btn custom-btn" id="step1Btn">Next<i id="spin1" class="fa fa-spinner fa-spin"></i></button>
</div>
So I would like to see where I went wrong. I am able to log and see output whenever i place a console.log in between the if(userForm.valid) and the userForm.submit().
But as soon as i place it in the userform.submit() I do not get any value back. Like, the form is totally not submitting. I dont know if its because of how I made my Ajax call.. Please Help
You're putting Ajax inside of a submit....
$("#step1Btn").click(function () {
....
if (userForm.valid()) {
userForm.submit(function () {
....
$.ajax({ ....
Which makes no sense since Ajax replaces the actual submit. By doing this you are effectively sending it through validation again; I can't see the .validate() method, but suspect that you are simply using the default option, which would be yet another regular submit... you're probably stuck in a loop going nowhere.
The best place for your Ajax would be inside the submitHandler of the .validate() method.
If your button is outside of the form, you capture the click and manually trigger a submit, which then lets the validation plugin take over the rest.
$("#step1Btn").click(function () { // click of external button
$("form[name='step1Form']").submit(); // trigger validation & submission
});
$("form[name='step1Form']").validate({ // initialize plugin
submitHandler: function(form) { // fires when valid
// YOUR AJAX GOES INSIDE HERE
return false;
},
// other options, rules, etc.
});
Read the documentation for the submitHandler.
Form :
<form method="post" id="loginForm">
<div class="form-group">
<label for="email-signin">Email address:</label>
<input type="email" class="form-control" id="email-signin" name="email-signin">
</div>
<div class="form-group">
<label for="pwd-signin">Password:</label>
<input type="password" class="form-control" id="pwd-signin" name="pwd-signin">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" id="signIn" name="signIn">Sign In</button>
<div id="error">
<!-- error will be shown here ! -->
</div>
</form>
jquery :
$("#signIn").on("click", function(e) {
e.preventDefault();
var values = $("#loginForm").serialize();
console.log( values );
$.ajax({
type: "POST",
url: "../php/BusinessLayer/User.php",
data: values,
beforeSend: function() { $("#error").fadeOut() },
success : function(response)
{
console.log("Success");
if(response=="ok"){
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
});
}
}
});
php:
<?php
session_start();
include ("../DataLayer/VO/UserVO.php");
include ("../DataLayer/DAO/UserDAO.php");
// Database Execution for User Related Request
$userDAO = new UserDAO();
print_r($_POST);
if(isset($_POST['signIn']))
{
echo 'test2';
$user = new UserVO();
$user->setEmail(trim($_POST['email-signin']));
$user->setPassword(trim($_POST['pwd-signin']));
// Request signin
$userDAO->signIn($user);
}
Using this code, my if(isset($_REQUEST['signIn'])) in my php file never returns true. I have tried multiple things, and nothing seems to work.
PS : I am using Jquery 1.12.4
Also, my print_r($_POST); returns an empty Array.
jQuery's serialize function does not encode the values of buttons. Taken from here
NOTE: This answer was originally posted by slashingweapon
jQuery's serialize() is pretty explicit about NOT encoding buttons or submit inputs, because they aren't considered to be "successful controls". This is because the serialize() method has no way of knowing what button (if any!) was clicked.
I managed to get around the problem by catching the button click, serializing the form, and then tacking on the encoded name and value of the clicked button to the result.
$("button.positive").click(function (evt) {
evt.preventDefault();
var button = $(evt.target);
var result = button.parents('form').serialize()
+ '&'
+ encodeURIComponent(button.attr('name'))
+ '='
+ encodeURIComponent(button.attr('value'))
;
console.log(result);
});
As far as the var dump being empty on the PHP side, try using jQuery's .click instead of the .on event.
$('#signIn').click(function(){});
Also, remove the method from your form. It looks like the form may be submitting as soon as you click the button. Also, remove
e.preventDefault();
and place
return false;
at the VERY END of the on click function. return false does 3 things
e.preventDefault()
e.stopPropigation();
return immdediatly
Hello I have a form with some data what I want is when I click a button a jQuery function executes and print all that data in the console so here is my form code:
<form>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="fecha">Fecha:</label>
<input type="text" name="fecha" id="fecha" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="total">Total:</label>
<input type="number" min="0" name="total" id="total" class="form-control">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="abono">Abono:</label>
<input type="number" min="0" name="abono" id="abono" class="form-control">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="resta">Restante:</label>
<input type="text" name="resta" id="resta" class="form-control" readonly>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-5">
<button type="submit" value="actualizar" class="btn btn-info" id="actualizar">Actualizar Datos
<span class="glyphicon glyphicon-refresh"></span>
</button>
</div>
</div>
</form>
and this is my script include
<script src="js/jquery-1.12.2.min.js"></script>
<script type="text/javascript" src="js/actualizar_orden.js"></script>
this is actualizar_orden.js file:
//Al clickear boton actualizar ordenes
$('#actualizar').click(function(){
var orden = parseInt($('#norden').val());
var id_tecnico = parseInt($('#id_tec').val());
var memoria = $('#memoria').val();
var chip = $('#chip').val();
var tapa = $('#tapa').val();
var falla = $('#falla').val();
var observacion = $('#observacion').val();
var estado = $('#estado').val();
var fecha = $('#fecha').val();
var total = parseInt($('#total').val());
var abono = parseInt($('#abono').val());
var ajaxUrl = 'actualizar_ordenes.php';
data = { 'norden': orden, 'id_tec': id_tecnico, 'memoria': memoria, 'chip': chip, 'tapa': tapa,
'falla': falla, 'observacion': observacion, 'estado': estado, 'fecha': fecha,
'total': total, 'abono': abono };
console.log(data);
/*$.post(ajaxUrl, data, function(response){
if(response.empty)
alert("Datos no actualizados");
else{
alert("Datos Actualizados.");
location.reload();
}
}) */
});
I just want to log that data into console to check if I'm getting it right.. but instead of log that to console my page is refreshing automatically so I can't see the output in the console... I've tried with both mozilla and chrome but still nothing
I see You want to submit form using jquery, without refreshing screen.
simply do following in Your js file:
$(function() {
$('form.ajax').submit(function(e) { // catch submit event on form with ajax class
e.preventDefault(); // prevent form act as default (stop default form sending)
var $form = $(this); // caching form object to variable
var data = $form.serializeArray(); // getting all inputs from current form and serializing to variable
var url = $form.attr('action'); // reading forms action attribute
console.log('DATA:', data);
$.post(url, data, function(response) { // posting form data to url (action)
console.log('RESPONSE:', response);
if(response.empty) {
alert("Datos no actualizados");
return;
}
alert("Datos Actualizados.");
$form.find('input, select').val(''); // resets form inputs
});
});
});
and change Your form tag to be like this:
<form class="ajax" action="actualizar_ordenes.php" method="post">
this example shows You that:
1) You can catch all form submits that has ajax class defined
2) no need to set exact url in js code (before it was hardcoded ajaxUrl variable). now it gets form action url from form attributes.
3) it does ajax post and if success, so You can redefine some wise behavior to make really flexible solution, and forget about writing custom code for each form submitting
isn't it flexible? (:
Everyform need some default action to do on submitting. When it's not set it reloads the page by default. So to prevent the refreshing, you should add some empty action to your <form> tag, like this:
<form action="javascript:void(0);">
I am trying to save an HTML field (for later use in a form) from a JS script.
This is the code:
Form
<form class="new_client" id="new_client" action="/clients" accept-charset="UTF-8" method="post">
<div class="form-group">
<input class="form-input" type="hidden" name="client[city]" id="client_city">
</div>
<div class="form-group">
<input class="form-input" type="hidden" name="client[address]" id="client_address">
</div>
<div id="locationField">
<input autocomplete="off" class="autocomplete" placeholder="Enter your address" type="text">
</div>
<div class="text-center">
<button class="btn button-general ">Save</button>
</div>
</form>
And the javascript:
function configureGeoAutocomplete(context) {
if( context === undefined ) {
context = $('body');
}
var element = context.find('.autocomplete')
//It doesn't really matter what this line does, it's from Google Places API
var autocomplete = new google.maps.places.Autocomplete(
element[0], {types: ['geocode']});
autocomplete.addListener('place_changed', fillInAddress)
}
function fillInAddress() {
var client_address = autocomplete.getPlace().formatted_address;
document.getElementById("client_address").value = client_address;
}
The javascript is queried when loading the modal in which the form is
jQuery(function() {
$('div.modal').on('loaded.bs.modal', function(e) {
configureGeoAutocomplete(context);
}
}
I wanna save that client_address to the text field so when the form is submitted I can have that information.
Sounds like an excellent candidate for cookies if you are allowed to use them: http://www.w3schools.com/js/js_cookies.asp. Another idea is to pass it along in a Query String. It isn't PII or anything like that. Try an event code on that input. I do not like to hit "enter"!
onkeypress="if (event.keycode==13) { // do something }"
Handle the form submit event:
$(function() {
$("#new_client").submit(function(e) {
e.preventDefault();
// This is your value stored in the field.
$("#client_address").val();
});
})
Apparently, for some reason, if I searched the element by ID it was not saving the information on the field. If I istead search by class:
function fillInAddress() {
var place = autocomplete.getPlace();
$(".client-address").val(place.formatted_address);
}
It works as intended.
This is my code so far:
$(function () {
$('.contact-form').submit(function (event) {
$(this).find("input , textarea").each(function () {
var input = $(this);
if (input.val() == "") {
event.preventDefault();
$("label, p").addClass("error");
input.addClass("error").one("keydown", function () {
$("label").removeClass("error");
self.removeClass("error");
});
}
});
});
});
What it does:
It prevents the form from redirecting to the php script, it turns all fields red (the error class) if they are not filled, and gives the labels an error class.
What I need help with:
Fix so if one field is getting filled remove the error class as it doesn't right now.
Fix so that the label error class gets removed on the specific field when filled (right now it removes the class on all labels over all fields)
And run this code when every field / textarea is validated to be filled:
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function () {
// Optionally alert the user of success here...
console.log("jag lyckades!");
}).fail(function () {
// Optionally alert the user of an error here...
console.log("jag lyckades INTE");
});
event.preventDefault(); // Prevent the form from submitting via the browser.
My html:
<form class="contact-form" action="<?= path(" postform.php "); ?>" method="post" validate>
<div class="row">
<div class="col-sm-6">
<label for="firstname">Förnamn*</label>
<input type="text" class="required" name="firstname" />
</div>
<div class="col-sm-6">
<label for="lastname">Efternamn</label>
<input type="text" name="lastname" />
</div>
</div>
<div class="row">
<div class="col-sm-6">
<label for="email">E-post*</label>
<input type="text" name="email" />
</div>
<div class="col-sm-6">
<label for="number">Telefon*</label>
<input type="text" name="number" />
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label for="message">Meddelande*</label>
<textarea name="message"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>Fält markerade med * är obligatoriska</p>
<input class="btn-form" type="submit" value="Skicka">
</div>
</div>
</form>
Thanks... I really appreciate your time guys
EDIT:
This is my code at the moment:
http://jsfiddle.net/dmyhd90d/
My problems now:
Having the ajax call run when there's no more form errors ( it runs even if none is filled now )
The label error class is getting the error class removed now instantly when you fill the fields, but the fields stay error classed till I hit the send button, then it revalidates.
Lets post it all in one place because comments are not the place for this anymore
First:
with form submissions, you can often let the error field just clear when you re-validate so by adding
$('.contact-form').submit(function (event) {
$('.error').removeClass("error"); // This
you can clear the errors out and re-validate the whole form from scratch.
second, you're trying to bind an event so that when you edit the input it clear the error from that input and it's label but right now you're clearing all labels errors so you can change it like this
if (input.val() == "") {
event.preventDefault();
$("label, p").addClass("error");
input.addClass("error").one("keydown", function () {
// $("label").removeClass("error");
$("label[for='" + $(this).attr('name') + "']").removeClass("error"); // becomes this
self.removeClass("error");
});
}
To associate the input you're looking at, with it's label. BTW just so you know it's good to put input id="something" and label for="something" as that'll link the label to the input in html, when you click the label. Remember to keep your names for submitting though.
Additionally I think that
$("label, p").addClass("error");
will add an error to all your labels at once. You might want to change it also to add errors only to the fields that have errors
$("label[for='" + $(this).attr('name') + "'], p").addClass("error");
Edit to answer the comment
$('.contact-form').submit(function (event) {
$('.error').removeClass("error"); // This
$(this).find("input , textarea").each(function () {
var input = $(this);
if (input.val() == "") {
event.preventDefault();
$("label[for='" + $(this).attr('name') + "'], p").addClass("error");
input.addClass("error").one("keydown", function () {
$("label[for='" + $(this).attr('name') + "']").removeClass("error");
self.removeClass("error");
});
}
});
if ($(".errors").length <= 0) { // If there are no more error classes
// Do $.ajax() here
// http://api.jquery.com/jquery.ajax/ <- you need to read this and other similar SO posts about ajax
}
});