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);
}
});
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'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!
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");
});
I am trying to upload image using ajax. But i am getting this error:
Notice: Undefined index: Image in /Applications/MAMP/htdocs/request/insert.php on line 8
Notice: Undefined index: Image in /Applications/MAMP/htdocs/request/insert.php on line 9
After clicked insert button then i am getting that error. The problem is just image section. Other details will still posting. There's something I missed.But I can not find. Anyone can help me here ?
My ajax code is here:
// Insert
$("body").on("click",".insert", function(){
var Desc = $(".Desc").val();
var Title = $(".Title").val();
var Image = $("#Image").val();
var dataString = 'Desc=' + Desc + '&Title=' + Title + '&Image=' + Image ;
$.ajax({
type: "POST",
url:"request/insert.php",
data: dataString,
cache:false,
success: function(html){
// Do something
}
});
});
HTML
<form method="post" action="" id="Form" enctype="multipart/form-data">
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file" name="Image" id="Image">
</div>
</div>
<div class="row">
<div class="row">
<div class="input-field col s12">
<textarea id="textarea1" name="Desc" class="materialize-textarea Desc"></textarea>
<label for="textarea1">Textarea</label>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input name="Title" id="first_name2" type="text" class="validate Title">
<label class="active" for="first_name2">First Name</label>
</div>
</div>
<div class="btn waves-effect waves-light insert" name="action">Submit
<i class="material-icons right">send</i>
</div>
</form>
PHP
<?php
include_once 'functions/db.php';
if(isSet($_POST['Title']) && isSet($_POST['Desc']) && isSet($_POST['Image'])) {
$Title = mysqli_real_escape_string($db, $_POST['Title']);
$Desc = mysqli_real_escape_string($db, $_POST['Desc']);
$Image = $_FILES['Image']['name'];
$image_tmp= $_FILES['Image']['tmp_name'];
move_uploaded_file($sliderPath);
$insert_query = mysqli_query($db,"INSERT INTO Post(Title,Desc,Image) VALUES ('$Title','$Desc','$Image')") or die(mysqli_error($db));
}
?>
You cannot send the image data like the way you are doing now inside jquery , you have to append it inside a FormData(); and then submit it to your url , as the image is multipart data , replace your javascript code with below:
$("body").on("click",".insert", function(){
var data = new FormData();
data.append('Desc',$(".Desc").val());
data.append('Title',$(".Title").val());
var Image = $("#Image").prop("files")[0];;
data.append('Image',Image);
$.ajax({
type: "POST",
url:"request/insert.php",
data: data,
cache:false,
processData:false,
contentType:false,
success: function(html){
// Do something
}
});
});
and inside php it is isset(); not iSset(); and also inside php change :
$_POST['Image']
to :
$_FILES['Image']
Your uploaded file information will be available in the global array $_FILES not $_POST and that is why you were not able to access it. You may access the Image information like this
$imageName = $_FILES['Image']['name']
You should also consider validating user's inputs before saving your data to the database. Rule #1: Never ever trust such data
Try your ajax call like this it will work for sure.
$("#Form").on("submit",function(e){
e.preventDefault();
var dataString = new FormData(this);
$.ajax({
type: "POST",
url:"img1.php",
data: dataString ,
processData: false,
contentType: false,
success: function(html){
console.log(html);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});
i'm trying to display a success /error message when a user login to my website through a hidden div, that is displayed by on click event jQuery. Looks like whatever i try, nothing works. Already searched over and over but can't find a solution. Any help please?
My current code:
$(document).on('submit', '#loginform',function(e){
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'portal/login',
type: 'POST',
dataType:"json",
data:formData,
contentType: false,
processData: false,
success: function(data) {
if(data.status == 1) {
console.log(data.status);
$('.login_result.success').show();
} else {
$('.login_result.error').show();
}
}
});
});
$('.modaltrigger').on('click',function() {
$('#loginmodal').fadeIn(500);
});
So i'm using Ajax to validate the user login, and then at success i want to fadeIn the .login_result
EDIT
My HTML code:
<div id="loginmodal" style="display:none;">
<div id="placeHolder">
<div class="main_logo"><img src="images/logo.jpg"></div>
<form action="portal/login" method="post" class="login" name="loginform" id="loginform">
<input id="user_email" name="user_email" placeholder="Email" type="text">
<input id="user_password" name="user_password" placeholder="Senha" type="password">
<button class="search_button login_button" name="admin_login">Entrar</button>
<span><?php //echo $error; ?></span>
</form>
<div class="login_result success">Login Efetuado com sucesso, Redirecionando!</div>
<div class="login_result error">Login Inválido!</div>
</div>