php – How to send array files via ajax?

Question:

Well folks I have a script that inserts the posts into the database now I'm trying to upload images along with the post I'm trying problems sending the input file array to the file where I'm going to handle the upload how can I do this ?

Script that adds posts

  <script>
    $(function() {
    $(".submit_button").click(function() {
        var textcontent = $("#opiniao").val();
        id_usuario = "<?php echo $_SESSION['user_id'] ?>";
        var dataString = 'id_estabelecimento=<?php echo $row->id; ?>&user_id='+id_usuario+'&opiniao='+textcontent;
        if(textcontent==''){
            alert("Por favor escreva uma opinião..");
            $("#opiniao").focus();
        }else{
            if(id_usuario == ''){
                alert("Para escrever uma opinião precisar estar logado aceda ao menu login para entrar na sua conta")
            }else{
                $("#flash").show();
                $("#flash").fadeIn(400).html('<span class="load">Aguarde por favor..</span>');
                $.ajax({
                    type: "POST",
                    url: "ajax/processa_post.php",
                    data: dataString,
                    cache: false,
                    success: function(html){
                        $("#show").after(html);
                        document.getElementById('opiniao').value='';
                        $("#flash").hide();
                        $("#opiniao").focus();
                    }  
                });
            }
        }
        return false;
    });
});
</script>

HTML form

<form  method="post" name="form" action="" enctype="multipart/form-data" >
<input type="hidden" name="valida" id="valida" value="ok" />
    <div id='share-container'>
    <section class="container" style="margin:0px 0px 20px 0px; border-radius: 2px;">
        <h3>Opiniões</h3>
        <table border="0" width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <td valign="top">
                    <textarea style="border:none;" placeholder="Em que estás a pensar?" id="opiniao" name="opiniao"></textarea>
                </td>   
           </tr>
            <tr>
                <td valign="top">
                    <div style="background-color:#FFF;">
                        <div style="float:right; padding:5px 5px 5px 5px;"><input type="submit" value="Publicar" name="submit" class="submit_button"/></div>
                        <div style="padding:15px 5px 5px 5px; float:right;"><input id="fb" name="fb" type="checkbox" />Facebook</div>
                        <div style="padding:15px 5px 5px 5px; float:right;"><input type="checkbox" />Twitter</div>
                        <label style="padding:16px 20px 5px 5px; float:right;" for="fotos_post">
                            <img src="img/fotos.png" alt="">
                        </label>
                        <input name="fotos_post[]" id="fotos_post" class="upload_post" type="file" multiple="" />
                    </div>
                </td>
           </tr>
        </table>
    </section>
    </div>
    <!--//one-half-->
</form>

Process_posts.php file

<?php
session_start();
require_once("../gtm/bd/funcoes.php");
ligarBd();  
mysql_query("SET NAMES 'utf8'");

if(isset($_POST['opiniao'])){
    if(!isset($_SESSION['user_id'])){
        echo "
        <script>
            window.location = 'http://sabeonde.pt/index.php?m=login';
        </script>
        ";
    }else{
        mysql_query("INSERT INTO posts (user_id, estabelecimento_id, opiniao, data) VALUES('".$_REQUEST['user_id']."', '".$_REQUEST['id_estabelecimento']."', '".$_REQUEST['opiniao']."', now()) ");  
        $fetch= mysql_query("SELECT * from posts where estabelecimento_id='".$_REQUEST['id_estabelecimento']."' order by data desc");
        $row=mysql_fetch_array($fetch);
    }
}
?>
<section class="container" style="margin:15px 0px 0px 0px;">
<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td valign="top">
           <div style="float:left; margin:0px 0px 10px 0px; "><img width="50" height="50" src="<?php echo $_SESSION['user_foto'] ?>"/></div>
           <h3 style="float:left; margin:15px 0px 0px 10px;"><?php echo utf8_encode($_SESSION['nome']); ?></h3>
        </td>
    </tr>
</table>      
<p><?php echo utf8_encode($row['opiniao']); ?></p>
</section>
<table border="0" bgcolor="#E9EAED" width="100%" cellpadding="0" cellspacing="0">
    <tr>
        <td valign="top" width="10%">
            <div style="padding:15px 5px 5px 20px;"><img width="33" height="33" src="<?php echo $_SESSION['user_foto'] ?>"/></div>
        </td>
        <td valign="top" width="90%">
            <div style="padding:15px 20px 5px 5px;"><textarea style="border:none; width:100%; height:33px;" placeholder="Escreve um comentário..." id="" name=""></textarea></div>
        </td>
    </tr>
</table>

In this file I want to retrieve the files that were chosen for upload via $_FILES

Answer:

I don't know if I understand very well if you want from AJAX to PHP or the other way around and that's why I put both:

1-To send from JAVASCRIPT you have to turn the array into a json string:

$.ajax({
    url: 'request/exemplo.php',
    data: JSON.stringify(fields),
    type: "POST"....

In php just get it from $_POST, but don't forget the json_decode($post['variable name']).

2-In the response from… process_post.php, return your array like this:

echo json_encode(array());

then in AJAX success put:

...
success: function (data) {
   var json_object = JSON.parse(data);
   (agora é só utilizar dentro do javascript)
}
...
Scroll to Top
AllEscort