Undefined response while uploading image with ajax - javascript

I have a problem uploading images in AJAX.
When I click on send the image, I get a jquery feedback that tells me "undefined" while the image has been clicked
I have try one other thing who works properly, but creating a really simple form and by giving a class attribute to jquery instead of id.
And that works..
The form who does not works ( i would like it to works :) )
<form action="ajax/uploadimage.php" method="post" enctype="multipart/form-data" >
<div class="card-body">
<!-- Single -->
<div class="dropzone dropzone-single mb-3" data-toggle="dropzone" data-dropzone-url="http://">
<div class="custom-file">
<input id="file-upload" type="file" name="fileToUpload" class="custom-file-input" multiple required>
<label class="custom-file-label" for="file-upload">Choose file</label>
</div>
<div class="dz-preview dz-preview-single">
<div class="dz-preview-cover">
<img class="dz-preview-img" src="..." alt="..." data-dz-thumbnail>
</div>
</div>
</div>
<center><input type="submit" class="btn btn-primary" id="file-submit" value="<?php echo TXT_DASHBOARD_MODIFIER; ?>"></center>
</div>
</form>
The jquery who does not works
<script type="text/javascript">
$(function() {
$('#file-submit').on('click', function() {
var file_data = $('#file-upload').prop('files')[0];
if(file_data != undefined) {
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
type: 'POST',
url: 'ajax/uploadimage.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
if(response == 'success') {
alert('File uploaded successfully.');
} else if(response == 'false') {
alert('Invalid file type.');
} else {
alert('Something went wrong. Please try again.');
}
$('#file-upload').val('');
}
});
}
return false;
});
});
</script>
The form who works :
<form>
<input type="file" name="image" class="image" required>
<input type="submit" name="submit" class="submit" value="Submit">
</form>
The jquery who works :
<script type="text/javascript">
$(function() {
$('.submit').on('click', function() {
var file_data = $('.image').prop('files')[0];
if(file_data != undefined) {
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
type: 'POST',
url: 'ajax/uploadimage.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
if(response == 'success') {
alert('File uploaded successfully.');
} else if(response == 'false') {
alert('Invalid file type.');
} else {
alert('Something went wrong. Please try again.');
}
$('.image').val('');
}
});
}
return false;
});
});
</script>
I would like to solve the undefined error..
Thanks for help :)

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.

serialized form not sending ajax

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!

How do I add my csrf token to my jQuery call?

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>

Codeigniter form validation

I have the following html code below that will upload images from client side to my php apache server.
Backend, I have used the codeigniter form validation. However, after using the code below, user's images cannot be uploaded in to my server. If I comment the form_open(......) code <?php $prevURLPATH=urlencode($prevURL); echo form_open('newPost/createNewPost/'.$userID.'/'.$username.'?prevURL='.$prevURLPATH); ?>, my form actually works(those images get posted successfully), but of course it is done without codeigniter validation.
There,
is it possible to be able to post images and using codeigniter validation at the same time??
<div id="wrapper">
<div class="main-container">
<div class="container">
<?php echo validation_errors("<div style='color:red;'>","</div>"); ?>
<?php $prevURLPATH=urlencode($prevURL); echo form_open('newPost/createNewPost/'.$userID.'/'.$username.'?prevURL='.$prevURLPATH); ?>
<div class="row">
<div class="col-md-9 page-content">
<div class="inner-box category-content">
<div class="row">
<div class="col-sm-12">
<form id="newPost" class="form-horizontal" method="post" enctype="multipart/form-data"
action="<?php echo base_url(); echo MY_PATH;?>newPost/createNewPost/<?php echo $userID.'/'.$username.'?prevURL='.urlencode($prevURL); ?>">
<fieldset>
………….
…………………………………
<div class="form-group row">
<label class="col-md-3 control-label text-center" for="textarea">
<i class="icon-camera-1"></i><abbr title="Min. 1 picture required."><?php echo $Picture;?></abbr><font color="red">*</font></label>
</label>
<div class="col-md-8">
<div class="mb10">
<input id="image" name="images[]" class="file" type="file" accept="image/*" multiple>
<div id="uploadImgError">
</div>
</div>
<p class="help-block">Add up to 5 photos. Use a better image of your product, not catalogs.</p>
</div>
</div>
div class="form-group row">
<label class="col-md-3 control-label text-center"></label>
<div class="col-md-8">
<button id="submit-upload-form" class="btn btn-primary btn-tw" onclick="setup(); return false;"><i class="glyphicon glyphicon-upload"></i>Submit</button>
<button id="validate" hidden="true" type="submit"></button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
The follow is the javascript call that will submit the form:
function setup()
{
var myform = document.getElementById("newPost");
$('#pleaseWaitDialog').modal('show');
setForm(function(data)
{
if(data == true)
{
var formData = new FormData(myform);
for (var i=0; i<fileList.length; i++){
formData.append('filelist[]', fileList[i]);
}
$('#image').fileinput('clear');
$('#image').fileinput('disable');
$('#Adtitle').attr('disabled', 'disabled');
$('#soldqty').attr('disabled', 'disabled');
$('#descriptionTextarea').attr('disabled', 'disabled');
$('#tagsInput').attr('disabled', 'disabled');
$('#submit-upload-form').attr('disabled', 'disabled');
$('#price').attr('disabled', 'disabled');
//console.log (formData.get('image'));
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total*100;
//Do something with upload progress
$("#upload-progress-bar").width(percentComplete+"%");
}
}, false);
return xhr;
},
url: "<?php echo base_url(); echo MY_PATH;?>newPost/createNewPost/<?php echo $userID.'/'.$username.'?prevURL='.urlencode($prevURL); ?>",
data: formData,
processData: false,
contentType: false,
type: 'POST',
success:function(msg){
$("#modal-text").html("Your post has been successfully uploaded.");
setTimeout(function(){
$("#modal-text").html("Your post will be reviewed and go on live within the next 24 hours.");
$('#fwd-btn').css("display", "block");
$('#fwd-btn').css("margin", "auto");
$('#progress-bar').css("display", "none");
}, 2000);
}
});
}
return data;
});
}
});
}
Actually,
I have below jquery javascript function in the submit button that will use URL to do form submit. How to change it??
function setup()
{
var myform = document.getElementById("newPost");
$('#pleaseWaitDialog').modal('show');
setForm(function(data)
{
if(data == true)
{
var formData = new FormData(myform);
for (var i=0; i<fileList.length; i++){
formData.append('filelist[]', fileList[i]);
}
$('#image').fileinput('clear');
$('#image').fileinput('disable');
$('#Adtitle').attr('disabled', 'disabled');
$('#soldqty').attr('disabled', 'disabled');
$('#descriptionTextarea').attr('disabled', 'disabled');
$('#tagsInput').attr('disabled', 'disabled');
$('#submit-upload-form').attr('disabled', 'disabled');
$('#price').attr('disabled', 'disabled');
//console.log (formData.get('image'));
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total*100;
//Do something with upload progress
$("#upload-progress-bar").width(percentComplete+"%");
}
}, false);
return xhr;
},
url: "<?php echo base_url(); echo MY_PATH;?>newPost/createNewPost/<?php echo $userID.'/'.$username.'?prevURL='.urlencode($prevURL); ?>",
data: formData,
processData: false,
contentType: false,
type: 'POST',
success:function(msg){
$("#modal-text").html("Your post has been successfully uploaded.");
setTimeout(function(){
$("#modal-text").html("Your post will be reviewed and go on live within the next 24 hours.");
$('#fwd-btn').css("display", "block");
$('#fwd-btn').css("margin", "auto");
$('#progress-bar').css("display", "none");
}, 2000);
}
});
}
return data;
});
}
});
}
First, you should use form_open_multipart() instead of form_open() but probably it won't be enough.
Form validation is not checking file inputs, I don't know why but I'm sure that. Because of that, you have to control it in your model.
You can use this structure:
if(empty($_FILES))
{
return false;
}
else
{
//some code here
}

My jQuery Ajax not working with PHP

I am trying to post data and receive response using jQuery Ajax Post and I am not sure why my code is not working.
<script>
$(document).ready(function(){
$('#login').click(function(){
$.ajax({
type: 'POST',
url: 'http://code.com/backend/test3',
dataType: 'json',
data: {"username":"akllkkj","password":"kljjkjkl"},
cache: false,
success: function(data){
console.log(data.stack);
console.log(data.key);
},
error:function(){
alert("failure");
}
});
return false;
});
});
</script>
<form autocomplete="off" class="ui fluid form segment" method="post">
<div class="ui fluid form segment">
<div class="two fields">
<div class="field">
<label>Email/Username</label>
<input placeholder="Email/Username" name="username" id="username" type="text">
</div>
<div class="field">
<label>Password</label>
<input placeholder="Password" name="password" id="password" type="password">
</div>
</div>
<input type="button" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
</div>
</form>
And my test3 page contains:
<?php
if(isset($_POST['username']) && isset($_POST['password'])) {
$arr = array(
'stack'=>'overflow',
'key'=>'value'
);
echo json_encode($arr);
}
?>
This has worked for me:
$('#form').submit(function (event) {
event.preventDefault();
var data = $('#form').serialize();
$.ajax({
type: 'post',
dataType: 'json',
data: data
}).done(function (resp) {
console.log(resp);
});
});
And on the php side of things, you may need something like this:
header('Content-Type: application/json');
echo json_encode($arr);
Try this. It will work.
<script type="text/javascript">
$(document).ready(function(){
$('#login').click(function(){
$.ajax({
type: 'POST',
url: 'http://code.com/backend/test3.php',
dataType: 'json',
data: {"username":"akllkkj","password":"kljjkjkl"},
async: true,
success: function(data){
var obj = jQuery.parseJSON(data);
if(obj)
{
for(i=0;i<obj.length;i++) {
console.log(obj[i].stack);
console.log(obj[i].key);
}
} else {
console.log("Empty Result");
}
},
error:function(){
alert("failure");
}
});
});
});
<script>
And you test3.php script will be:
<?php
$arr=array();
if(isset($_POST['username']) && isset($_POST['password'])) {
$arr[] = array(
'stack'=>'overflow',
'key'=>'value'
);
}
echo json_encode($arr);
?>

Categories

Resources