0

I'm trying to upload an image through ajax in laravel.

I have this code for the ajax.

$("#stepbutton2").focus(function(){
            var formData = new FormData($("#form1"));
            $.ajax({
                url: '/nominations/upload/image',
                data: formData,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function(data){
                    alert(data.url);
                },
                error: function(err){
                    alert(err);
                }
            });
        });

and php file:

public function image(){
        $file = Input::file('largeImage');
        $ext = $file->getClientOriginalExtension();
        $newName = md5(time()).".$ext";

        $path= "uploads/{$this->getDate()}";
        $file->move($path, $newName);
        $imageUrl = $path.'/'.$newName;
        return Response::json(["success"=>"true", "url"=>$imageUrl]);
    }

#stepbutton2 is a button type and not submit. I'm getting the alert [Object object] but it should be the uploaded URL. The markup is something like:

<form id='form1'>
  <input type='file' id='largeImage' name='largeImage'>
  <input type='button' id='stepbutton2'>
</form>

where did I go wrong? I need to use this url to populate another field in the same form and continue filling the form to the next steps.

user1012181
  • 8,648
  • 10
  • 64
  • 106
  • Crap, I closed to the wrong question, here is the correct one http://stackoverflow.com/questions/14495296/upload-file-through-ajax – Musa Feb 06 '15 at 17:59
  • I used their solution and till couldn't find the answer. That's why I asked it here again. – user1012181 Feb 06 '15 at 18:04
  • So you did `var formData = new FormData($("#form1")[0]);` and it didn't work? – Musa Feb 06 '15 at 18:06
  • no it didn't help me. – user1012181 Feb 06 '15 at 18:07
  • Well it looks like your call is triggering the error callback, try using console.log instead of alert. – Musa Feb 06 '15 at 18:11
  • The error message is this: `{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Call to a member function getClientOriginalExtension() on a non-object","file":"C:\\wamp\\www\\laravel\\app\\controllers\\UploadController.php","line":9}}` – user1012181 Feb 06 '15 at 18:16
  • 1
    I have no Idea what that means, so I've reopened the question. – Musa Feb 06 '15 at 18:18
  • What about `var fd = new FormData(); fd.append("largeImage", jQuery('#largeImage')[0].files[0]);` ? – Mohebifar Feb 06 '15 at 19:15
  • Maybe there was a redirect, what do you get if you `var_dump($_SERVER['REQUEST_METHOD'])` – Musa Feb 06 '15 at 22:32

0 Answers0