Dynamic Image Toggle Feature with Laravel and Javascript

Currently, I'm working on developing an eCommerce Shopping Site using Laravel 5.0 for my final year project. Although there is still a long way to go, I have made progress by creating a product show page.

Here is a snippet of my controller:

     public function getView($id)
{
    return view('store.show')->with('products', Product::find($id))->with('categories',Category::all())->with('db',Product::all())->with('options', Gambar::where('product_id','=',$id)->lists('name', 'img'));
}

One particular code I'd like to point out is lists('name', 'img') at the end of the line. This code is used to list out the column names and image values.

Everything was working perfectly, except for the need to create a dropdown list with image changes on selection.

Below is the code for my dropdown list and image swap:

    <div class="form-group">

     {!! Form::open(array('url' => 'foo/bar')) !!}
     {!! Form::label('Link Category') !!}<br />
     {!! Form::select('product_id',(['0' => 'Select an Option'] + $options),null,['class' => 'form-control', 'id' => 'dlist', 'onChange' => 'swapImage()']) !!}
     {!! Form::close() !!}

     <script type="text/javascript">
     function swapImage(){
     var image = document.getElementById("imageToSwap");
     var dropd = document.getElementById("dlist");
     image.src = dropd.value;
     };
     </script>
    </div>

Then, there's the code where the image will appear based on the selection (products->image is the main image, not one selected from the dropdown list):

 <img id="imageToSwap" src="{{asset($products->image)}}"  />

The issue I faced was that while the List flow in the controller worked, it gave this output in the Chrome view source:

<img id="imageToSwap" src="img/upload/20-3-291-image-1.jpg"  />

The image did not appear on the page as it should have. It should have displayed like this:

<img id="imageToSwap" src="localhost:8000/img/upload/20-3-291-image-1.jpg"  />

My question is, how can I return the "img" with Laravel asset {{asset()}}, so that the image can be displayed perfectly?

Answer №1

The issue at hand is the communication between Laravel and JavaScript.

As you mentioned, when you use lists('name', 'img'), the asset prefix is not included.

Therefore, when you execute image.src = dropd.value;, the image source lacks the asset prefix.

I can see two solutions:

  • Either you preprocess your list before sending it:
    lists('name', 'img')->map(asset)
    (using the map method --not certain if it's supported in Laravel 5.0)
  • Or you can add it in your JavaScript:
    image.src = "{{asset()}}/" + dropd.value;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlinked Checkbox in Angular Bootstrap Modal Controller

I am currently utilizing the modal feature from Bootstrap 3's Angular fork, and I am facing an issue with using a checkbox within the modal and retrieving its value in my main controller. The checkbox value is properly bound in the view but not in th ...

Issue with relative templateUrl in Angular 2 not resolving paths

As I embark on creating my first Angular 2 app, I'm faced with the task of setting my template in an HTML file using `templateUrl`. Currently, both the component.ts and view.html are stored in the same folder under src/ directory. Here's what I ...

What is the most efficient way to retrieve the accurate current date from the server using nodeJS?

I am currently working on filtering the data being sent back to the user. My filter criteria includes the date, month, and year. While I have successfully filtered by date and month, I am encountering unexpected results when filtering by year. Below is ...

Conditional compilation in Laravel Mix allows for specific code blocks to be

I'm currently working on a Laravel project and I need to introduce some conditional statements. Within the root folder of the project, there's a file called module_statuses.json which contains JSON variables like this: { "Module1": true, ...

Troubleshooting an issue with window.close in AngularJS

I'm struggling to properly execute the window.close function without encountering the error message below: Scripts may close only the windows that were opened by it. Here is the structure of my application: HTML: <html ng-app="mynewAPP" ng-co ...

Sluggish animation performance in threejs when using requestAnimationFrame within a class

Experiencing choppy animation on the JSFiddle? When trying to move your mouse or interact with the content, you may have come across issues with the classing related to requestAnimationFrame(this.animation). Initially, it didn't work as expected, but ...

Oops! Vue.js is throwing a compile error involving unused variables and undefined variables

I'm currently working on developing a new Vue.js component, but I'm encountering an error when launching the application. The specific error message is displayed below: https://i.sstatic.net/0MQxl.png <template> <div class="hello" ...

How can I use console.log to display a message when a variable reaches a specific value?

As a beginner coder, I am struggling to find the solution to this coding issue. Here is the code snippet that I have attempted: var X = "Angry"; if X = "Angry" console.log(X is Angry) After running this code, I encountered an error message specifically p ...

Requesting CORs on Web API version 2.0

After enabling CORs on a Web API, I encountered an issue where GET and POST requests were failing on Chrome. Interestingly, the GET request worked fine on MS Edge, but the POST request threw two error messages in the console: The request could not be proc ...

Using jQuery cookies to dynamically change the body id during page loading

Is it possible to dynamically change the body ID during page load? I recently created an application that successfully changes the body ID. Now, I'm interested in detecting the body ID that I have already selected during page loading. Below is the c ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

Is there a way to change the visibility of a form element within a directive with the help of

Consider a scenario where you have a basic form as shown below: <form ng-submit="methods.submit(formData)" ng-controller="diamondController" name="diamond" novalidate> <help-block field="diamond.firstName"></help-block> <input ...

django div auto refresh

Whenever I submit a form, the content of console.html is supposed to change. I tried to use the code below to refresh the page, but it doesn't seem to refresh console.html: Javascript function autorefresh() { // auto refresh page after 1 sec ...

Submitting JSON data using JavaScript

My goal is to send a username and password to my backend server. However, I am encountering an issue where the data does not successfully reach the backend when using the following code: function register() { var text = '{"username":"admin1","pass ...

Learning how to retrieve the ID and Title using Jquery

Hello, I'm having an issue with my UL and LI elements. They work fine with the click function, but I can't seem to get the title when trying to access it. Example: // Works fine, but can't access the title $("#list li").on('click&ap ...

Implementing conditional redirects in react-router-dom v6

Currently facing an issue with react router dom@6. I'm trying to redirect users to other pages once they are logged in. However, when using the Navigate component, an error is thrown: "[Navigate] is not a component. All component children of Rou ...

Display everything when an option is clicked

I have a filter that is working perfectly. When I select a specific category, it filters out only rows with that category. However, I am stuck on how to display all rows again after clicking on the first option. My objective is to show all rows when "Categ ...

Troubleshooting an Angular.js "Hello World" application that is malfunctioning

I've been trying to get a simple Hello World app working by following different tutorials, but it doesn't seem to be functioning correctly. I've double-checked my code and everything looks right to me. Could someone please assist me in troub ...

I am having trouble embedding YouTube videos with my code

Need a fresh pair of eyes on this code. Everything looks correct to me, but it's not functioning as expected. The entries are results from a search. function displayVideos(data) { var feed = data.feed; var entries = feed.entry || []; va ...

Can someone explain why the console.log(items) command seems to be executing twice

Item.find() .then(function (items) { if (items.length === 0) { Item.insertMany(defaultItems) .then(function () { console.log("Successfully Saved"); }) .catch(function (err) { console.l ...