php $POST[] empty after Ajax call from jquery - javascript

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

Related

why is this not printing to console

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);">

jquery (ajax) click makes php script to run multiple times

I'm having a button, and when is clicked, it renders (with the help of ajax), the content of a php script (basically it's a contact form). My problem is that when the button is clicked, this calls the php script twice or more times. I've tried many solutions, but none worked.
HTML
<ul class="nav navbar-nav navbar-right">
<li>CONTACT</li>
</ul>
JavaScript
$(document).ready(function(){
$('#contact').off();
// the above line I've replaced it with:
// 1. $('#contact').off('click');
// 2. $('#contact').unbind();
// 3. $('#contact').unbind('click');
$('#contact').click(function(e){
$.ajax({
type: "POST",
url: "contact.php",
success: function(html){
$('#content').html(html);
}
});
e.preventDefault();
});
});
The response I get when I run the page which contains the HTML and JS:
The contact.php receives the data send with ajax (from index.php - the page which contains the above code), and then sends the new contact to another php script (which is a class), who stores the new contact in the database, and gives back (to contact.php) a response.
contact.php
<form id="form">
<div class="form-group col-xs-12 col-md-4">
<input type="text" class="form-control" id="nume" value="<?php echo Escape::esc($nume);?>" style="pointer-events:none;background:#EFEFEF;"/>
</div>
<div class="col-xs-12"></div>
<div class="form-group col-xs-12 col-md-4">
<input type="text" class="form-control" id="prenume" value="<?php echo Escape::esc($prenume);?>" style="pointer-events:none;background:#EFEFEF;"/>
</div>
<div class="col-xs-12"></div>
<div class="form-group col-xs-12 col-md-10">
<textarea class="form-control" id="mesaj" rows="20" data-toggle="mesaj" data-placement="bottom" title="Va rog introduceti mesajul dvs."></textarea>
</div>
<div class="col-xs-12"></div>
<div style="clear:both"></div>
<button class="btn btn-default" onclick="return validate();" style="margin-left:15px;">TRIMITE</button>
</form>
<script type="text/javascript">
function validate(){
var nume = $('#nume').val();
var prenume = $('#prenume').val();
var mesaj = $('#mesaj').val().trim();
if (mesaj == '' || mesaj.length < 3){
$(function(){
$('[data-toggle="mesaj"]').tooltip();
document.getElementById('mesaj').focus();
});
return false;
}
$('#form').off();// here I tried to unbind all the previous submit events too
$('#form').on('submit',function(e){
$.ajax({
type: "POST",
url: "../../app/classes/Contact.php",
data: {nume:nume, prenume:prenume, mesaj:mesaj},
success: function(html){
$('#content').html(html);
}
});
e.preventDefault();
});
}
</script>
Any tip is welcomed! Thank you!
From what I understand, JavaScript does not execute functions sequentially by nature. In your first jQuery snippet it looks like your code assumes that it will first unbind any events bound to $('#contact') and then create a new binding, but that's not necessarily true.
Also, the off() command only works if you bound the event to the element using a corresponding on() command, but your code uses click() instead of on().
You may want to try something like this instead:
$(document).ready(function(){
$('#contact').on('click', function(e){
$.ajax({
type: "POST",
url: "contact.php",
success: function(html){
$('#content').html(html);
}
});
e.preventDefault();
});
});
Using $('#contact').on('click', function(e) ... will allow you to call $('#contact').off() after the e.preventDefault(); if you want to try to use that to troubleshoot the double-posting problem.
I'm not sure that will fix your issue, but hopefully it's a step in the right direction.

AJAX Request when submitting form

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?

javascript ajax post form function and validation

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
}
});

Submit 2 forms with 1 button, form1 after form 2 is complete

I have the following problem:
2 forms that need to be submitted with one button. I will explain how it should work.
And of course my code so far.
#frmOne contains a url field where I need to copy the data from to my #frmTwo, this works.
(it forces the visitor to use www. and not http:// etc)
When I press 1 submit button
Verify fields #frmOne (only url works now, help needed on the others)
Call #frmTwo and show result in iframe. result shows progress bar (works)
But Div, modal or any other solution besides iframe are welcome.
Close #frmOne (does not work)
Finally process (submit) #frmOne if #frmTwo is done (does not work)
Process completed code of #frmTwo in iframe =
<div style='width' id='information'>Process completed</div>
<ol class="forms">
<iframe width="100%" height="50" name="formprogress" frameborder="0" scrolling="no" allowtransparency="true"></iframe>
<div id="txtMessage"></div>
</ol>
<div id="hide-on-submit">
<form id="frmOne" method="post">
<input type="text" name="company" id="company" >
<input type="text" name="url" id="url" >
<input type="text" name="phone" id="phone" >
<input type="text" name="occupation" id="occupation" >
<textarea rows="20" cols="30" name="summary" id="summary" >
<button type="submit" class="btn btn-danger">Submit</button>
</form>
</div>
<form id="frmTwo" method="post" target="formprogress"></form>
<script>
jQuery(document).ready(function(){
//Cache variables
var $frmOne = $('#frmOne'),
$frmTwo = $('#frmTwo'),
$txtMessage = $('#txtMessage'),
frmTwoAction = 'http://www.mydomainname.com/form.php?url=';
//Form 1 sumbit event
$frmOne.on('submit', function(event){
event.preventDefault();
var strUrl = $frmOne.find('#url').val();
//validation
if(strUrl === ''){
$txtMessage.html('<b>Missing Information: </b> Please enter a URL.');
}
else if(strUrl.substring(0,7) === 'http://'){
//Clear field
$frmOne.find('#url').val('');
$txtMessage.html('<b>http://</b> is not supported!');
}
else if(strUrl.substring(0,4) !== 'www.'){
//Clear field
$frmOne.find('#url').val('');
$txtMessage.html('<b>Invalid URL</b> Please enter a valid URL!');
}
else{
//set form action and submit form
$frmTwo.attr('action', frmTwoAction + strUrl).submit();
$('#hide-on-submit').hide(0).fadeIn(1000);
$('form#frmOne').submit(function(e) {
$(this).hide(1000);
return true; // let form one submit now!
}
return false;
});
});
</script>
read here https://api.jquery.com/jQuery.ajax/. basically you need to submit the first one with $.ajax and then, when you get the server response (in the success() function ) you need to send the second form, again width ajax().
Something like:
$form1.on('submit', function(e) {
e.preventDefault(); //don't send the form yet
$.ajax(
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize()
).success(function(data) {
alert('form one sent');
$.ajax(
url: $('#form2').attr('action'),
type: $('#form2').attr('method'),
data: $('#form2').serialize()
).success(function(data) {
alert('form two sent');
})
});
});
This code isn't ready to be copy/pasted, it's just to give you a guideline of how I would solve it. It's a big question, try going with this solution and come back with smaller question if you find yourself blocked.

Categories