Tuesday 30 September 2014

Update or save file using ajax request

How to upload an image using "ajax reguest" in PHP

Note: We need to pass atleast one parameter otherthan file upload control. Then only the ajax file upload will work properly in PHP.

/*================Ajax request from HTML Page=================*/
function SaveImage(vId){
debugger;
   var vCategory=$("#hdnCategory").val();
   //Creating object for form data to collect control's data from HTML page
                   var m_data = new FormData();
   m_data.append('desc', $("#txtDescription").val());
                  //collecting data from file upload control
   m_data.append('file_attach', $('input[name=file_attach]')[0].files[0]);
m_data.append('rowId',vId);
m_data.append('category',vCategory);
            $.ajax({
              url: 'contact_me.php',  //PHP page url
              data: m_data,
              processData: false,
              contentType: false,
              type: 'POST',
              dataType:'json',
              success: function(response){
 alert('Image inserted successfully');
              },
 error:function(err){

  alert('Something went wrong'); }
            });



}

/*======================Server code======================*/

<?php
if($_POST)
{
   $output="";
   $conn=mysql_connect("localhost","root","");
   $db=mysql_select_db("<db name>");
   mysql_query("SET NAMES 'utf8'");
   mysql_query('SET CHARACTER SET utf8');
   if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        $output = json_encode(array( //create JSON data
            'type'=>'error',
            'text' => 'Sorry Request must be Ajax POST'
        ));
        die($output);
    }
    $file_attached = false;
if(isset($_FILES['file_attach']))
{
   //Id to update
   $rowId  = $_POST["rowId"];
$file_tmp_name  = $_FILES['file_attach']['tmp_name'];
   $file_content = file_get_contents($file_tmp_name);
//Here iam saving the image in BLOB datatype in MySql database. so iam converting the image into //base64.
   $encode=base64_encode($file_content);
        $sql_edit="<your query here>";
   $sql=mysql_query( $sql_edit);
echo json_encode("File uploaded successfully");
}else{
echo json_encode("No file to upload");
}
echo json_encode($output);

}
?>

//End of Server code
References: http://www.sanwebe.com/2014/04/ajax-contact-form-attachment-jquery-php

No comments:

Post a Comment