Image upload after submit using ajax - javascript

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

Related

how to use ajax to perform php background submission in html

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"].

How to process two different ajax placed in different script tag?

I have a page with 3 dropdowns and 1 submit button, on selecting top dropdown value rest auto-populate with ajax.
And after that submit button is used to submit information, for this, I have written ajax in a different script tag.
The problem here is first ajax is working perfect, but second ajax is not working, I know 2 ajax call is not allowed.
I have tried to do this by writing PHP on the same page, but on reloading the page the previously selected information auto submits.
<form style="margin: 10px 50px 10px 50px;" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<div class="row">
<div class="col-md-12">
<div class="form-group">Book Name
<select class="form-control" id="sel_book">
<option value='0'>---Select---</option>
<?php
foreach($result as $key=>$rs):
{
?>
<option value="<?php $key; ?>"> <?php echo $rs[1];?> </option>
<?php
}
endforeach;
?>
</select>
</div>
</div>
</div>
<div class="row" >
<div class="col-md-12" >
<div class="form-group">Member ID
<select class="form-control" id="sel_uid">
</select>
</div>
</div>
</div>
<div class="row" >
<div class="col-md-12" >
<div class="form-group">Member Name
<select class="form-control" id ="sel_uname">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-icon btn-3 btn-primary" id="accept">
<span class="btn-inner--icon"><i class="ni ni-user-run"></i></span>
<span class="btn-inner--text">Accept Return</span>
</button>
</div>
</div>
</form>
<script>
$(document).ready(function(){
$("#sel_book").change(function(){
var bid = $(this).val();
bid = bid+1;
//alert(bid);
$.ajax({
url: 'get_user.php',
type: 'post',
data: {id:bid},
async: false,
dataType: 'json',
success:function(response){
$("#sel_uid").append("<option value='"+response.name+"'>"+response.name+"</option>");
$("#sel_uname").append("<option value='"+response.mname+"'>"+response.mname+"</option>");
}
});
});
});
</script>
<script>
$(document).ready(function(){
$('#accept').click(function(e){
var book = $("#sel_book :selected").text();
var memberId = $("#sel_uid :selected").text();
var memberName = $("#sel_uname :selected").text();
var message = book+'\n'+memberId+'\n'+memberName;
alert(message);
e.preventDefalut();
$.ajax({
type:'post',
url:'accept_return.php',
async: false,
data:{bname:book,memid:memberId,memname:memberName},
dataType:'json',
success:function(response){
$("#final").text("Processing completed sucessfully");
}
});
});
});
</script>
The second script is running properly, but the ajax call to the PHP page is not made.
<script>
$(document).ready(function(){
$("#sel_book").change(function(){
var bid = $(this).val();
bid = bid+1;
//alert(bid);
$.ajax({
url: 'get_user.php',
type: 'post',
data: {id:bid},
async: false,
dataType: 'json',
success:function(response){
$("#sel_uid").append("<option value='"+response.name+"'>"+response.name+"</option>");
$("#sel_uname").append("<option value='"+response.mname+"'>"+response.mname+"</option>");
}
});
});
});
$('#accept').click(function(e){
var book = $("#sel_book :selected").text();
var memberId = $("#sel_uid :selected").text();
var memberName = $("#sel_uname :selected").text();
var message = book+'\n'+memberId+'\n'+memberName;
alert(message);
e.preventDefalut();
$.ajax({
type:'post',
url:'accept_return.php',
async: false,
data:{bname:book,memid:memberId,memname:memberName},
dataType:'json',
success:function(response){
$("#final").text("Processing completed sucessfully");
}
});
});
</script>
Hi you are facing this problem because of two document ready used .First document ready works fine but second ready is not recognized.Please put your click function out of any document ready.Please try using single script as below.May be this helps

Submitting HTML form using Jquery Ajax to check login

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

Dynamic form and send to mysql via jquery and ajax

I have already asked some questions about this, I was helped, but kind of the way they said it only works if the form is normal, with inputs with name "something here" my form only has an input "text" name "table" to put The table number the rest of the form comes via mysql ajax. My question is how can I pass this form to the database since it is dynamic? My code below.
My form
<div class="well">
<!-- left -->
<div id="theproducts" class="col-sm-5">
</div>
<!-- left -->
<form method="post" action="relatorio.php" id="formRel">
<span>Mesa</span>
<input type="text" id="numero_mesa" name="numero_mesa">
<input type="text" id="theinputsum">
<!-- right -->
<div id="thetotal" class="col-sm-7">
<h1 id="total"></h1>
<button type="submit" class="btn btn-lg btn-success btn-block"><i class="fa fa-shopping-cart" aria-hidden="true"></i> Finalizar Pedido</button>
</form>
</div>
<!-- right -->
</div>
And the javascript code.
<script>
$('#formRel').submit(function(event){
event.preventDefault();
var formDados = new FormData($(this)[0]);
$.ajax({
method: "POST",
url: "relatorio.php",
data: $("#formRel").serialize(),
dataType : "html"
})
};
</script>
The insert query is like this.
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
//Criar a conexao
$link = new mysqli ("localhost", "root", "", "restaurant");
if($link->connect_errno){
echo"Nossas falhas local experiência ..";
exit();
}
//echo "<pre>"; print_r($_POST); exit;
$mesa = $_POST['numero_mesa'];
$pedido = $_POST['products'];
$preco = $_POST['products'];
$sql = "INSERT INTO spedido ('pedido','preco','numero_mesa') VALUES ('$mesa','$pedido','$preco')";
$link->query($sql);
?>
enter image description here
<script>
$(document).on('submit', '#formRel', function(event) {
event.preventDefault();
var numero_mesa = $('#numero_mesa').val();
$.ajax({
type: "POST",
url: "relatorio.php?",
data: "numero_mesa="+ numero_mesa+
"&products="+ products,
success: function (data) {
alert(data) // this will send you a message that might help you see whats going on in your php file
});
})
};
</script>

PHP Not Able To Get POST value passed from AJAX

I'm following what this post mentioned to upload a file. A little difference is I added one more text input field on the form. The image file is uploaded to server successfully but it seems the value in input field doesn't get passed to PHP for database update. The database function is fired and database record added but missing the value from the form.
Can anyone point me out what I missed? Thanks.
$.validate({
form: '#frmSlide',
modules: 'file, html5',
validateOnBlur: false,
errorMessagePosition: 'top', // Instead of 'element' which is default
scrollToTopOnError: false, // Set this property to true if you have a long form
onSuccess: function($form) {
var file_data = $('#a_imgfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'slide_upd.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
alert(data);
}
});
}
});
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data" class="form-horizontal" id="frmSlide">
<div class="form-group">
<label class="col-sm-4 control-label" for="imgfile">Image file</label>
<div class="col-sm-8">
<input type="file" id="a_imgfile" data-validation="required mime size" data-validation-allowing="jpg, png, gif" data-validation-ratio="1:1" data-validation-max-size="1M" data-validation-error-msg="An image file is mandatory." />
</div>
</div>
<div class="form-group">
<div class="col-sm-8 col-md-offset-4" id="image-holder">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="seq">Sequence</label>
<div class="col-sm-8">
<input class="form-control server" name="a_seq" id="a_seq" type="number" min="1" max="4" value="" placeholder="Enter display sequence of this slide" data-validation-error-msg="Only 1 to 4 is allowed." />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button name="btnUpd" id="btnUpd" type="submit" class="clsUpd btn btn-primary"><i class="fa fa-floppy-o"></i> Update</button>
</div>
</div>
</form>
<?php
$image_name = $_FILES['file']['name'];
$image_size = $_FILES['file']['size'];
$image_temp = $_FILES['file']['tmp_name'];
move_uploaded_file($image_temp, 'img/'.$image_name);
$seq = $_POST['a_seq'];
addSlide($seq);
?>
function addSlide($seq) {
$seq = (int)$seq;
mysql_query("INSERT INTO slide (seq, lastchgat)
VALUES ('$seq', now())") or die(mysql_error());
}
The a_seq is not appended to the form_data.
add var a_seq = $('#a_seq').val();
form_data.append('a_seq', a_seq);
Should be good to go
I think this will fix your problem
$.validate({
form: '#frmSlide',
modules: 'file, html5',
validateOnBlur: false,
errorMessagePosition: 'top', // Instead of 'element' which is default
scrollToTopOnError: false, // Set this property to true if you have a long form
onSuccess: function($form) {
//var file_data = $('#a_imgfile').prop('files')[0];
//var form_data = new FormData();
//form_data.append('file', file_data);
//------ instead of three lines i just did this and works fine for me -------
var formData=new FormData($('#frmSlide')[0]);
$.ajax({
url: 'slide_upd.php', // point to server-side PHP script
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function(data) {
alert(data);
}
});
}
});

Categories

Resources