I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!
Related
Hi i'm trying to converting my form data to pdf like below.
HTML -> AJAX -> PHP (fpdf)
After click submit button ajax processing & pop message as "localhost say : ok"
if i not full any input name in html , ajax pop say "please fill all fields."
why ajax not able to reach php did i done any thing wrong in php, please help.
Below my code :
html code :
enter code here
<form id="form">
<div class="row">
<div class="col-md-12 form-group container"" >
<center> <b>E-FSR Reporting</b>
<p name="date" id="date"></p>
</center>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group" >
<input type="text" class="form-control" name="name" id="name" placeholder="name" >
</div>
</div>
<div class="row">
<div class="col-12 ">
<td colspan="2" align="center" >
<input type="submit" id="submit" name="submit" value=" Submit E-FSR " class="btn btn-primary rounded-0 py-2 px-4">
</td>
<span class="submitting"></span>
</div>
</div>
ajax code : script.js
$(document).ready(function(){
$("#submit").click(function(){
var name= $("#name").val();
var dataString = 'name='+ name;
if(name=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "pdf.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
php code : pdf.php
enter code here
<?php
if(!empty($_POST['submit']))
{
$name= $_POST['name'];
require("fpdf/fpdf.php");
$pdf = new FPDF();
$pdf->AddPage();
....
Thanks
You are sending you data in a incorrect way:
Your javascript code should be like this:
$(document).ready(function(){
$("#submit").click(function(){
var name= $("#name").val();
if(name=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "pdf.php",
data:{
name:name
},
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
Remark:in php when you fetch data from the $_POST the key should be like how you sent it from ajax.
From example in ajax you are writing
data:{
name:fname,
gender:mygender
}
Then in php it should be $_POST["name"] and $_POST["gender"].
I have following codes as form, and I wanted to check if the form is been successfully submitted.
I was wondering how I can check on the console. I want to check if the form is been successfully submitted so I can display another form.
<form id="signup" data-magellan-target="signup" action="http://app-service-staging.com" class="epic_app-signup" method="POST">
<div class="grid__column " style="width: 100%;">
<input type="text" name="first_name" placeholder="Name" required/>
</div>
<div class="grid__column " style="width: 100%;">
<input type="text" name="password" placeholder="Password" required/>
</div>
<div class="grid__column " style="width: 100%;">
<input type="text" name="confimred-password" placeholder="Confirmed password" />
</div>
<div class="grid__column " style="width: 100%;">
<input type="date" name="startdate" id="startdate" min="2019-12-16">
</div>
</div>
<button type="submit" class="grid__column" style="width: 50%;"></button>
</div>
</div>
</div>
</form>
and the script,
$('.epic_app-signup').on('submit', function(e) {
e.preventDefault();
var formData = $('.epic_app-signup').serializeArray();
var jsonData = {};
formData.forEach(function(item, index) {
jsonData[item.name] = item.value;
});
console.log('data\n', jsonData);
$.ajax({
url: 'http://app-service-staging.com/api/auth/register',
type:'POST',
data: jsonData,
contentType: 'application/json'
}).done(function(data, textStatus, jqXHR) {
if (textStatus === 'success') {
}
});
});
});
you can do this by various ways currently you are not using ajax request if you want to achieve this without ajax let follow these steps
when user click on submit button your form is submitted received form information(you define the path in action attribute where form submitted) after processing successfully redirect toward a new form
second solution use jquery ajax request
//first form
<form action='test.php' id='form_1' method='post'>
<label>Full Name</label>
<input type='text' name='full_name'>
<input type='submit'>
</form>
//second form
<form action='test.php' id='form_2' method='post' style='display:none'>
<label>Father Name</label>
<input type='text' name='father_name'>
<input type='submit'>
</form>
use jquery cdn
<script src='https://code.jquery.com/jquery-git.js'></script>
<script>
$("#form_1").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert("form submitted successfully");
$('#form_1').hide();
$('#form_2').show();
},
error:function(data){
alert("there is an error kindly check it now");
}
});
return false;
});
</script>
My server generates a csrfToken, which is inserted into the following element:
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
The {{_csrfToken}}, is used for templating, but at run time is replaced at the server with the actual token.
<div class="formContainer">
<form class="form-horizontal signupform" role="form" action="/process?form=signupform" method="POST">
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
<div class="form-group">
<label for="fieldName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input type="text" class="form-control"
id="fieldName" name="name">
</div>
</div>
<div class="form-group">
<label for="fieldEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" required id="fieldName" name="email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class="btn btn-default">Register</button>
</div>
</div>
</form>
</div>
{{#section 'jquery'}}
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
{{/section}}
How do I update my jQuery call to include the token ? Right now it is generating errors because the token is not included...
Try this, you did not post anything in fact. I did not test it, if it fails, maybe you should collect data manually.
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
+ var payload = $(this).serializeArray()
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
+ data: payload,
success: function(data){
if(data.success){ $container.html('<h2>Thank you</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
though it looks like it's a duplicate post still as far as answer is concerned this is how you should do check this SO post
and I am writing the code for you here
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer');
var token = $('input[name="_csrf"]').attr('value')
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Csrf-Token', token);
}
});
$.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
I am working with jquery ajax , html form , mysql and php. I have some registered users in the database. What I want to do now with the login form is; When someone click the submit button of the login form, serialize the form and make the isset() method true in the php file so that it can receive the sent data from the form. And check it with the database and return the user information but unfortunately its not working for me. Do any one know whats the problem . For now i have commented out the query from php, just to make clear that the form data is not echoing .
Below is the Form
<form class="login-form" method="post" id="login-form">
<div class="flow-text center-align">LOGIN</div>
<div class="input-field col s12 ">
<i class="material-icons prefix">account_circle</i>
<input id="icon_prefix" name="login_email" type="email" class="validate" required autocomplete="off">
<label for="icon_prefix">Email</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">security</i>
<input id="icon_prefix" name="login_pass" type="password" class="validate" required autocomplete="off">
<label for="icon_prefix">Password</label>
</div>
<div class="input-field col s12">
<button type="submit" name="login_btn" id="lb" class="btn-flat waves-effect waves-blue-grey darken-4 right" > Submit <i class="fa fa-paper-plane"></i> </button>
</div>
</form>
Jquery Ajax, serializing the form
$("#lb").on("click",function(){
$.ajax({
url: "connections.php",
method: "post",
data: $("#login-form").serialize() + "&checkLogin=true",
success: function(r){
console.log(r);
}
});
});
The php file to receive login information
if(isset($_POST["checkLogin"])) {
echo $_POST["login_email"];
echo $_POST["login_pass"];
//$sel_whole_tab = "SELECT * FROM fb_data WHERE user_email='$le' AND user_pass='$lp' ";
//$q = $con -> query($sel_whole_tab);
//if(mysqli_num_rows($q)>0){
// while($s_r = mysqli_fetch_assoc($q)){$curr_arr = $s_r;}
// echo json_encode($curr_arr);
//}
}
First you should prevent form submit on click.
$("#lb").on("click",function(){
$.ajax({
url: "connections.php",
method: "post",
data: $("#login-form").serialize() + "&checkLogin=true",
success: function(r){
console.log(r);
}
});
return false; // this one
});
It works, I see sent ajax request. Check the fiddle https://jsfiddle.net/ishukshin/npdavsz9/
You could try this.
<script type="text/javascript">
$("#lb").on("click", function () {
alert('ok');
$.ajax({
url: "connections.php",
method: "post",
data: $("#login-form").serialize() + "&checkLogin=true",
success: function (r) {
console.log(r);
}
});
});
</script>
Try this,
In your JS
var str = $("#login-form").serializeArray();
$.ajax({
type: "POST",
url: "connections.php,
data: str,
success: function(value) {
console.log(value);
}
});
I want to achieve that the user can search on the website and then filter his search results by clicking on a link (which triggers javascript) so he gets people instead of articles. In terms of database and PHP it works, but when I try to submit this code:
<form id="searchform" class="navbar-form" role="search" method="post" action="/search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="<?php if(isset($searchterm)) { echo $searchterm; } ?>">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
... with this code:
function submit() {
document.getElementById("searchform").submit();
}
this is what I use to communicate with my database initially, the url leads to a PHP function that returns the users. (works)
The following code only gets submitted with HTML button, but not with the link which will submit the form through javascript.
$("#searchform").submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url : "/search/people",
data : form.serialize(),
dataType : "json",
success : function(data){
if(data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});
I get no results in the console when I press the link, BUT with the search bar button (html) I get something in the console.
So what I want to do is with the second link in this code:
<div class="list-group">
sounds
<a id="people" onclick="submit()" href="#" class="list-group-item">people</a>
requests
</div>
I will submit the javascript that part is not working.
Any suggestions on what I can try?
Here's a working example of your code:
https://jsfiddle.net/jonva/x99nxz0h/1/
It seems perfectly fine.
<form id="searchform" class="navbar-form" role="search" method="post" action="/echo/json">
abc
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">Search</button>
</div>
</div>
</form>
$("#searchform").submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "/echo/json",
data: form.serialize(),
dataType: "json",
success: function(data) {
if (data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});