Link to home
Start Free TrialLog in
Avatar of Moses Dwana
Moses Dwana

asked on

how to send data and file to php using ajax

can you please show me how to upload file using ajax? i have been successifully submitting data using ajax but when i try to upload file, the entire code stop working. please see my code below:
this is the html
<form method="POST"  id="form8" name="form8"  class='sform' action="">

        <!-- /.portlet-header -->


        <div class="portlet-content">

         
		  
		  
<div class="form-group">






<div>
<div id="result10"></div>
<div id="result9"></div>
</div>
<div class="col-sm-4">
 <div class="row">  
              <div class="fileupload fileupload-new" data-provides="fileupload">
                <div class="fileupload-preview thumbnail" style="width: 200px; height: 150px;"></div>
                <div>
                  <span class="btn btn-default btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" id="fupload" name="fupload" /></span>
                  <a href="#" class="btn btn-default fileupload-exists" data-dismiss="fileupload">Remove</a>
                </div>
            </div>
			</div>
</div>
<div class="col-sm-4">
			<p>First Name</p>
             <input type="text" class="form-control" id="sfname" name="sfname" placeholder="First Name" onblur="this.value=this.value.toUpperCase()">
		 <div id="result"></div> 
            </div> 
			
			<div class="col-sm-4">
			<p>Middle Name</p>
             <input type="text" class="form-control" id="smname" name="smname" placeholder="Last Name">
			   
            </div> 
			<div class="col-sm-4">
			<p>Last Name</p>
             <input type="text" class="form-control" id="slname" name="slname" placeholder="Last Name">
			<div id="result2"></div>   
            </div> 
			<div class="col-sm-4">
			<p>Sex</p>
              <select  id="ssex" name="ssex" class="form-control">
				  <option value="">select one</option>
				 <option value="Male">Male</option>
                  <option value="Female">Female</option>
				 </select>
			<div id="result3"></div>   
            </div>
          </div>
		  <div class="form-group">
		 <div class="col-sm-4">
			<p>Age</p>
             <input type="text" class="form-control" id="sage" name="sage" placeholder="Age">
			<div id="result5"></div>   
            </div> 
			<div class="col-sm-4">
			<p>Address</p>
             <input type="text" class="form-control" id="saddress" name="saddress" placeholder="Address">
			<div id="result4"></div>  
            </div> 
			<div class="col-sm-4">
			<p>Phone Number</p>
             <input type="text" class="form-control" id="sphonenum" name="sphonenum" placeholder="Phone Number">
			<div id="result6"></div>  
            </div> 
			
		  </div>
		   <div class="form-group">
		  
			<div class="col-sm-4">
			<p>Previous School</p>
             <input type="text" class="form-control" id="spreviousschool" name="spreviousschool" placeholder="Name of previous school">
			 
            </div>
            <div class="col-sm-4">
			<p>class assign</p>
             <?php
          echo " <select class='form-control' id='s2_multi_value' name='sclass' onchange='prbSelect(this);' ><option value=''>Select class</option>";
          foreach ($mysqli->query($sql3) as $row) {
          echo "<option value=$row[class_id] >$row[classname] ($row[sectionname])</option>";
           }?>
			 </select>
			
			<div id="result7"></div>  
            </div>
			
		  <div class="col-sm-4">
			<p>Parent name</p>
               <?php
          echo " <select class='form-control' id='s3_multi_value' name='sparent' onchange='prbSelect(this);' ><option value=''>Select class</option>";
          foreach ($mysqli->query($sql4) as $row) {
          echo "<option value=$row[parent_id] >$row[fname] $row[middlename] $row[lname] ($row[phone])</option>";
           }?>
			 </select>
				  <input type="hidden" name="btype[]" value="" />
			<div id="result8"></div>
            </div> 			
		   </div>


           <!-- /.row-spacer -->

         <!-- /.row -->

          <!-- /.row-spacer -->
          

        </div> 
		
		
		
		
		
		<div class="portlet-content">
		
		
<div class="col-sm-4">
 
		  </div>
		  <div class="col-sm-2">
 
		  </div>
		  <div class="col-sm-2">
		  <?php if($_SESSION['login_user']==true&& $r_session2 =='Admin' || $r_session2 =='Standard' ){ echo ' 
 <button type="submit" id="form1" class="btn btn-secondary btn-block btn-lg">
          SUBMIT&nbsp; <i class="fa fa-play-circle"></i>
          </button>
		   ';
}
?>  
		  </div>
</div>

Open in new window


this is the jquery
<script>
 $( document ).ready(function() {
    $(function(){
        $('#form1').on('click',function(e){
            e.preventDefault();  // do not allow the default form action
             var form = $(this)[0].form;
             var data = $(form).serialize();
			 
		  
			
            $.ajax({
                method: "POST",
                url: "orgprocess.php",
                data: data
				})
			
			 
		
			 .done(function( data ) {  // capture the return from process.php
                    var obj = $.parseJSON( data );
                    var firnamevalid = obj.sfvalid;
					 var lasnamevalid = obj.slvalid;
					  var agevalid = obj.sagevalid;
					  var classvalid = obj.sclassvalid;
					   var parentvalid = obj.sparentvalid;
					  var phonevalid = obj.sphonevalid;
					  var phonemessage = obj.msg_sphone;
					   var classmessage = obj.msg_class;
					   var parentmessage = obj.msg_parent;
					  var agemessage = obj.msg_sage;
					  var addressvalid = obj.saddrevalid;
					  var sexvalid = obj.ssexvalid;
					   var entryvalid = obj.entryerrorvalid;
					    var successval = obj.successvalid;
						 var successmessage = obj.success;
					    var entrymessage = obj.msg_entryerror;
					  var sexmessage = obj.msg_sex;
					   var addressmessage = obj.msg_saddress;
					var firmessage = obj.msg_sfirname;
					var lasmessage = obj.msg_slasname;
	
	
	

                    if(firnamevalid == 1){  // place results on the page
					     $('input[name="sfname"]').removeClass('textBoxError');
                        $('#result').html('<div  class="valid"></div>');
                    } else {
						 $('input[name="sfname"]').addClass('textBoxError');
                        $('#result').html('<div class="error">'+firmessage+'</div>');
					
                    }
					if(lasnamevalid == 1){  // place results on the page
					     $('input[name="slname"]').removeClass('textBoxError');
                        $('#result2').html('<div  class="valid"></div>');
                    } else {
						 $('input[name="slname"]').addClass('textBoxError');
                        $('#result2').html('<div class="error">'+lasmessage+'</div>');
					
                    }
					if(sexvalid == 1){  // place results on the page
					     $('select[name="ssex"]').removeClass('textBoxError');
                        $('#result3').html('<div  class="valid"></div>');
                    } else {
						 $('select[name="ssex"]').addClass('textBoxError');
                        $('#result3').html('<div class="error">'+sexmessage+'</div>');
					
                    }
					if(addressvalid == 1){  // place results on the page
					     $('input[name="saddress"]').removeClass('textBoxError');
                        $('#result4').html('<div  class="valid"></div>');
                    } else {
						 $('input[name="saddress"]').addClass('textBoxError');
                        $('#result4').html('<div class="error">'+addressmessage+'</div>');
					
                    }
					if(agevalid == 1){  // place results on the page
					     $('input[name="sage"]').removeClass('textBoxError');
                        $('#result5').html('<div  class="valid"></div>');
                    } else {
						 $('input[name="sage"]').addClass('textBoxError');
                        $('#result5').html('<div class="error">'+agemessage+'</div>');
					
                    }
					if(phonevalid == 1){  // place results on the page
					     $('input[name="sphonenum"]').removeClass('textBoxError');
                        $('#result6').html('<div  class="valid"></div>');
                    } else {
						 $('input[name="sphonenum"]').addClass('textBoxError');
                        $('#result6').html('<div class="error">'+phonemessage+'</div>');
					
                    }
					if(classvalid == 1){  // place results on the page
					     $('input[name="sclass"]').removeClass('textBoxError');
                        $('#result7').html('<div  class="valid"></div>');
                    } else {
						 $('input[name="sclass"]').addClass('textBoxError');
                        $('#result7').html('<div class="error">'+classmessage+'</div>');
					
                    }
					if(parentvalid == 1){  // place results on the page
					     $('input[name="sparent"]').removeClass('textBoxError');
                        $('#result8').html('<div  class="valid"></div>');
                    } else {
						 $('input[name="sparent"]').addClass('textBoxError');
                        $('#result8').html('<div class="error">'+parentmessage+'</div>');
					
                    }
					if(entryvalid == 1){  // place results on the page
					    
                        $('#result9').html('<div  class="valid"></div>');
                    } else {
                        $('#result9').html('<div class="error">'+entrymessage+'</div>');
					
                    }
					
                  
					if(successval == 0){  // place results on the page
					 $('#result10').html('<div class="error2">'+successmessage+'</div>').show().delay(2000).fadeOut();
					//$('#s2_multi_value').val('').trigger('change'); 
					$("#form8")[0].reset();
					 window.location.reload(true); 
                    }
                });
        });
    });

	});
	 
</script>

Open in new window


this is the php
<?php
include('schconfigure.php');
if(isset($_POST)){
    $sfirstname = $_POST['sfname'];
	 $slastname = $_POST['slname'];
	  $smiddlename = $_POST['smname'];
	   $previousschool = $_POST['spreviousschool'];
	  $stusex = $_POST['ssex'];
	   $stuaddress = $_POST['saddress'];
	    $stuage = $_POST['sage'];
		$sphonenumber = $_POST['sphonenum'];
		$classassign = $_POST['sclass'];
		$studentparent = $_POST['sparent'];
		//$uplo = $_FILES['fupload']['name'];
	

	//$tealname = $_POST['tlasname'];

/* $chk='';  
   foreach($phone as $chk1)  
      {  
          $chk .= $chk1.",";  
      }   */

   	
    $sfvalid =1;
	 $sagevalid =1;
	  $sclassvalid =1;
	   $sparentvalid =1;
	  $sphonevalid = 1;
	   $msg_sphone = '';
	    $msg_class = '';
		 $msg_parent = '';
	 $msg_sage = '';
	 $saddrevalid =1;
	$slvalid =1;
	$ssexvalid =1;
	$msg_sfirname = '';
	$msg_saddress = '';
	$msg_sex = '';
	$msg_slasname = '';
	$msg_entryerror= '';
     $entryerrorvalid = 1; 
   $successvalid = 1;
	$success = '';
	
	if (empty($sfirstname)) {  // test for valid email
        $msg_sfirname = " * first name is require.";
        $sfvalid = 0;  // if bad, set valid flag to 0
		
    }
	if (empty($slastname)) {  // test for valid email
        $msg_slasname = " * last name is require.";
        $slvalid = 0;  // if bad, set valid flag to 0
		}
		if (empty( $stusex)) {  // test for valid email
        $msg_sex = " * gender is require.";
        $ssexvalid = 0;  // if bad, set valid flag to 0
		}
		if (empty($stuaddress)) {  // test for valid email
        $msg_saddress = " * address is require.";
        $saddrevalid = 0;  // if bad, set valid flag to 0
		}
		if (!empty($stuage)) {
		if(!is_numeric($stuage)){
		$msg_sage = " * enter only number.";
        $sagevalid = 0;	
		}else{
		$sagevalid = 1;
		}
        }
		 if(!empty($sphonenumber)){
		if(!is_numeric($sphonenumber)){
		$msg_sphone = " * enter only number.";
       $sphonevalid= 0;	
		}else if(strlen($sphonenumber) != 10){
		$msg_sphone = " *invalid phone number.";
		$sphonevalid= 0;	
		}else{
		$sphonevalid= 1;
		}
        }
       if (empty($classassign)) {  // test for valid email
        $msg_class = " * class is require.";
        $sclassvalid = 0;  // if bad, set valid flag to 0
		}	
       if (empty($studentparent)) {  // test for valid email
        $msg_parent = " * parent name is require.";
        $sparentvalid = 0;  // if bad, set valid flag to 0
		}			
	
	
	 
	 if($msg_sfirname=='' and $msg_slasname=='' and  $msg_sex=='' and $msg_saddress=='' and $msg_sage=='' and $msg_sphone=='' and $msg_class=='' and  $msg_parent==''){
 $qu = mysqli_query($mysqli, "SELECT * FROM studentinfo WHERE fname='$sfirstname' AND mname='$smiddlename' AND lname= '$slastname' AND classid='$classassign'");


 if(mysqli_num_rows($qu) >= 1){	

       $msg_entryerror = "  $sfirstname $smiddlename $slastname already exist in the class selected.";
       $entryerrorvalid =0;
	    $successvalid = 1;
	
	  
	 }else{
		  /* $target_dir = "picture/";
       $target_file = $target_dir . basename($_FILES["fupload"]["name"]);
       $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
	   $check = getimagesize($_FILES["fupload"]["tmp_name"]);
	   
	   if($check == false ) {
	   $imageerror = "The file selected is not an image";}else{  
		   
	 move_uploaded_file($_FILES["fupload"]["tmp_name"], $target_file);  
		  */
		 $query =mysqli_query($mysqli,"insert into studentinfo(parent_id,fname,mname,lname,sex,age,address,phone,previousschool,classid) values ('$studentparent','$sfirstname','$smiddlename','$slastname',' $stusex ','$stuage',' $stuaddress ','$sphonenumber','$previousschool','$classassign')");	
       $success ="form submitted successifully";
       $successvalid = 0;
    } 
	 }   

	
		
    $result = array('sfvalid' => $sfvalid,'success' => $success,'successvalid' => $successvalid,'msg_entryerror' => $msg_entryerror,'entryerrorvalid' => $entryerrorvalid,'msg_parent' => $msg_parent,'sparentvalid' => $sparentvalid,'msg_class' => $msg_class,'sclassvalid' => $sclassvalid,'msg_sphone' => $msg_sphone,'sphonevalid' => $sphonevalid,'sagevalid' => $sagevalid,'msg_sage' => $msg_sage,'msg_saddress' => $msg_saddress,'saddrevalid' => $saddrevalid,'msg_sex' => $msg_sex,'ssexvalid' => $ssexvalid,'slvalid' => $slvalid,'msg_slasname' => $msg_slasname,'msg_sfirname' => $msg_sfirname);  // create an array to be converted to json

    echo json_encode($result);  // echo out json encoded response 
}
?>
   
	

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

to upload a file you can use the FormData() which is supported in all browsers and in IE from version 10.

This MDN Article discusses how to use it for files
var formData = new FormData();

formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"

// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);

// JavaScript file-like object
var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

formData.append("webmasterfile", blob);

var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);

Open in new window


You can use jQuery like so
var form = $('form')[0]; // Or select using id / class
var formData = new FormData(form);
$.ajax({
    url: 'path/to/your/script',
    data: formData,
    type: 'POST',
    contentType: false, 
    processData: false, 
    // Reset of AJAX request as normal
});

Open in new window

Avatar of Moses Dwana
Moses Dwana

ASKER

thank for the reply julian. however, i am some how confuse how to use it in my script. currently  this is the script sending the data:
how do i change this to enable me send file and data?
$('#form1').on('click',function(e){
            e.preventDefault();  // do not allow the default form action
             var form = $(this)[0].form;
             var data = $(form).serialize();

Open in new window


i am also receiving return from the server like  the scrip below. how do i also change it to enable me achieve my objective?

thanks for the help
 .done(function( data ) {  // capture the return from process.php
                    var obj = $.parseJSON( data );
                    var firnamevalid = obj.sfvalid;
					 var lasnamevalid = obj.slvalid;
					  var agevalid = obj.sagevalid;
					  var classvalid = obj.sclassvalid;
					   var parentvalid = obj.sparentvalid;

Open in new window

Just do this - as per my earlier post create a new FormData() object passing your form to it.
$('#form1').on('click',function(e){
            e.preventDefault();  // do not allow the default form action
             var form = $(this)[0].form;
             var data = new FormData(form);

Open in new window

wow !!!! thank very mush Julian. I am getting signer now, but only this code not working working (it use in the php file to check whether selected is an image). if i comment it, i get signer that it is working.
i need this code to check whether the file selected is an image or not I don't know why it's not working.
$check = getimagesize($_FILES["fupload"]["tmp_name"]);

Open in new window

put this line in your code

echo "<pre>" . print_r($_FILES, true) . "</pre>";

Open in new window


Paste the result here
sorry Julian, everything working fine now. I was not selecting the image.
thanks very mush!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
You are welcome.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.