photo not storing onto the database. php [undefined Index] - php

I have form like this:
<form class="wrefresh" action="Code Files/Accused.php" method="post" enctype="multipart/form-data">
<div class="row-form">
<div class="span3" style="margin-top: 06px">Picture:</div>
<div id="photo_settings2" style="margin-left:11px;">
<img id="Picture2" src="../../img/User No-Frame.png"/>
</div>
<div id='Upload_Panel'>
<input name="file" type='file' id='file_browse' onchange="readURL(this,'Picture2')" style="cursor: pointer;"/>
</div>
</div>
<button type="submit" class="a-btn2"style="cursor: pointer; background-color:#5C635F; color:white; font-family:'Candara'; margin-top:-47px; margin-left:192px; height:37px;"><big>Submit</big></button>
</form>
I have a php code in Accused.php:
$Mother_Language = $_POST['mlang'];
$Other_Languages = $_POST['olang'];
$Complexion = $_POST['comp'];
$Previous_Thug_Record = $_POST['precord'];
$Religion = $_POST['religion'];
$Type_of_Accused = $_POST['taccused'];
$City = $_POST['city'];
$Country = $_POST['country'];
$Nationality = $_POST['nationality'];
$ID_Mark = $_POST['idmark'];
$Hair_Color = $_POST['haircolor'];
$Occupation = $_POST['occupation'];
$Academic_Info = $_POST['ainfo'];
$Alias = $_POST['alias'];
$Caste = $_POST['caste'];
$Sect = $_POST['sect'];
$Remarks = $_POST['remarks'];
$photo = $_POST['file']; // giving error : undefined index/ getting nothing from the form.
my ajax function is:
<script>
var frm = $('.wrefresh');
frm.submit(function (ev)
{
ev.preventDefault();
var postdate = $(this).serialize();
var path = $(this).attr("action");
var mehtodtype = $(this).attr("method").toUpperCase();
$(".loadingimg").show();
$.ajax
({
type: mehtodtype,
url: path,
data: postdate,
success: function(data)
{
// Get Form Data.
$("#FIRtable").html(data);
$("#Accusedtable").html(data);
// Clear fields data.
$('form :input[type=text], textarea').attr('value', '');
// show hide icons when click on submit.
$(".loadingimg").delay(1000).fadeOut();
setTimeout(function()
{
$(".okicon").fadeIn('slow');
$(".okicon").delay(2800).fadeOut();
}, 1800);
}
});
});
</script>
I think my error is because of the ajax function i am using. I am getting every thing working except $photo = $_POST['file']; this // giving error : undefined index. help would be appreciated.

Uploading files through AJAX is a lot more complex than just referencing the $_FILES array. You'll need something like this to handle the file upload:
function upload_file() {
var formData = new FormData( document.getElementById( "form-uploader" ));
$.ajax( {
url : "Code Files/Accused.php",
type : "post",
xhr : function() {
my_xhr = $.ajaxSettings.xhr();
if( my_xhr.upload ) {
my_xhr.upload.addEventListener( "progress", handler_progress, false );
}
return my_xhr;
},
beforeSend : handler_before_send,
success : handler_complete,
error : handler_error,
data : formData,
contentType : false,
processData : false
} );
}
The primary difference between this and your code is that it employes the JavaScript FormData object, which is required to upload files with AJAX.
And then a variety of supporting functions that will be called when the upload starts, what its progress is, if there are any errors, and when it completes:
function handler_progress( e ) {
if( e.lengthComputable ) {
$( "progress" ).attr( {value:e.loaded, max:e.total} );
}
}
function handler_before_send( e ) {
var progress = $( "<progress></progress>" ).attr( "id", "progress-bar" );
$( "#form-uploader" ).append( progress );
}
function handler_error( e ) {
alert( "error" + e );
}
function handler_complete( e ) {
// The browser has completed the upload, do any clean-up here
}
This is mostly copy-and-paste from one of my projects where I do what you're describing (with a couple of changes to tie it in with your code), so you'll see some elements referenced by ID that are in my HTML that you'll have to modify. But this is essentially what you're looking for to upload files via AJAX.

Related

Ajax post work but PHP doesn't recognize it

I'm trying to use ajax to store the JavaScript variables which get their values from divs into MySql every 10 seconds. But for some reason the PHP doesn't recognize the variables I'm Posting to it. It displays Undefined Index for all the variables. I tried to use the if(isset($_POST['Joy'])) and the error disappeared but the sql query is never created.
Here is the HTML code (Note: The HTML is originally provided by Affectiva (https://www.affectiva.com) for the video stream facial emotion recognition system. The code lines followed with // are from the original HTML file. The rest are personal effort to store the values of emotions to the database),
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://download.affectiva.com/js/3.2/affdex.js"></script>
</head>
<body>
<div class="container-fluid"> //
<div class="row"> //
<div class="col-md-8" id="affdex_elements" //
style="width:680px;height:480px;"></div> //
<div class="col-md-4"> //
<div style="height:25em;"> //
<strong>EMOTION TRACKING RESULTS</strong><br> //
Joy <div id="Joy"></div> //
Sad <div id="Sadness"></div> //
Disgust <div id="Disgust"></div> //
Anger <div id="Anger"></div> //
Fear <div id="Fear"></div> //
</div> //
</div> //
</div> //
</div> //
<div> //
<button id="start" onclick="onStart()">Start</button> //
</div> //
Here is the JavaScript code,
var divRoot = $("#affdex_elements")[0]; //
var width = 640; //
var height = 480; //
var faceMode = affdex.FaceDetectorMode.LARGE_FACES; //
var detector = new affdex.CameraDetector(divRoot, width, height,
faceMode); //
detector.detectAllEmotions(); //
function onStart() { //
if (detector && !detector.isRunning) { //
detector.start(); //
} } //
function log(node_name, msg) { //
$(node_name).append( msg ) //
} //
setInterval(function getElement(){
var j = Number($("#Joy").text()); //div value
var s = Number($("#Sadness").text()); //div value
var d = Number($("#Disgust").text()); //div value
var a = Number($("#Anger").text()); //div value
var f = Number($("#Fear").text()); //div value
$.ajax({
url: "HTML.php",
data: {Joy:j,Sadness:s,Disgust:d,Anger:a,Fear:f},
type: 'POST',
success : function (){
alert("sucess");
} });
}
,10000);
detector.addEventListener("onImageResultsSuccess", function(faces, image,
timestamp) { //
$("#Joy").html("");$("#Sadness").html("");$("#Disgust").html(""); //
$("#Anger").html("");$("#Fear").html(""); //
var joy = JSON.stringify(faces[0].emotions.joy,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
var sad = JSON.stringify(faces[0].emotions.sadness,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
var disgust =
JSON.stringify(faces[0].emotions.disgust,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
var anger = JSON.stringify(faces[0].emotions.anger,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
var fear = JSON.stringify(faces[0].emotions.fear,function(key,val) {
return val.toFixed ? Number(val.toFixed(0)) : val; //
});
log('#Joy', JSON.parse(joy) );
log('#Sadness', JSON.parse(sad));
log('#Disgust', JSON.parse(disgust));
log('#Anger', JSON.parse(anger));
log('#Fear', JSON.parse(fear));
});
I get the success alert but the database contain nothing. Here is my PHP code,
<?php
$conn = mysqli_connect('localhost', 'root', '', 'emotions');
if(isset($_POST['Joy'])){
$Joy = $_POST['Joy'];
$Sadness = $_POST['Sadness'];
$Disgust = $_POST['Disgust'];
$Anger = $_POST['Anger'];
$Fear = $_POST['Fear'];
$sql = "Insert into IPEMOTION (JOY, SADNESS, DISGUST, ANGER, FEAR) values
($Joy,$Sadness,$Disgust,$Anger,$Fear)";
mysqli_query($conn, $sql); }
?>
One test I have made is checking the contents of $_POST['Joy'] so I wrote the following code in my php
if (!isset($_POST['Joy'])){
echo "Joy is empty";}
after running the code the previous message "Joy is empty" appeared to me.
Your data shouldn't be like that!
From the Documentation, the data should be like this :
{variableName: value}
So, in your case, the data should be :
{Joy:Joy,Sadness:Sadness,Disgust:Disgust,Anger:Anger,Fear:Fear}
Without the quotes (')
And in HTMLNew.php you can do :
$joy = $_POST['Joy'];
I'm just gonna keep helping you through the answer section, as it is the most easy way for now. So you are saying that the ajax success alert is popping. Then i think that your Interval is not functioning well. Change this:
setInterval(function getElement(){
var j = Number($("#Joy").text()); //div value
var s = Number($("#Sadness").text()); //div value
var d = Number($("#Disgust").text()); //div value
var a = Number($("#Anger").text()); //div value
var f = Number($("#Fear").text()); //div value
$.ajax({
url: "HTML.php",
data: {Joy:j,Sadness:s,Disgust:d,Anger:a,Fear:f},
type: 'POST',
success : function (){
alert("sucess");
} });
},10000);
Into this:
function getElement(){
var j = Number($("#Joy").text()); //div value
var s = Number($("#Sadness").text()); //div value
var d = Number($("#Disgust").text()); //div value
var a = Number($("#Anger").text()); //div value
var f = Number($("#Fear").text()); //div value
$.ajax({
url: "HTML.php",
data: {Joy:j,Sadness:s,Disgust:d,Anger:a,Fear:f},
type: 'POST',
success : function (){
alert("sucess");
}
});
}
setInterval(function() {
getElement();
}, 10000);
Just a few question. To see if your values are right you can echo $Disgust in your PHP Script. Then change this:
success : function (){
alert("sucess");
}
Into this
success : function (data){
alert(data);
}
Then:
<?php
//$conn = mysqli_connect('localhost', 'root', '', 'emotions');
//if(isset($_POST['Joy'])){
$Joy = $_POST['Joy'];
$Sadness = $_POST['Sadness'];
$Disgust = $_POST['Disgust'];
$Anger = $_POST['Anger'];
$Fear = $_POST['Fear'];
echo $Joy;
echo $Sadness;
echo $Disgust;
echo $Anger;
echo $Fear;
//$sql = "Insert into IPEMOTION (JOY, SADNESS, DISGUST, ANGER, FEAR) values
//($Joy,$Sadness,$Disgust,$Anger,$Fear)";
//mysqli_query($conn, $sql);
//}
?>
Let me know. I'm deleting all my past answers until now.

jQuery Form Plugin doesn't submit forms per AJAX, it's still reloading the page, why?

Can't seem to get this running, I am using jQuery 3.2.1 together with the jQuery Form Plugin 4.2.1. I also have included the jQuery Cookies Plugin 1.4.1. Now, if I submit a Form, that is called by .ajaxForm(); it doesn't work and still reloads the page and redirects me to the action-path that is included in the form. I tried it with a lower version of jQuery, 1.2 and with that it worked fine. But if I use the older version, some other functions wouldn't work anymore, what's why I need to use the latest one.
Here's my head-tag:
<!--- JQUERY --->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!--- JQUERY FORM PLUGIN --->
<script src="js/de.jqu.form.421.js"></script>
<!--- JQUERY COOKIE PLUGIN --->
<script src="js/de.jqu.cookies.141.js"></script>
<!--- JQUERY MIGRATE --->
<script src="https://code.jquery.com/jquery-migrate-3.0.0.js">
The HTML form:
<form enctype="multipart/form-data" name='imageform' role="form" id="imageform" method="post" action="/functions/c_uploadcans.php">
...
<input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/>
</form>
And the script I am using to call the .ajaxForm():
(function() {
$('#imageform').ajaxForm({
beforeSubmit: function() {
count = 0;
val = $.trim( $('#images').val() );
if( val == '' ){
count= 1;
$( "#images" ).next('span').html( "Please select your images" );
}
if(count == 0){
for (var i = 0; i < $('#images').get(0).files.length; ++i) {
img = $('#images').get(0).files[i].name;
var extension = img.split('.').pop().toUpperCase();
if(extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG"){
count= count+ 1
}
}
if( count> 0) $( "#images" ).next('span').html( "Please select valid images" );
}
if( count> 0){
return false;
} else {
$( "#images" ).next('span').html( "" );
}
},
beforeSend:function(){
$('#loader').show();
$('#image_upload').hide();
},
success: function(msg) {
},
complete: function(xhr) {
$('#loader').hide();
$('#image_upload').show();
$('#images').val('');
$('#error_div').html('');
result = xhr.responseText;
result = $.parseJSON(result);
base_path = $('#base_path').val();
if( result.success ){
name = base_path+'images/'+result.success;
html = '';
html+= '<image src="'+name+'">';
$('#uploaded_images #success_div').append( html );
} else if( result.error ){
error = result.error
html = '';
html+='<p>'+error+'</p>';
$('#uploaded_images #error_div').append( html );
}
$('#error_div').delay(5000).fadeOut('slow');
}
});
})(jQuery);
Maybe someone finds a mistake, I really have no idea. Thanks in advance.
how are you calling that function. may be its not even called. put that in `
$(document).ready(function()`{ your ajaxForm code });
like this ...
$(document).ready(function() {
$('#imageform').ajaxForm({
beforeSubmit: function() {
count = 0;
val = $.trim( $('#images').val() );
......
......
});
});
hope this works for you
My guess is because in your beforeSend all you are doing is showing the loader and hiding image_upload
beforeSend:function(){
$('#loader').show();
$('#image_upload').hide();
},
Shouldn't you be handling ajax post call here as well?

Input type file - ajax upload, and php script

I am trying to use jquery( v. 1.11.3 )ajax, in conjunction with jquery.validate 1.15 to upload a form that includes input type file. You can see from the js comment lines some of everything I have tried. With each of the variations the php script returns "no image file". Of course, if I remove the jquery script, the form submits fine with accompanying page refresh. I really wanted to eliminate the page refresh for a better UX but I am having no luck getting this to work. If someone could help me fix my code, I'd really appreciate it. Please Note: I have researched numerous examples of jquery ajax .post but these examples are not helping me as those code structures don't work with Jquery.Validate plugin. I also found this answer here: File Upload PHP AJAX but as you can see from my code comments, I have tired this with no luck.
I must be missing something.
Heading ##The html and js:
<!DOCTYPE html>
<html>
<body>
<form action="imguploadTest.php" method="post" enctype="multipart/form-data" id="addItemsForm" name="addItemsForm">
<label>Select image to upload:</label>
<input type="file" name="itemImg" id="itemImg" />
<label>Name</label>
<input type="text" name="itemName" class="form-control" placeholder="Item Name..." maxlength="25" value="Really Cool Hoodie" />
<input type="submit" value="Upload Form" name="submit">
<div>
<div id="results"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/additional-methods.min.js"></script>
<script>
$(document).ready(function(){
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else if (element.parent('.radio-inline').length || element.parent('.checkbox-inline') ) {
error.insertAfter(element.parent().parent());
} else {
error.insertAfter(element);
}
}
});
$('#addItemsForm').validate({ // initialize the plugin
debug: true,
submitHandler: function(){
//var formData = $('#addItemsForm').serialize();
//var data = new FormData($('#addItemsForm'));
//var form = $('form')[0];
//var formData = new FormData(form);
//console.log(addform);
var frmData = new FormData($(this)[0]);
$.ajax({
url: "imgUploadTest.php",
data: frmData,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
})
.done( function(res, jqXHR, textStatus) {
console.log(res);
//$('#results').html('<h4>Thumb link: ' + res["thumb"] + '<h4>');
//$('#results').append('<h4>Small link: ' + res["small"] + '<h4>');
//$('#results').append('<h4>Name: ' + res["name"] + '<h4>');
})
.fail( function (res, jqXHR, textStatus, errorThrown){
alert("failed! " + jqXHR, textStatus);
});
return false;
} // submitHandler
}); // validate
}); // doc ready
</script>
</body>
</html>
Heading ##The PHP:
<?php
include 'imguploader.class.php';
// FUNCTIONS
function imagehandler($item_attr_ID) {
$imgId = $item_attr_ID;
$img = new imgUploader($_FILES['itemImg']);
$time = time();
$thumb = $img->upload('mobileApp/uploads/', $imgId.'_thumb', 100,100); // change these numbers for display
$small = $img->upload('mobileApp/uploads/', $imgId.'_small', 400,400); // change these numbers for display
//$full = $img->upload_unscaled('mobileApp/uploads/', $time);
if($thumb && $small){ // && $full
return array($thumb, $small);
/* TO SHOW IMAGE
echo '<img src="'.$thumb.'" alt="aPicture" /> <img src="'.$small.'" alt="aPicture" /> <img src="'.$full.'"alt="aPicture" />';
*/
} else {
echo ( 'ERROR! '.$img->getError() ); // --> error code 011.1
}
} // end imagehandler()
// Processes
if (!empty( $_FILES["itemImg"]) ){
$item_attr_ID = "jPlayerandtheGirls_8_1456";
list($item_img_thumb, $item_img_small) = imagehandler($item_attr_ID);
if ($item_img_thumb && $item_img_small){
$r["thumb"] = $item_img_thumb;
$r["small"] = $item_img_small;
} else {
$r["thumb"] = "No Thumb";
$r["small"] = "No Small";
$r["name"] = "Didn't get to name";
echo json_encode($r);
}
} else {
$r = "No image file";
echo json_encode($r);
}
if (!empty( $_POST["itemName"] )){
$r["name"] = $_POST["itemName"];
json_encode($r);
}
?>
Ok I am able to answer my own question, though I am not exactly sure about the theory that goes with it as I am relatively new to JS/Jquery. .serialize() does not work. I think this is because by definition, files are binaries and thus can not be serialized - but don't quote me. So you have to use FormData to send the file. I was aware of this but could not come up with the proper syntax for use with jquery validation 1.15. See the answer below. Hope it helps someone to save some time.
first correct the rookie mistake with my code: add type: 'post'
second: the variable to hold your form's data, including the input type="file" is this var formData = new FormData($('#useYourFormElementIdHere')[0]);
So the final is this:
$.ajax({
type: "POST",
url: "imgUploadTest.php",
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
}).done({}).fail({}).always({})

submit form php without refresh page

I'm working on a PHP application i want to submit form without refresh page. Actually, i want my php code to be written on the same page as the one containing html and jquery code.
In order to submit form using jquery i've written this code
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
$.post("php-opt.php", //Required URL of the page on server
{ // Data Sending With Request To Server
selectrefuser:vname,
},
function(response,status){ // Required Callback Function
//alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
});
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
//return false;
//e.preventDefault();
//$("#monbutton:hidden").trigger('click');
});
});
and my php code is :
<?php
$resclient_alt = 1;
$resclient_long = 1;
if(isset($_POST['selectrefuser'])){
$client = $_POST['selectrefuser'];
echo $client;
$client_valide = mysql_real_escape_string($client);
$dbprotect = mysql_connect("localhost", "root", "") ;
$query_alt= "SELECT altitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1_alt=mysql_query($query_alt, $dbprotect);
$row_ss_alt = mysql_fetch_row($query_resclient1_alt);
$resclient_alt = $row_ss_alt[0];
//echo $resclient_alt;
$query_gps= "SELECT longitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1=mysql_query($query_gps, $dbprotect);
$row_ss_ad = mysql_fetch_row($query_resclient1);
$resclient_long = $row_ss_ad[0];
}
?>
My form is as below
<form id="form1" name="form1" method="post" >
<label>
<select name="selectrefuser" id="selectrefuser">
<?php
$array1_refuser = array();
while (list($key,$value) = each($array_facture_client_refuser)) {
$array1_refuser[$key] = $value;
?>
<option value="0" selected="selected"></option>
<option value="<?php echo $value["client"];?>"> <?php echo $value["client"];?></option>
<?php
}
?>
</select>
</label>
<button id="btn">Send Data</button>
</form>
My code does these actions:
select client get its GPS coordinates
recuperates them in php variable
use them as jquery variable
display marquer on map
So since i do this steps for many clients i don't want my page to refresh.
When i add return false or e.preventDefault the marquer is not displayed, when i remove it the page refresh i can get my marquer but i'll lost it when selecting another client.
is there a way to do this ?
EDIT
I've tried using this code, php_query.php is my current page , but the page still refresh.
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Edit
When adding e.preventDfault , this code doesn't seem to work
$( "#monbutton" ).click(function() {
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
$('#myResults').html("je suis "+php_long);
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
});
This code recuperate this value var vname = $("#selectrefuser").val(); get result from sql query and return it to jquery .
It will refresh since you have not prvent default action of <button> in script
$("#btn").click(function(e){ //pass event
e.preventDefault(); //this will prevent from refresh
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Updated
Actually, i want my php code to be written on the same page as the one containing html and jquery code
You can detect the ajax call on php using below snippet
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special code here */
}

I want to upload file my file

I was getting undefined file as an error in my php while uploading a file.
function click_submit_form() {
var action = "jb_data_charity_submit.php";
// alert("I step"+$('#id_frm_per_details, #id_frm_acc_details , #id_frm_charity_details').serialize());
$.ajax({
url: 'jb_data_charity_submit.php',
type: 'POST',
data: $('#id_frm_charity_details').serialize(),
success: function (data_in) {
//alert(data_in);
if (data_in != null && !isEmpty(data_in) && (data_in).indexOf('VALIDATION_ERROR') != -1) {
var value = data_in.substr(data_in.indexOf('VALIDATION_ERROR'), data_in.indexOf('|#END#'));
var array_str = value.split('|')
//alert(array_str[0]);
//alert(array_str[1]);
//alert(array_str[2]);
var id_val = "#id_" + array_str[1].trim();
show_error(id_val, array_str[2])
} else {
window.location.replace('jb_charity_regn_confirm.html');
alert(data_in);
// alert("FINAL");
}
}
});
return false;
}
<form class='form-vertical' id='id_frm_charity_details' name='frm_charity_details' action='jb_data_harity_submit.php' enctype='multipart/form-data'>
<input id="id_file" name="file" class="input-file" type="file"> <a onclick='click_submit_form();' href="#" class="btn btn-info btn-custom8 btn-large "><i class=" icon-play"></i> Submit Application</a>
</form>
In my php
<?php
$files = $_FILES['file']['name'];
$files_tmp = $_FILES['file']['tmp_name'];
$copy = copy($files_tmp, $files);
//echo $_POST['file'];
move_uploaded_file($files_tmp, "C:\wamp32\www\jb_from_live\src\uploaded_files/" . $files);
?>
If i use the above line then it says undefined index 'file'.But the execution not going after $files=$_FILES['file']['name'];
It says undefined index file.
Send image to this format
$('#form').submit(function() {
var img=$('#image').val();
var forms=($(this).serialize());
$.ajax({
type:"POST",
url: "do.php?do=upload",
data:forms+'&r='+encodeURIComponent(img),
success: function(result){ //your code }
});
Try this in your code like this
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
function click_submit_form(){
var action = "jb_data_charity_submit.php";
// alert("I step"+$('#id_frm_per_details, #id_frm_acc_details , #id_frm_charity_details').serialize());
var img=$('#id_file').val();
var forms=($('#id_frm_charity_details').serialize());
$.ajax({
url: 'jb_data_charity_submit.php',
type: 'POST',
data:forms+'&r='+encodeURIComponent(img),
// data: $('#id_frm_charity_details').serialize(),
success: function(data_in) {
//alert(data_in);
if (data_in != null && !isEmpty(data_in) && (data_in).indexOf('VALIDATION_ERROR') != -1) {
var value = data_in.substr(data_in.indexOf('VALIDATION_ERROR'), data_in.indexOf('|#END#'));
var array_str = value.split('|')
//alert(array_str[0]);
//alert(array_str[1]);
//alert(array_str[2]);
var id_val = "#id_" + array_str[1].trim();
show_error(id_val, array_str[2])
} else {
window.location.replace('jb_charity_regn_confirm.html');
alert(data_in);
// alert("FINAL");
}
}
});
return false;
}
</script>
<form class='form-vertical' id='id_frm_charity_details' name='frm_charity_details' action='jb_data_harity_submit.php' enctype='multipart/form-data' >
<input id="id_file" name="file" class="input-file" type="file">
<a onclick='click_submit_form();' href="#" class="btn btn-info btn-custom8 btn-large "><i class=" icon-play"></i> Submit Application</a>
</form>
I recommend you to use FormData instead of serialize(). The advantage of using formData is that you can also upload pdf,xml,JSON files by specifying their content-type.
For eg:
var fData = new FormData();
fData.append("XML", new Blob([ xml ], { type: "text/xml" });
fData.append("JSON", new Blob([ JSON.stringify(json) ], { type: "application/json" }));
fData.append("PDF", file);
Make sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
You cannot upload a file via ajax that simply unfortunately, for security reasons js doesn't have access to file data and therefore cannot post it via the form serialize function.
If you want to validate other parts of the form and then submit you could write a function like this
function submit(){
var valid = true;
//TODO: check validation on form, set valid to false if incorrect
if( valid )
document.forms[0].submit();
return false;
}
If you want to use HTML5 have a geez at this answer which utilizes the FormData() function:
How can I upload files asynchronously?
Otherwise if you with to upload a file asynchronously you'll have to look for a jsp or flash fallback plugin.
Here's a really good one:
http://blueimp.github.io/jQuery-File-Upload/

Categories