0

I am using Laravel and i'm making an AJAX request. In the success event I wrote:

var name = response.filename;
var path = "<?php echo route('getImage', "name")?>";                        
document.getElementsByClassName("getImage")[0].setAttribute("src", path);

But it looks like on the second row the name variable is interpretated as text, not as variable. And the src's value is

http://localhost/bluedrive/drive/public/getimage/name;

How could I get this right?

4
  • 4
    You cannot call any PHP code from your JS. You must run the route function on the server side, return its result in the success response and set it as the image src. Commented Jan 3, 2016 at 13:37
  • Aren't you using blade? Commented Jan 3, 2016 at 13:50
  • 2
    Not strictly true @AnatoliyArkhipov if OP is putting their javascript in their blade templates. Commented Jan 3, 2016 at 13:54
  • Oh, yes, looks like I'm incorrectly understand the question. I thought that the given code is a part of some success callback in JS Commented Jan 3, 2016 at 17:13

1 Answer 1

1

You could do the following, assuming the javascript is in your blade templates.

var name = response.filename;
var path = "{{ route('getImage', ['image_name']) }}";
document.getElementsByClassName("getImage")[0].setAttribute("src", path.replace('image_name', name));

I think your best option however is to return the full image src back in your ajax response. So your controller may look something like this

Input::file('image')->move('/my/filepath', $filename);

return response()->json([
    'image_url' => url('/my/filepath/' . $filename),
]);

This returns the url for the image which you can then use in your javascript as below

.success(function(response) {
    document.getElementsByClassName("getImage")[0].setAttribute("src", response.image_url);
});
Sign up to request clarification or add additional context in comments.

Comments

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.