PHP Not Able To Get POST value passed from AJAX - javascript

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

Related

Email input value come undefined on alert using javascript

I have form which contain email input field
<form id="TypeValidation" action="" method="post" enctype='multipart/form-data'>
<div class="form-group has-label col-sm-6">
<label>
Email
</label>
<input class="form-control" name=email" type="email" required>
</div>
<div class="card-footer text-center">
<button type="submit" name="add_usr_acc" id="add_usr_acc" value="add_usr_acc" class="btn btn-primary" >Add</button>
</div>
</div>
</form>
Issue is that in script code when alert on email then come undefined. how to get value in which user type a email
<script>
$("#TypeValidation").on('submit', (function(e) {
var email = $(this).find('input[name="email"]').val();
alert(email); {
e.preventDefault();
$.ajax({
url: "fn_acc_submit.php?addUsraccID=" + addUsraccID,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType: "html",
beforeSend: function() {
$("#add_usr_acc").prop('disabled', 'disabled')
},
success: function(result) {
alert(result);
location.reload();
if (result == '1') {
location.replace("lst_user_account.php");
} else {
location.replace("add_user_account.php");
}
}
});
}
}));
</script>
Please fix my problem where I am doing wrong.
Problem is in your HTML code at below line:
<input class="form-control" name=email" type="email" required>
Here name=email" is not valid.
Change this to name="email"
In you input field, it should name="email". You forgot to add opening quotes.

Ajax POST file upload in django

I'm trying to process a POST request with a file field via Ajax post in my djano app.
I'm getting this error:
Forbidden (CSRF token missing or incorrect.): /user/instance/create/new/awod/
Here's what I have tried:
From template.html
<div class="container" style="background-color: lightgray; opacity: 0.7;margin-top:10%;margin-left: 2%; padding-bottom: 10%;">
<form method="post" class="form-horizontal" action="" id="gitForm" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="control-label" for="inputGroupSuccess1">Deployment Name:</label>
<div class="input-group">
<span class="input-group-addon">#</span>
<input type="text" class="form-control" name="name" id="inputGroupSuccess1" aria-describedby="inputGroupSuccess1Status">
</div>
</div>
<div class="form-group">
<label class="control-label">Select File</label>
<input type="file" id="inputGroupSuccess2" name="archive" class="file" multiple data-allowed-file-extensions='["zip", "tar"]'>
<small id="fileHelp" class="form-text control-label" style="color:black">Upload a Tar or Zip archive without a Dockerfile, otherwise your deployment will fail.</small>
</div>
<div id="spinner" style="display: none;">
<div class="f_circleG" id="frotateG_01"></div>
<div class="f_circleG" id="frotateG_02"></div>
<div class="f_circleG" id="frotateG_03"></div>
<div class="f_circleG" id="frotateG_04"></div>
<div class="f_circleG" id="frotateG_05"></div>
<div class="f_circleG" id="frotateG_06"></div>
<div class="f_circleG" id="frotateG_07"></div>
<div class="f_circleG" id="frotateG_08"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg pull-right" value="Submit"> Submit </button>
<span style="padding-right: 5%;float: right;"><img src="{% static 'images/go-back-arrow.svg' %}" style="width: 24px; height: 24px;"> Go Back! </span>
</div>
</form>
</div>
</div>
</div>
</div>
my javascript
<script type="text/javascript">
$(document).ajaxStart(function() {
$('#spinner').show();
console.log("ajax start")
});
$(document).ajaxStop(function() {
$('#spinner').hide();
});
$(document).on('submit', '#gitForm', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url : '/user/instance/create/new/awod/',
data: {
name:$('#inputGroupSuccess1').val(),
archive:$('#inputGroupSuccess2').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
},
async: false,
cache: false,
contentType: false,
processData: false,
success:function () {
$('#message').show();
$('#inputGroupSuccess1').val('');
$('#inputGroupSuccess2').val('');
}
})
});
Even when I console.log the csrf_token field, it prints the csrf token properly.
is there something wrong?
Help me, please!
Thanks in advance!
While you can pass the token in the data, the recommended method is to set a custom X-CSRFToken HTTP header:
$.ajax({
type: 'POST',
headers: {'X-CSRFToken': $.cookie('csrftoken')},
url : '/user/instance/create/new/awod/',
data: {
name:$('#inputGroupSuccess1').val(),
archive:$('#inputGroupSuccess2').val()
},
async: false,
cache: false,
contentType: false,
processData: false,
success:function () {
$('#message').show();
$('#inputGroupSuccess1').val('');
$('#inputGroupSuccess2').val('');
}
})
As you can see, the value is the csrftoken cookie (set by Django). I have used the jQuery.cookie library to retrieve the token, but you can retrieve it however you'd prefer.
It is generely a bad idea to use async:false since it'll prevent other events on the page from firing you probably don't want your code to be paused, I'd suggest you to use ajax like this :
$(document).on('submit', '#gitForm', function (e) {
var form_data = new FormData($(this)[0]);
$.ajax({
type:'POST',
url:'/user/instance/create/new/awod/',
processData: false,
contentType: false,
data : form_data,
success: function(response) {
$('#message').show();
$('#inputGroupSuccess1').val('');
$('#inputGroupSuccess2').val('');
}
});
});
this should also resolve your issue with csrf_token.

Add image uploading function inside this existing ajax code

My code here works fine except image uploading. It inserts all data in database .
<input type="file" name="image2" class="file" id="imgInp"/>
But after adding file type input in php it is showing
Notice: Undefined index: image2 in C:\xampp\htdocs\upload\submit.php on line 18
How can I add image uploading function in my existing code.
<div id="form-content">
<form method="post" id="reg-form" enctype="multipart/form-data" autocomplete="off">
<div class="form-group">
<input type="text" class="form-control" name="txt_fname" id="lname" placeholder="First Name" required /></div>
<div class="form-group">
<input type="text" class="form-control" name="txt_lname" id="lname" placeholder="Last Name" required /></div>
<div class="form-group">
<input type="text" class="form-control" name="txt_email" id="lname" placeholder="Your Mail" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="txt_contact" id="lname" placeholder="Contact No" required />
</div>
// here is the problem
<input type="file" name="image2" class="file" id="imgInp"/>
//here is the problem
<hr />
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
// submit form using $.ajax() method
$('#reg-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'submit.php',
type: 'POST',
data: $(this).serialize() // it will serialize the form data
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...'); });
});
</script>
submit.php
<?php
$con = mysqli_connect("localhost","root","","table" ) or die
( "unable to connect to internet");
include ("connect.php");
include ("functions.php");
if( $_POST ){
$fname = $_POST['txt_fname'];
$lname = $_POST['txt_lname'];
$email = $_POST['txt_email'];
$phno = $_POST['txt_contact'];
$post_image2 = $_FILES['image2']['name']; // this line shows error
$image_tmp2 = $_FILES['image2']['tmp_name'];
move_uploaded_file($image_tmp2,"images/$post_image2");
$insert =" insert into comments
(firstname,lastname,email,number,post_image) values('$fname','$lname','$email','$phno','$post_image2' ) ";
$run = mysqli_query($con,$insert);
?>
You can use FormData, also I suggest you can change the elements id of the form, now all of them have ('lname') Try this with your current:
In yout HTML, put an ID to your file input
<input type="file" name="image2" id="name="image2"" class="file" id="imgInp"/>
And change the id of the other input.
In your JavaScript:
var frmData = new FormData();
//for the input
frmData.append('image2', $('#image2')[0].files[0]);
//for all other input
$('#reg-form :input').each(function(){
if($(this).attr('id')!='image2' ){
frmData.append($(this).attr('name'), $(this).val() );
}
});
$.ajax( {
url: 'URLTOPOST',
type: 'POST',
data: frmData,
processData: false,
contentType: false
}).done(function( result ) {
//When done, maybe show success dialog from JSON
}).fail(function( result ) {
//When fail, maybe show an error dialog
}).always(function( result ) {
//always execute, for example hide loading screen
});
In your PHP code you can access the image with $_FILE and the input with $_POST
FormData() works on the modern browsers.If you want for older browser support use malsup/form plugin
Your Form
<form method="post" action="action.php" id="reg-form" enctype="multipart/form-data" autocomplete="off">
Javscript
<script type="text/javascript">
var frm = $('#reg-form');
frm.submit(function (ev) {
var ajaxData = new FormData(frm);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: ajaxData,
contentType: false,
cache: false,
processData:false,
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
In php extract($_POST) to get all input data and $_FILE for files

Submit text-data AND file to php script with jquery

I'm trying to pass the input of an HTML form to a PHP script with jQuery, but all that happens is a refresh of the page. The PHP script called by this form returns a formatted div which contains all the post data. How can I display this data in the page without reloading it?
jQuery
$("form#submissionform").submit(function(){
var formData = new FormData($(this));
$.ajax({
url: 'handlers/upload.php',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data){
$("#submissionform").html(data);
}});
});
HTML
<form id="submissionform" method="post" enctype="multipart/form-data">
<p>Title: <p><br><input style="width:360px" type="text" name="songtitle"><br>
<p>Artist: </p><br><input style="width:360px" type="text" name="artist"><br>
<p>YouTube Link(s): </p><br><input style="width:360px" type="text" name="ytlinks" cols="50"><br>
<p>Other Info </p><br><textarea style="width:100%" name="otherinfo" rows="4" cols="50" placeholder="Bitte alle zusätzlichen Informationen hier eintragen"></textarea><br>
<p>Select file to upload:</p>
<input type="file" name="fileToUpload" id="fileToUpload">
<br><br>
<button>Send Form</button>
</form>
Firstly make an id on your button.If you use submit it will refresh your page.
<button id="btnSubmit">Submit</button>
Then
$("#btnSubmit").click(function(){
var formData = new FormData($(this));//Here I'd like to suggest you send the data using variable .I'm giving one exmple then do like that
<p>Title: <p><br><input style="width:360px" type="text" name="songtitle" id="songtitle"><br>
var songTitle = $("#songtitle").val().trim();
In similar way you can do.
<p>Artist: </p><br><input style="width:360px" type="text" name="artist" id="artist"><br>
var artist = $("#artist").val().trim();
var formData = {
artist : artist,
songTitle : songTitle
}
$.ajax({
url: 'handlers/upload.php',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data){
$("#submissionform").html(data);
}});
});
(...) but all that happens is a refresh of the page. (...)
In order to prevent page refreshing, you have to prevent default form submission. If the <button> inside a form has no type attribute specified or if the attribute is dynamically changed to an empty or invalid value, it's treated as type=submit, which - naturally - will submit the form as a HTTP POST request (reloading page).
The following code should work for you:
index.html:
<html>
<body>
<form id="submissionform" method="post" enctype="multipart/form-data">
<p>Title: <p><br><input style="width:360px" type="text" name="songtitle"><br>
<p>Artist: </p><br><input style="width:360px" type="text" name="artist"><br>
<p>YouTube Link(s): </p><br><input style="width:360px" type="text" name="ytlinks" cols="50"><br>
<p>Other Info </p><br><textarea style="width:100%" name="otherinfo" rows="4" cols="50" placeholder="Bitte alle zusätzlichen Informationen hier eintragen"></textarea><br>
<p>Select file to upload:</p>
<input type="file" name="fileToUpload" id="fileToUpload">
<br><br>
<!-- The button has no "type" attribute specified, so it's treated as type="submit" : -->
<button>Send Form</button>
</form>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$("form#submissionform").submit(function(event){
// prevent default form submission:
event.preventDefault();
var data = new FormData($(this)[0]);
$.ajax({
url: 'handlers/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
});
</script>
</body>
</html>
handlers/upload.php:
<?php
$data = $_POST;
foreach ($data as $key => $value) {
echo $key . " " . $value . "\n";
}
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$res = move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
echo $res;
?>
Note: In my case, I have uploads folder inside handlers folder.
References:
event.pReventDefault()
button type attribute

Image upload after submit using ajax

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

Categories

Resources