Troutfisher
Troutfisher

Reputation: 69

Uploading image and data using ajax and php

I am trying to upload firstname, lastname, description and image path to MySql database. And move uploaded image to specific folder.

Here is my ajax function

formData = new FormData(addPeopleForm);
var file_data = $('input[type="file"]')[0].file;
formData.append("file", file_data);

$.ajax({
  type: "POST",
  url: "functions.php",
  contentType: false,
  cache: false,
  processData: false,
  data: {
    function: "savepeople",
    data: formData
  }, success: function(data){
      console.log(data);
      getPeople();
  }

});

functions.php

if(isset($_POST['function'])){
 $f = $_POST['function'];

 if($f == "savepeople"){
  require_once("config.php");   
  echo $_POST['firstname'];
  .
  .
  .

Upvotes: 1

Views: 1865

Answers (3)

Masivuye Cokile
Masivuye Cokile

Reputation: 4772

var formData = new FormData($(this)[0]);
var action = "savepeople";

    $.ajax({
        url  : 'functions.php',
    type : 'POST',
    data: {action:action,formData:formData},
    contentType: false,
    cache: false,
    processData:false,
    async : false,
    , success: function(data){
console.log(data);
getPeople();
}
});

functions.php

if(isset($_POST['action']) && $_POST['action'] == "savepeople"){


    //TO DO CODE
}

Upvotes: 0

Gaurang Sondagar
Gaurang Sondagar

Reputation: 311

you can not send directly image to php file with ajax call, you have to take form enctype="multipart/form-data" while form defination

and replace this code for file upload while ajax call

for appending file in formdata use below code

formData = new FormData(); //your form name 
var file_data = $('input[type="file"]')[0].file;
formData.append("file", file_data);
formData.append("function","savepeople"); // new variable for your php condition



$.ajax({
    url: "YOUR_FILE_PATH",
    type: "POST",
    data: formData,
    contentType: false,
    cache: false,
    processData: false,
    success: function(data) {
    // success operation here
    },

and on php side you have to use $_FILES['YOUR_FILE_NAME'] instead of $_POST['YOUR_FILE_NAME'] for accessing a uploaded file on server.

Upvotes: 1

Ravi Parmar
Ravi Parmar

Reputation: 81

you can try this code

$.ajax({
    type:'POST',
    url:'functions.php',     
    data:new FormData($('#my_form')[0]),
    cache: false,
    contentType: false,
    processData: false,
    success:function(msg)
    {
         console.log(msg);
    }
});
return false;

where #my_form is your form id

Upvotes: 0

Related Questions