0

I created a form where values are entered which will then be read by jQuery. At this point, the jQuery will make an ajax call to the PHP file that will have to upload the article to MySQL (which it already does). The problem is that I can not find a way to pass the tmp for the image to PHP to make it read.

First code: form

 <form class="form">
  <input type="text" id="titolo" placeholder="Titolo" name="post_title" />
  <input type="text" id="autore" placeholder="Autore" name="post_author"  />
  <input type="date" id="data" name="post_date" />
  <select id="categoria" name="category">
    // code php from mysql to select category               
  </select>
  <textarea id="article" name="post_content" rows="10" cols="30"></textarea><br/>             
  <label for="anteprima">Seleziona l'immagine di anteprima:</label><br/>
  <input type="file" accept="image/*" id="anteprima" name="post_image"/><br/>
  <input type="button" value="Upload Articolo" name="submit" class="invia" />
   <div id="public_article"></div>
 </form>

Read object jQuery:

$(".invia").click(function(e){ 
  e.preventDefault();
  var v1 = $('#titolo').val();
  var v2 = $('#autore').val();
  var v3 = $('#data').val();
  var v4 = $('#categoria').val();
  var v5 = $('#article').val();
  var v6 = $('#anteprima');

  // here control of the value if it's ok go to the $.post

 $.post("(//here the name of file php)", {titolo: v1, autore: v2 , date: v3, categoria: v4, rif_testo: 
 v5, rif_immagine: v6, cache:false})
        .done(function(dataResult){
            $("#public_article").html(dataResult);
        })
        .fail(function() {
            $("#public_article").html("error");
        }); 

});

I can't send the photo to PHP file and recover it via $_FILES.

Lucius
  • 1,246
  • 1
  • 8
  • 21
Mfoto94
  • 47
  • 5

1 Answers1

1

You can use FormData for this:

var formData = new FormData($(.form)[0]);


// now send it not using post but using ajax
    $.ajax({
        url: '//here the name of file php',
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

in PHP you would process it just like a normal form.

Daniel Resch
  • 584
  • 3
  • 12