Problems to send image from Ajax, FormData and receive with PHP - php

Help, try upload a image from a form with js, using Ajax,FormData
MODAL FORM,
FORM USED TO COLLECT THE INFORMATION AND THE IMAGE
<div id="modal-editar" style="display: none">
<form id="pais-editar" >
<div class="Listar-table">
<div class="Listar-table-dato">
<span class="">Nombre Empresa</span>
</div>
<div class="Listar-table-dato">
<span class="Forms-table">
<input type="text" name="conf[pais]" id="pais-ed" required="">
</span>
</div>
</div>
<div class="Listar-table">
<div class="Listar-table-dato">
<span class="">MONEDA (Abreviatura)</span>
</div>
<div class="Listar-table-dato">
<span class="Forms-table">
<input type="text" name="conf[moneda]" id="moneda-ed" required="">
</span>
</div>
</div>
<div class="Listar-table">
<div class="Listar-table-dato">
<span class="">Bandera</span>
</div>
<div class="Listar-table-dato">
<span class="Forms-table">
<input type="file" name="bandera" accept="image/x-png,image/gif,image/jpeg" />
</span>
</div>
</div>
<div id="mensaje-editar">
</div>
<div class="Contendedor-filtro-der Contener-btn" style="text-align: center;">
<input type="submit" class="Btn-naranja-auto" name="" value="Guardar Pais">
</div>
</form>
</div>
JS FUNCTION, THIS TAKES THE INFORMATION FROM THE FORM AND SEND IT USING AJAX
$('body').on('submit', '#pais-editar', function(e) {
e.preventDefault();
$('#modal-editar').iziModal('startLoading');
var data = new FormData();
$.each($('#bandera'), function(i, obj) {
$.each(obj.files, function(j, file) {
data.append('bandera', file);
});
});
otradata = $('#pais-editar').serializeArray();
$.each(otradata, function(key, input) {
data.append(input.name, input.value);
});
data.append('conf[id]', pais_id);
data.append('conf[opc]', 'pais-editar');
$.ajax({
url: 'libs/ac_configuracion',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
dataType: 'json',
success: function(data) {
$('#modal-editar').iziModal('stopLoading');
if (data.status == true) {
$('#modal-editar').iziModal('resetContent');
iziToast.success({
title: 'Correcto',
message: data.msg,
position: 'center',
overlay: true,
displayMode: 1,
target: '#mensaje-editar',
pauseOnHover: false
});
lista_paises(1);
} else {
iziToast.error({
title: 'Error',
message: data.msg,
position: 'center',
overlay: true,
displayMode: 1,
target: '#mensaje-editar',
pauseOnHover: false
});
}
}
});
});
and finally this is my php code that receives the data, uploads the image and edits the information
$codigo = explode('-', $data['id']);
#$nombre_adjunto = $_FILES['bandera']['name'];
#$tmp_adjunto = $_FILES['bandera']['tmp_name'];
$folder_gastos = '../banderas';
$trozo1=explode(".", $nombre_adjunto);
$nombre_archivo= 'bandera_'.($data['pais']).'.'.end($trozo1);
#$target_path = $folder_gastos.'/'.$nombre_archivo; //Indicamos la ruta de destino, así como el nombre del archivo
move_uploaded_file($tmp_adjunto, $target_path);
$dats = ['nombre_pa' => $data['pais'], 'moneda_pa' => $data['moneda'] , 'bandera' => $nombre_archivo];
$nuevo = $db
->where('Id_pa', $codigo[1])
->update('paises', $dats);
if ($nuevo) {
$msg['status'] = true;
$msg['msg'] = 'País Editado';
} else {
$msg['status'] = false;
$msg['msg'] = 'No se ha podido editar el país';
}
echo json_encode($msg);
it's supposed to work, the text information arrives but the image does not

Related

Undefined index when trying to upload image ( with jquery validate and steps )

I'm using form steps with jquery steps and jquery validate. But when i try to upload image, it show "Undefined Index: picture". When i try without both of jquery, it works.
register.php
<form class="form-contact contact_form" id="register" enctype="multipart/form-data">
<input name="remarks" id="remarks" type="hidden" value="SMP">
<div class="row">
<h3> Profil </h3>
<section>
<div class="col-md-3">
<p class="katapen">NISN</p>
</div>
<div class="col-md-9">
<input class="form-control required number" name="nisn" id="nisn" type="text" placeholder='Please enter your NISN'>
</div>
<div class="col-md-3">
<p class="katapen">School Status</p>
</div>
<div class="col-md-4">
<div class="switch-wrap d-flex justify-content-between">
<div class="primary-radio">
<input type="radio" name="schoolstatus" value="A" id="primary-radio" required>
<label for="primary-radio"></label>
</div>
<p class="spasidrradio">A</p>
</div>
</div>
<div class="col-md-4">
<div class="switch-wrap d-flex justify-content-between">
<div class="primary-radio">
<input type="radio" name="schoolstatus" value="B" id="primary-radio">
<label for="primary-radio"></label>
</div>
<p class="spasidrradio">B</p>
</div>
</div>
</section>
<h3> Personal Data </h3>
<section>
<div class="col-md-3">
<p class="katapen">Full Name</p>
</div>
<div class="col-md-9">
<input class="form-control required" name="fullname" id="fullname" type="text" placeholder='Please enter your fullname' required>
<div class="col-md-3">
<p class="katapen">Picture</p>
</div>
<div class="col-md-9">
<input class="form-control" name="picture" id="picture" type="file">
</div>
</section>
test.js
var former = $("#register");
former.validate
({
errorPlacement: function errorPlacement(error, element)
{
element.before(error);
},
rules:
{
}
});
former.children("div").steps
({
headerTag: "h3",
bodyTag: "section",
transitionEffect: "slideLeft",
onStepChanging: function (event, currentIndex, newIndex)
{
former.validate().settings.ignore = ":disabled,:hidden";
return former.valid();
},
onFinishing: function (event, currentIndex)
{
former.validate().settings.ignore = ":disabled";
return former.valid();
},
onFinished: function (event, currentIndex)
{
studentregister();
}
});
function studentregister()
{
var remarks = document.getElementById('remarks');
$.ajax
({
type: "POST",
url : base_url + "register/" + remarks.value,
data: $('#register').serialize(),
dataType: 'json',
success: function(data)
{
if(data.log.status == '1')
{
swal
({
title: "",
type: "success",
text: data.log.ket,
confirmButtonClass: "btn-success",
confirmButtonText: "Con"
},function(){
});
}else{
swal
({
title: "",
type: "error",
text: data.log.ket,
confirmButtonClass: "btn-default",
confirmButtonText: "Back"
},function(){
});
}
$("#register")[0].reset();
},
error: function(ts)
{
alert(ts.responseText);
}
});
return false;
};
base_url + "register/" + remarks.value will be route to saveregister and remarks.value as uri2
This is my adm.php
public function saveregister()
{
$uri1 = $this->uri->segment(1);
$uri2 = $this->uri->segment(2);
$uri3 = $this->uri->segment(3);
$uri4 = $this->uri->segment(4);
//var post from json
$p = json_decode(file_get_contents('php://input'));
$_log = array();
if($uri2 == "SD")
{
}else if($uri2 == "SMP"){
$p = $this->input->post();
$folder = "./upload/register/";
$allowed_type = array("image/jpeg", "image/jpg", "image/png", "image/gif",
"audio/mpeg", "audio/mpg", "audio/mpeg3", "audio/mp3", "audio/x-wav", "audio/wave", "audio/wav","video/mp4", "application/octet-stream", "application/pdf", "application/doc");
$file_name = $_FILES['picture']['name'];
$file_type = $_FILES['picture']['type'];
$file_tmp = $_FILES['picture']['tmp_name'];
$file_error = $_FILES['picture']['error'];
$file_size = $_FILES['picture']['size'];
$ekstensi = explode("/", $file_type);
$time = date("Yhsms");
$filename= $this->db->escape($p['nisn'])."_".$time .".".$ekstensi[1];
#move_uploaded_file($file_tmp, $folder .$filename);
}else{
}
}
If you look at the jquery serialize() Documentation, it says the data from file select elements is not serialized. You could use FormData to send file input through ajax :
function studentregister()
{
var remarks = document.getElementById('remarks');
var form = $("#register")[0]; // use the form ID
var formData = new FormData(form);
$.ajax
({
type: "POST",
url : base_url + "register/" + remarks.value,
data: formData,
dataType: 'json',
contentType: false, // required
processData: false, // required
success: function(data)
{
if(data.log.status == '1')
{
swal
({
title: "",
type: "success",
text: data.log.ket,
confirmButtonClass: "btn-success",
confirmButtonText: "Con"
},function(){
});
}else{
swal
({
title: "",
type: "error",
text: data.log.ket,
confirmButtonClass: "btn-default",
confirmButtonText: "Back"
},function(){
});
}
$("#register")[0].reset();
},
error: function(ts)
{
alert(ts.responseText);
}
});
return false;
};

File upload not submitting through ajax

I created a form upload which contains some inputs but when I submitted the form to ajax, ajax was unable to grap the file name.
I keep on getting Notice: Undefined index: userImage in C:\wamp\www\osun\i_admin\php_action\uploadImage.php on line 14 . userImage is the name of the file
index.php
<?php include('header.php'); ?>
<?php include('top.php'); ?>
<?php include('links.php'); ?>
<section class="content">
<div class="container-fluid">
<div class="block-header">
<h2>Worker of the Month</h2>
</div>
<!-- Basic -->
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div id="error" class="closeit"></div>
<div id="messages"></div>
<div class="body">
<form enctype="multipart/form-data" id="uploadImageForm">
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="name" id="name">
<label class="form-label">Worker's Name</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="dept" id="dept">
<label class="form-label">Department</label>
</div>
</div>
<div class="form-group form-float">
<div class="input-group">
<div class="form-line">
<input type="text" data-type="date" id="date" name="date" placeholder="Date" class="form-control datepicker">
</div>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<textarea name="description" id="description" cols="30" rows="5" class="form-control no-resize"></textarea>
<label class="form-label">Description</label>
</div>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Photo</label>
<div id="kv-avatar-errors-2" class="center-block" style="width:800px;display:none"></div>
<div class="kv-avatar center-block" style="width:200px">
<input id="avatar-2" name="userImage" type="file" class="file-loading">
</div>
</div>
<div class="form-group" align="center">
<button type="input" name="submit" class="btn btn-success btn-md btn-icon waves-effect" id="btn-submit" ><i class="fa fa-check-square-o"></i> Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- #END# Basic -->
</div>
</section>
<?php include('footer.php'); ?>
uploadimage.php
include('../../includes/functions.php');
if($_POST) {
$valid = array('success' => false, 'messages' => array());
$name = $mysqli->real_escape_string($_POST['name']);// user name
$dept = $mysqli->real_escape_string($_POST['dept']);
$desc = $mysqli->real_escape_string($_POST['description']);// user email
$yr = $mysqli->real_escape_string($_POST['date']);
$fileName = $_FILES['userImage']['name'];
$type = explode('.', $fileName);
$type = $type[count($type) - 1];
$url = '../user_images/' . uniqid(rand()) . '.' . $type;
if(in_array($type, array('gif', 'jpg', 'jpeg', 'png'))) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
if(move_uploaded_file($_FILES['userImage']['tmp_name'], $url)) {
// insert into database
$sql = "INSERT INTO worker_of_the_month (name, dept, description, given, img) VALUES ('$name','$dept','$desc','$yr', '$url')";
if($mysqli->query($sql) === TRUE) {
$valid['success'] = true;
$valid['messages'] = "Successfully Saved.";
}
else {
$valid['success'] = false;
$valid['messages'] = "Error while saving. " . $mysqli->error;
}
$mysqli->close();
}
else {
$valid['success'] = false;
$valid['messages'] = "Error while saving. " . $mysqli->error;
}
}
}
echo json_encode($valid);
// upload the file
}
Ajax.js
$('document').ready(function() {
/* validation */
$("#uploadImageForm").validate({
rules:
{
name:{
required: true
},
dept:{
required: true
},
description:{
required: true
},
date:{
required: true
},
},
messages:
{
name: "Worker name required",
dept: "Worker department name required",
description: "Enter description for this honour.",
date: "Please select date",
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm()
{
var data = $("#uploadImageForm").serialize();
$.ajax({
type : 'POST',
url : 'php_action/uploadImage.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-submit").html('<img src="../img/processing.gif" width="30" /> processing');
},
success : function(data)
{
if(data.success == true)
{
$("#btn-submit").html('<img src="../img/processing.gif" width="30" /> Saving ...');
$("#messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
data.messages +
'</div>');
$('#uploadImageForm')[0].reset();
/*setTimeout(' window.location.href = "success.php"; ',4000);*/
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").html('<span class="fa fa-check-square-o"></span> Save');
});
}
}
});
return false;
}
/* form submit */
});
</script>
What am I doing wrong?
You need to use a FormData() to pass files.
Change
var data = $('#uploadImageForm').serialize();
to
var form = $('#uploadImageForm')[0];
var data = new FormData(form);
As #ThisGuyHasTwoThumbs pointed you should set cache, contentType and processData via your ajax call
$.ajax({
cache: false,
processData: false,
contentType: false,
//other ajax parameters
});
You cannot POST files via AJAX like you have your code now.
This is how you can upload files using javascript and way better option:
PHP:
<?php
$fileName = $_FILES['afile']['name'];
$fileType = $_FILES['afile']['type'];
$fileContent = file_get_contents($_FILES['afile']['tmp_name']);
$dataUrl = 'data:' . $fileType . ';base64,' . base64_encode($fileContent);
$json = json_encode(array(
'name' => $fileName,
'type' => $fileType,
'dataUrl' => $dataUrl,
'username' => $_REQUEST['username'],
'accountnum' => $_REQUEST['accountnum']
));
echo $json;
?>
HTML:
<!DOCTYPE html>
<!--
Copyright 2012 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Author: Eric Bidelman (ericbidelman#chromium.org)
-->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<title>xhr.send(FormData) Example</title>
</head>
<body>
<input type="file" name="afile" id="afile" accept="image/*"/>
<script>
document.querySelector('#afile').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("afile", file);
// These extra params aren't necessary but show that you can include other data.
fd.append("username", "Groucho");
fd.append("accountnum", 123456);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'handle_file_upload.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
}
};
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
console.log('Server got:', resp);
var image = document.createElement('img');
image.src = resp.dataUrl;
document.body.appendChild(image);
};
};
xhr.send(fd);
}, false);
</script>
<!--[if IE]>
<script src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
<script>CFInstall.check({mode: 'overlay'});</script>
<![endif]-->
</body>
</html>
Quick example taken from: https://gist.github.com/ebidel/2410898

how to pass the two file value in next page through AJAX while adding muliple image in single form field

Here i have two form fields(file upload),first user select the logo and select one banner image means value is getting in next page (home.php).suppose user select one logo and select multiple banner image means i can not get the value in next page (home.php).how can do this ?
<script>
var i=0;
$(document).on("click",".add_banner",function() {
i++;
var htmlText = '';
htmlText += '<div class="form-group"><label class="col-md-3 control-label">Project Banners</label><div class="col-md-6"><div class="fileupload fileupload-new" data-provides="fileupload"><div class="input-append"><div class="uneditable-input"><i class="fa fa-file fileupload-exists"></i><span class="fileupload-preview"></span></div><span class="btn btn-default btn-file"><span class="fileupload-exists">Change</span><span class="fileupload-new">Select file</span>';
htmlText +='<input type="file" name="banners[]" id="banners' + i +'">';
htmlText += '</span><span style="margin-left:10px"><button type="button" class="btn btn-default add_banner" id="add_banner">Add</button></span>Remove</div></div></div></div>';
$('#add_banner_append').append(htmlText);
});
</script>
<script>
$(document).ready(function(){
$('#btn-submit').click(function(){
if($('#empForm').valid()){
var formData = new FormData();
var formData = new FormData($('#empForm')[0]);
formData.append('logo', $('input[type=file]')[0].files[0]);
formData.append('banners', $('input[type=file]')[1].files[1]);
$.ajax({
type:'POST',
url :"php/home.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if(data == "Success"){
$("#alert_success").show();
$("#alert_success").fadeOut(3000);
setTimeout(function () {
window.location.href = "dashboard.php";
}, 2000); //will call the function after 2 secs.
}
},
error:function(exception){
alert('Exeption:'+exception);
}
});
return false;
}
});
});
// Shorthand for $( document ).ready()
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form class="form-horizontal form-bordered" method="POST" id="empForm">
<div class="form-group">
<label class="col-md-3 control-label">Project Logo</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="logo" name="logo" required="" data-msg-required="File" value="" aria-required="true">
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Project Banners</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="banners" name="banners[]" required="" data-msg-required="File" value="" aria-required="true">
</span><span style="margin-left:10px">
<button type="button" class="btn btn-default add_banner" id="add_banner">Add</button></span>
</div>
</div>
</div>
</div>
<div id="add_banner_append"></div>
<div class="form-group">
<div class="col-md-3">
</div>
<div class="col-md-6">
<input type="button" class="btn btn-primary btn-block" id="btn-submit" name="submit" value="SUBMIT">
</div>
</div>
</form
$postedBanners = array();
/* foreach ($_FILES['banners']['name'] as $key => $value) {
$postedBanners[$key] = array(
'name' => $_FILES['banners']['name'][$key],
'type' => $_FILES['banners']['type'][$key],
'tmp_name' => $_FILES['banners']['tmp_name'][$key],
'error' => $_FILES['banners']['error'][$key],
);
} */
$uploads_dir = '/banners';
foreach ($_FILES["banners"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["banners"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = $_FILES["banners"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
You are missing enctype in both html form and ajax calling. You should add enctype in form like as <form class="form-horizontal form-bordered" method="post" id="empForm" enctype="multipart/form-data">.
Aslo add enctype in ajax calling -
$('#btn-submit').click(function(){
if($('#empForm').valid()){
var formData = new FormData();
var formData = new FormData($('#empForm')[0]);
formData.append('logo', $('input[type=file]')[0].files[0]);
formData.append('banners', $('input[type=file]')[1].files[1]);
$.ajax({
type:'POST',
url :"test.php",
enctype: 'multipart/form-data',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if(data == "Success"){
$("#alert_success").show();
$("#alert_success").fadeOut(3000);
setTimeout(function () {
window.location.href = "dashboard.php";
}, 2000); //will call the function after 2 secs.
}
},
error:function(exception){
alert('Exeption:'+exception);
}
});
return false;
}
});
I have added enctype: 'multipart/form-data' in ajax calling.
At server end you need to get all multiple added banner image as following -
if(!empty($_FILES['banners']['name'])){
$postedBanners = array();
foreach ($_FILES['banners']['name'] as $key => $value) {
$postedBanners[$key] = array(
'name' => $_FILES['banners']['name'][$key],
'type' => $_FILES['banners']['type'][$key],
'tmp_name' => $_FILES['banners']['tmp_name'][$key],
'error' => $_FILES['banners']['error'][$key],
);
}
echo '<pre>';
print_r($postedBanners);
}
I will return output as following -
Array
(
[0] => Array
(
[name] => preview.png
[type] => image/png
[tmp_name] => /private/var/tmp/php9Fyir9
[error] => 0
)
)
For Upload banner images in a folder.
$uploads_dir = '/uploads';
foreach ($_FILES["banners"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["banners"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["banners"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}

fileupload not working in ajax

i have file upload form field,i select one gif','png' ,'jpg' means it will work,and i am select any other file .mp3,.php file it will give error like this **SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 73 of the JSON data**.i want to file type check and file size after that i want to insert the value,but don't know how to do this,i think my PHP code should be wrong...
<?php
$filename = basename($_FILES['file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new_name= md5($filename.time()).'.'.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'], "horoscope/".$new_name)) {
// FILE TYPE CHECKING
$allowed = array('gif','png' ,'jpg');
if(!in_array($extension,$allowed) ) {
$newuser = array('photoname' => $new_name, "message" => "error");
if($_FILES['file']['size'] > 2459681 ){
$newuser = array('photoname' => $new_name, "message" => "filesize is to large");
}else{
$newuser = array('photoname' => $new_name, "message" => "success");
}
echo json_encode($newuser);
}
else{
$newuser = array('photoname' => $new_name, "message" => "success");
}
echo json_encode($newuser);
}else{
//echo "Error";
$newuser = array("message" => "file is not moving");
echo json_encode($newuser);
}
?>
<script type="text/javascript">
$(document).ready(function(){
$("#user-submit").click(function(event){
event.preventDefault();
if($("form#newUserForm").valid()){
var formData = new FormData();
var formData = new FormData($('#newUserForm')[0]);
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'horoscope-check.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
},
});
return false;
}else{
console.log("false");
}
});
});
</script>
<form class="form-horizontal form-bordered" method="POST" id="newUserForm" enctype="multipart/form-data">
<div class="form-group">
<label class="col-md-3 control-label">Photo Upload</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="file" name="file" value="" aria-required="true" required="" data-msg-required="Please select your file">
</span>
Remove
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button class="btn btn-info" type="submit" id="user-submit">Submit</button>
</div>
</div>
</form>
Using xhr() could solve your problem... for example :-
var formData = new FormData($('#newUserForm')[0]);
$.ajax({
url: 'horoscope-check.php',
type: 'POST',
data: formData,
async: false,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
//if you want progress report otherwise you can remove this part from here to
myXhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100 ;
percentComplete = Math.round(percentComplete);
$("#progress").text(percentComplete + " %");
}
}, false);
//here
return myXhr;
},
cache: false,
contentType: false,
processData: false,
success: function (data) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
},
});

Json response to ajax

The data is inserted and i receive in console the json response but the page move for the insert php and gives the json response
So i start in page A (form) and after submit moves to page B (insert)giving me the json response.
I'm having a problem getting the response of the following php into ajax
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
$target_path = "/uploads/" . basename($_FILES['fileToUpload']['name']);
$sql = "INSERT INTO `ebspma_paad_ebspma`.`formacoes`(idescola, nome, inicio, horas, local, destinatarios, dataLimite, visto, path) VALUES(?, ?, ?, ?, ? ,?, ?, ?, ? )";
$stmt = $mysqli->prepare($sql);
if ($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $mysqli->error, E_USER_ERROR);
}
$stmt->bind_param('issssssis', $escola, $form, $data, $horas, $local, $dest, $datas, $visto, $target_path);
if (!$stmt->execute()) {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
} else {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
$stmt->close();
echo json_encode(array('status' => 'success', 'message' => 'Nova formação gravada'));
This is my ajax
$.ajax({
url: 'nova_formacaoBD.php',
dataType: 'json',
data: data,
success: function(data) {
$('#ajaxDivOk').html('Informação: Esta formação foi registada na base de dados');
if(data.status == "success"){
$('#ajaxDivOk').append(data.message);
}
}
});
And this is my form
<form action="nova_formacaoBD.php" method="post" id="formacao" name="formacao" enctype="multipart/form-data">
UPDATE
The data is all the input fields in the form
Seven strings and upload of one file
<form method="post" id="formacao" name="formacao" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile">Escola: </label>
<select class="form-control" id="escola" name="escola" onchange="verificaEscola()">
<?php echo $escolaOptions; ?>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Nome Formação: </label>
<input class="form-control" id="form" name="form" onchange="verificaNome()">
</input>
<div class="form-group">
<label for="exampleInputEmail1">Data de Início: </label><input type="text" class="form-control" id="data" name="data" onchange="verificaData()" />
</div>
<div class="form-group">
<label for="exampleInputEmail1">Horas: </label><input type="text" class="form-control" id="horas" name="horas" onchange="verificaHoras()">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Local: </label>
<input class="form-control" id="local" name="local" onchange="verificaLocal()">
</input>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Destinatários: </label>
<input class="form-control" id="dest" name="dest" onchange="verificaDest()">
</input>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Data Limite: </label><input type="text" class="form-control" id="datas" name="datas" onchange="verificaDataLimite()"/>
</div>
<div class="form-group">
<label for="exampleInputFile">Programa da Formação</label>
<input type="file" name="fileToUpload" id="fileToUpload" name="fileToUpload">
</div>
<button type="submit" class="btn btn-default" onclick="return checkBoxes(this)">Registar</button>
</form>
This is my form complete
UPDATE 2 (now it works but i have a warning in my console
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
and the beforeSend funtion doesn't work
I don't see the div "Wait while updating the file)
Js code
<script type="text/javascript">
$(document).ready(function () {
$("#formacao").submit(function (event) {
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
$.ajax({
url: 'nova_formacaoBD.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
beforeSend: function(data){
$('#ajaxDivAlert').html('A carregar o ficheiro...aguarde por favor')
},
success: function (data) {
var result = data.status;
console.log(result);
if(result == 'success'){
$('#ajaxDivAlert').empty();
$('#ajaxDivOk').html('Informação: ' + data.message);
$("#ajaxDivOk").fadeIn();
$("#ajaxDivOk").fadeOut(5000);
}
},
error: function(){
$("#ajaxDivErro").html('Esta formação já está registada na base de dados');
$("#ajaxDivErro").fadeIn();
$("#ajaxDivErro").fadeOut(5000);
}
});
return false;
});
});
</script>
So, i just need to put info to complete the code, the rest is working
You have some changes to do :
Html : Remove the action="nova_formacaoBD.php" like that :
<form method="post" id="formacao" name="formacao" enctype="multipart/form-data">
Then I suppose that you have a ajax called like that :
UPDATE
$(document).ready(function () {
$("#formacao").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var ajaxDivAlert = $('#ajaxDivAlert');
$.ajax({
url: 'nova_formacaoBD.php',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
ajaxDivAlert.empty().html('A carregar o ficheiro...aguarde por favor')
}
}).done(function (data) {
var result = data.status;
if (result == 'success'){
ajaxDivAlert.empty().fadeIn().html('Informação: ' + data.message).fadeOut(5000);
}
}).fail(function () {
ajaxDivAlert.empty().fadeIn().html('Esta formação já está registada na base de dados').fadeOut(5000);
});
});
});
You had the error XMLHttpRequest because you put async: false. I removed it because since jQuery 1.8, the use of async: false with jqXHR ($ .Deferred) is deprecated

Categories