0

My problem is that my script doesnt upload the pic on serv and insert it into database when i use ajax submit for some reason. If i submit form with php action="file.php" it works. Here are my ajax script and php one.I dont see where the problem is and why it works with php submit and not working with ajax. Thnx in advance.

<script>
$(function() {
//twitter bootstrap script
    $("button#submit").click(function(){
            $.ajax({
            type: "POST",
        url: "engine/app/process.php",
        data: $(\'form.edit\').serialize(),
        dataType:\'json\',
            success: function(data){
                    $("#bday").html(data.a)
                     $("#locatie").html(data.b)
                     $("#descriere").html(data.c)
                     $("#interes").html(data.d)
                     $("#status").html(data.e)
                     $(".img").html(data.f)

                   $("#myModal").modal(\'hide\');    
                },
        error: function(){
            alert("failure");
            }
              });
    });
});
</script>

php script

<?php
require_once('../core/dbconfig.php');
$dbc = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASS, DB_NAME);
$nume=$_POST['nume'];
$bday=$_POST['bday'];
$locatie=$_POST['locatie'];
$status=$_POST['status'];
$interese=$_POST['interese'];
$despre=$_POST['descriere'];
$id_user=$_POST['id_user'];

$query="Update `users` SET username='$nume',bday='$bday',Locatie='$locatie',Relatie='$status',Interese='$interese',Descriere='$despre' where id='$id_user' ";   
                                $result=mysqli_query($dbc,$query) or die("query failed: " . mysqli_error($dbc));


$path = '../../images/users/'.$id_user.'/'; 
if(!is_dir($path)){
  mkdir($path,0755);
}
    $valid_formats = array("jpg", "png", "gif", "bmp", "jpeg", "JPG");

            $name = $_FILES['img1']['name'];
            $size = $_FILES['img1']['size'];


            if(strlen($name))
                {
                    list($txt, $ext) = explode(".", $name);
                    if(in_array($ext,$valid_formats))
                    {
                    if($size<(1024*1024))
                        {
                            /*$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;*/
                            $actual_image_name=$id_user.'.'.$ext;
                            $tmp = $_FILES['img1']['tmp_name'];
                            if(move_uploaded_file($tmp, $path.$actual_image_name))
                                {
                                $queryz="Insert into Galerie (ID_User,Poza,Poza_Profil) VALUES ('$id_user','$actual_image_name',1)";    
                                $resultz=mysqli_query($dbc,$queryz) or die("query failed: " . mysqli_error($dbc));                              
                                }
                            else
                                echo "failed";
                        }
                        else
                        echo "Image file size max 1 MB";                    
                        }
                        else
                        echo "Invalid file format..";   
                }   



echo json_encode(array("a" => $bday, "b" => $locatie,"c" => $despre,"d" => $interese,"e" => $name,"f" => ""));
?>
1

2 Answers 2

1

The serialize method puts your form fields data in a string complying to the application/x-www-form-urlencoded content type used to submit forms to servers for processing, while files are submitted in requests encoded in the multipart/form-data content type, so, serialize ignores file inputs.

You should use formData

var form = new FormData(document.getElementById('your_frm_id'));
var file = document.getElementById('img1').files[0];
    if (file) {
        $('#sent_progress').show();
        form.append('img1', file);
    }

In ajax use

data: form,

Read More here https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

Or you can use some Jquery Plugin to upload your file with form hope it will help

Sign up to request clarification or add additional context in comments.

1 Comment

thnx, it was good info but i couldnt modify my script and i just made new one for upload image. So practicly on 1 submit i call 2 functions one for normal infos and 1 for upload :)
-1

With only Ajax request you can't upload the file to the server. A Better option is use jQuery Form

This links also includes some example codes, follow the documentation and achieve what you want.

Take a look how to implement jQuery Form plugin, on Ajax based image upload

2 Comments

Thnx, i added one more script for upload image. Coudnt modify mine i'm not that good at ajax and i wanted to keep the json return too. But it works with 2 scripts too so thnx for help :).<script type="text/javascript" src="js/jquery.form.js"></script> <script type="text/javascript" > $(document).ready(function() { $("#imageform").ajaxForm({ target: \'#preview \' }) }); </script>
@Downvoters may i know what is the reason for down vote here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.