Przemek Wojtas Przemek Wojtas - 1 month ago 8
Ajax Question

Retrieve html file from database once image is clicked in ajax

I am using laravel framework and I am looking to implement a feature so that when image on a page is clicked it loads it's source code and display that html file on the page. Image location and html file location are on the same database table. I am very new with ajax so could anyone tell me what function to use/ or give me an example so I can work on it. Thank you.

So this is how I want it to go:

Click on image>Request html from database>Display html in "" on the same page

View::

@extends('layouts.master')

@section('title', 'Best programmer ever')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link href="{{asset('/js/template.js')}}" rel="javascript" type="text/javascript">
@section('content')
@endsection
@section('template')

<div class= "template_class">
<a class="content-link" href="templates/template1.html">
<img id = "image" src="{{ asset($template->image )}}"/>
</a>
</div>
@show


JS:

$(function(){
$('.content-link').click(function(e){
e.preventDefault();
$('.content').load(this.href)
.fail(function()( alert('Oops...something went wrong')));
});
});


DB Table::

Schema::create('templates', function (Blueprint $table) {
$table->increments('id');
$table->string('image');
$table->string('file');
$table->timestamps();
});


DB Entry::

DB::table('templates')->insert(['image' => 'img/1.jpg', 'file' => 'templates/template1.html']);


Example of template which is to be displayed in a div::

<!DOCTYPE html>

<html>
<head>
<title>Template 1</title>
<link href="css.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="content">Insert your content here</div>


</body>
</html>

Answer

Wrap the image in an <a> and use the href to make request for correct html

<div class = "template_class">
  <a class="content-link" href="/path/to/get/html/{{ asset($template->id )}}"> 
        <img id = "image" src="{{ asset($template->image )}}"/>
  </a>
</div>

Then in script

$(function(){
   $('.content-link').click(function(e){
       e.preventDefault();
       $('.content').load(this.href)
                    .fail(function()( alert('Oops...something went wrong');});
   });
});