How to render a mail with HTML variable? - laravel

I am trying to send email by html code.
I would like to include image and data on the blade template, but can't render the view.
current code:
MailTemplate.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class MailTemplate extends Mailable
{
use Queueable, SerializesModels;
public $subject = null;
public $template;
public $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($subject, $template, $data)
{
//
$this->subject = $subject;
$this->template = $template;
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$this->template = '<div><img src="{{ $message->embed(public_path('/assets/images/logo.png')) }}" ></div>';
return $this->subject( $this->subject)->view('emails.EmailTemplate');
}
}
EmailTemplate.blade.php
<html>
<body>
{!! $template !!}
</body>
</html>
result
current:
<html>
<body>
<div><img src="{{ $message->embed(public_path('/assets/images/logo.png')) }}" ></div>
</body>
</html>
//==============================================
**I want:**
<html>
<body>
<div><img src="embed swiftmailfile~~~~~~" ></div>
</body>
</html>
So, how can I return the view using HTML
so that it can be passed to the variable?

You can try this:
Just pass src to view
public function build()
{
$src = $message->embed(public_path('/assets/images/logo.png'));
return $this->subject( $this->subject)->view('emails.EmailTemplate', ['src' => $src]);
}
And then , render to view
<html>
<body>
<div><img src="{{ $src }}" ></div>
</body>
</html>

You are trying to render blade inside the mailable.
Instead, create the string using concatenation
$this->template = '<div><img src="' . $message->embed(public_path('/assets/images/logo.png')) . '" ></div>';

Related

Laravel Full Calendar

I'm trying to follow this tutorial https://laravelcode.com/post/laravel-full-calendar-tutorial-example-using-maddhatter-laravel-fullcalendar. I completed every steps but the calendar still does not appear, only the Laravel header and the "Full Calendar Example" writing but not the calendar itself or if I remove "extends('layout.php')" nothing appears. :( What could be the problem? I hope someone can give a quick answer. Sorry if it's a bad question here.
My code:
config/app.php
'providers' => [
.....
.....
MaddHatter\LaravelFullcalendar\ServiceProvider::class,
],
'aliases' => [
.....
.....
'Calendar' => MaddHatter\LaravelFullcalendar\Facades\Calendar::class,
]
database/migrations/CreateEventsTable
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEventsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->date('start_date');
$table->date('end_date');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop("events");
}
}
app/Event.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
protected $fillable = ['title','start_date','end_date'];
}
database/seeds/AddDummyEvents.php
use Illuminate\Database\Seeder;
use App\Event;
class AddDummyEvent extends Seeder
{
public function run()
{
$data = [
['title'=>'Demo Event-1', 'start_date'=>'2017-09-11', 'end_date'=>'2017-09-12'],
['title'=>'Demo Event-2', 'start_date'=>'2017-09-11', 'end_date'=>'2017-09-13'],
['title'=>'Demo Event-3', 'start_date'=>'2017-09-14', 'end_date'=>'2017-09-14'],
['title'=>'Demo Event-3', 'start_date'=>'2017-09-17', 'end_date'=>'2017-09-17'],
];
foreach ($data as $key => $value) {
Event::create($value);
}
}
}
routes/web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('events', 'EventController#index');
app/Http/Controllers/EventController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Calendar;
use App\Event;
class EventController extends Controller
{
public function index()
{
$events = [];
$data = Event::all();
if($data->count()) {
foreach ($data as $key => $value) {
$events[] = Calendar::event(
$value->title,
true,
new \DateTime($value->start_date),
new \DateTime($value->end_date.' +1 day'),
null,
// Add color and link on event
[
'color' => '#f05050',
'url' => 'pass here url and any route',
]
);
}
}
$calendar = Calendar::addEvents($events);
return view('fullcalendar', compact('calendar'));
}
}
resources/views/fullcalendar.blade.php
#extends('layouts.app')
#section('style')
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.css"/>
#endsection
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Full Calendar Example</div>
<div class="panel-body">
{!! $calendar->calendar() !!}
</div>
</div>
</div>
</div>
</div>
#endsection
#section('script')
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.js"></script>
{!! $calendar->script() !!}
#endsection
Unsure why it was left out of the tutorial, but they didn't have you set up a layout blade file. They also forgot to include jquery. If you change fullcalendar.blade.php to the following code it works.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<link rel="stylesheet" type="text/css"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet"
ref="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.css"/>
<body>
<div class="container" style="margin-top: 100px">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Full Calendar Example</div>
<div class="panel-body">
{!! $calendar->calendar() !!}
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.js"></script>
{!! $calendar->script() !!}
</html>
Look in the EventController in the calender() function
The return view() is trying to return "calender", change it to calendar to match the view name you created in views.

How to load model relationships inside an event Laravel 5.3

I have an event for when a new article is created. On another page I am listening for this event (VueJs and Laravel Echo), and then appending the newly created article to the articles list (actually unshifting), which then updates the view reactively. However, an article has an author which is related to the users table. I keep getting error and Vue keeps crashing because the article doesn't have an author attribute. Which is because the author is a relationship. I have tried putting $this->article->load('author') in the __construct method of the event itself, and I've tried using load('author') before sending the article to the event. Neither have worked at all. How can I maintain this relationship in the event so that it will be sent in the broadcast, in turn allowing Vue to access it as a property?
Template:
<template>
<div>
<div class="article-preview-container" v-for="article in articles">
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title"><a :href="article.slug">{{ article.title}}</a></h2>
</div>
<div class="panel-body">
<p class="lead">
<span class="glyphicon glyphicon-time"></span> {{ article.created_at }} |
<span class="glyphicon glyphicon-user"></span> {{ article.author.full_name }}
</p>
<div class="article-preview">
<img :src="article.main_image" :alt="article.title">
<p>{{ article.preview }}</p>
</div>
</div>
</div>
</div>
<infinite-loading :on-infinite="onInfinite" ref="infiniteLoading" spinner="spiral">
<span slot="no-more">
There are no more articles to display :(
</span>
</infinite-loading>
</div>
</template>
<script>
import InfiniteLoading from 'vue-infinite-loading';
export default {
mounted() {
Echo.channel('articles').listen('ArticleCreated', (event) => {
console.log(event.article.author);
this.articles.unshift(event.article);
});
},
data() {
return {
articles: [],
skip: 0,
};
},
methods: {
onInfinite() {
axios.get('/articles/' + this.skip).then(function (response) {
if(response.data.length > 0) {
this.articles = this.articles.concat(response.data);
this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
if(response.data.length < 5) {
this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
} else {
this.skip += 5;
}
} else {
this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
}
}.bind(this));
},
},
components: {
InfiniteLoading,
},
};
</script>
Event:
<?php
namespace App\Events;
use App\Article;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class ArticleCreated implements ShouldBroadcast {
use InteractsWithSockets, SerializesModels;
public $article;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(Article $article) {
$this->article = $article;
//tried $this->article->load('author')
//tried $this->article = $article->with('author')
//tried loading author using just $this->article->author
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn() {
return new Channel('articles');
}
}

Laravel 5.2.45 - empty $errors variable in views

Problem:
The $errors variable is empty in the views. There's talk that this has been fixed in 5.2 so hopefully the problem is on my end.
Environment:
Mac OS X
Laravel 5.2.45
The Codez:
Routes.php
Route::get('/', 'AlleleController#index');
Route::get('/register', function () {
return view('auth.register');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::get('/alleles', 'AlleleController#index');
Route::post('/allele', 'AlleleController#store');
Route::delete('/allele/{allele}', 'AlleleController#destroy');
AlleleController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Allele;
class AlleleController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
// All methods require authentication except index.
$this->middleware('auth', ['except' => ['index']]);
}
/**
* Root page.
*
* #return Response
*/
public function index() {
return view('welcome');
}
/**
* Create a new allele.
*
* #param Request $request
* #return Response
*/
public function store(Request $request) {
$allele = new Allele();
// Get all input as an array.
$input = $request->all();
// Validate input.
if ($allele->validate($input)) {
// Valid input. Write to database.
// The inserted model instance is returned.
$result = $allele::create($input);
if ($result) {
// Insert successful.
$message = array('message' => 'Data added!');
return view('home', $message);
} else {
// Insert failed. Send errors to view.
$errors = array('errors' => 'Error saving data.');
return view('home', $errors);
}
} else {
// Invalid input. Get errors.
$errors = $allele->errors();
// Send errors to view.
return view('home', $errors);
}
}
}
?>
HomeController.php:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
class HomeController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index() {
return view('home');
}
}
Model: Allele.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Allele extends Validation {
/**
* The attributes that are mass assignable.
*/
protected $fillable = ['allele'];
/**
* Validation rules.
*/
protected $rules = array (
'allele' => 'required|max:20',
);
}
Model: Validation.php
<?php
namespace App;
use Validator;
use Illuminate\Database\Eloquent\Model;
class Validation extends Model {
protected $rules = array();
protected $errors;
public function validate($input) {
// Make a new validator object.
$v = Validator::make($input, $this->rules);
// Check for failure.
if ($v->fails()) {
// Set errors and return false.
$this->errors = $v->errors();
return false;
}
// Validation passed.
return true;
}
// Retrieves the errors object.
public function errors() {
return $this->errors;
}
}
View: views/common/errors.blade.php
#if (count($errors) > 0)
<!-- Form Error List -->
<div class="alert alert-danger">
<strong>Whoops! Something went wrong!</strong>
<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
View: views/home.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Dashboard</div>
<div class="panel-body">
You are logged in!
</div>
</div>
</div>
</div>
</div>
<!-- Create New Allele -->
<div class="panel-body">
<!-- Display Validation Errors -->
#include('common.errors')
<!-- New Allele Form -->
<form action="{{ url('allele') }}" method="POST" class="form-horizontal">
{{ csrf_field() }}
<!-- Allele Name -->
<div class="form-group">
<label for="allele-name" class="col-sm-3 control-label">Allele</label>
<div class="col-sm-6">
<input type="text" name="allele" id="allele-name" class="form-control">
</div>
</div>
<!-- Add Allele Button -->
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button type="submit" class="btn btn-default">
<i class="fa fa-plus"></i> Add Allele
</button>
</div>
</div>
</form>
</div>
#endsection
All validation methods should be placed inside web middleware . I do not see any other error. Replace your route.php like this.
Route::group(['middleware' => ['web']], function ()
{
Route::get('/', 'AlleleController#index');
Route::get('/register', function () {
return view('auth.register');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::get('/alleles', 'AlleleController#index');
Route::post('/allele', 'AlleleController#store');
Route::delete('/allele/{allele}', 'AlleleController#destroy');
});

Flash data in Laravel 5

I'm trying to display flash data but it's not showing properly. It's showing:
{{ Session::get('flash_message') }}
but it should be the message
"Your article has been created"
What's wrong with my code? Thanks!
In my controller I have:
public function store(ArticleRequest $request)
{
Auth::user()->articles()->create($request->all());
\Session::flash('flash_message', 'Your article has been created');
return redirect('articles');
}
My app.blade.php is:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>App Name - #yield('title')</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="{{ elixir('css/all.css') }}">
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<div class="container">
#if(Session::has('flash_message'))
<div class="alert alert-success">{{ Session::get('flash_message') }}</div>
#endif
#yield('content')
</div>
#yield('footer')
</body>
</html>
In my route.php I have the following: Curly braces display content as string not variables.
<?php
Blade::setContentTags('<%', '%>'); // for variables and all things Blade
Blade::setEscapedContentTags('<%%', '%%>'); // for escaped data
Route::get('/', function() {
return 'Home Page';
});
Route::get('blade', function () {
return view('about');
});
Route::get('about', 'HelloWorld#about');
Route::get('foo', ['middleware' => 'manager', function() {
return 'this page may only be viewed by managers';
}]);
Route:resource('articles', 'ArticlesController');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
If you have this in your route.php:
Blade::setContentTags('<%', '%>');
then that means you cannot use curly brackets for blade content. Try this instead:
#if(Session::has('flash_message'))
<div class="alert alert-success">
<% Session::get('flash_message') %>
</div>
#endif
or simply remove the setContentTags() call from your route.php.
You can make a multiple messages and with different types.
Follow these steps below:
Create a file: "app/Components/FlashMessages.php"
namespace App\Components;
trait FlashMessages
{
protected static function message($level = 'info', $message = null)
{
if (session()->has('messages')) {
$messages = session()->pull('messages');
}
$messages[] = $message = ['level' => $level, 'message' => $message];
session()->flash('messages', $messages);
return $message;
}
protected static function messages()
{
return self::hasMessages() ? session()->pull('messages') : [];
}
protected static function hasMessages()
{
return session()->has('messages');
}
protected static function success($message)
{
return self::message('success', $message);
}
protected static function info($message)
{
return self::message('info', $message);
}
protected static function warning($message)
{
return self::message('warning', $message);
}
protected static function danger($message)
{
return self::message('danger', $message);
}
}
On your base controller "app/Http/Controllers/Controller.php".
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use App\Components\FlashMessages;
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
use FlashMessages;
}
This will make the FlashMessages trait available to all controllers that extending this class.
Create a blade template for our messages: "views/partials/messages.blade.php"
#if (count($messages))
<div class="row">
<div class="col-md-12">
#foreach ($messages as $message)
<div class="alert alert-{{ $message['level'] }}">{!! $message['message'] !!}</div>
#endforeach
</div>
</div>
#endif
On "boot()" method of "app/Providers/AppServiceProvider.php":
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Components\FlashMessages;
class AppServiceProvider extends ServiceProvider
{
use FlashMessages;
public function boot()
{
view()->composer('partials.messages', function ($view) {
$messages = self::messages();
return $view->with('messages', $messages);
});
}
...
}
This will make the $messages variable available to "views/partials/message.blade.php" template whenever it is called.
On your template, include our messages template - "views/partials/messages.blade.php"
<div class="row">
<p>Page title goes here</p>
</div>
#include ('partials.messages')
<div class="row">
<div class="col-md-12">
Page content goes here
</div>
</div>
You only need to include the messages template wherever you want to display the messages on your page.
On your controller, you can simply do this to push flash messages:
use App\Components\FlashMessages;
class ProductsController {
use FlashMessages;
public function store(Request $request)
{
self::message('info', 'Just a plain message.');
self::message('success', 'Item has been added.');
self::message('warning', 'Service is currently under maintenance.');
self::message('danger', 'An unknown error occured.');
//or
self::info('Just a plain message.');
self::success('Item has been added.');
self::warning('Service is currently under maintenance.');
self::danger('An unknown error occured.');
}
...
Hope it'l help you.

Ajax retrieves html instead of json

I'm having a problem with an ajax method, it retrieves an html file instead of json and I have no clue why it is happening because it works perfectly in my home route, but when I try to implement it in my create route, the ajax method doesn't work right
route file
Route::get('home', 'HomeController#index');
Route::get('suggestions',[
'as' => 'suggestions_path',
'uses' => 'SuggestionController#index'
]);
Route::get('suggestions/create',[
'as' => 'suggestions_path',
'uses' => 'SuggestionController#create'
]);
Route::get('ajax_scrap_app',[
'as' => 'ajax_scrap_app_path',
'uses' => 'AjaxController#getAppOpenGraph'
]);
HomeController
<?php namespace App\Http\Controllers;
use App\Level;
class HomeController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard to the user.
*
* #return Response
*/
public function index()
{
$levels = Level::all();
//dd($levels);
return view('home')->with('levels',$levels);
}
}
SuggestionController
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\SuggestionRequest;
use App\Level;
use App\Scrap;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Suggestion;
class SuggestionController extends Controller {
public function __construct()
{
$this->middleware('auth');
}
/**
* Despliega todas las sugerencias hechas por el usuario
*
* #return Response
*/
public function index()
{
$suggestions = Auth::user()->suggestions()->latest()->get();
return view('suggestions.all')->with('suggestions',$suggestions);
}
/**
* Despliega la forma para crear una sugerencia
*
* #return Response
*/
public function create()
{
$levels = Level::all();
return view('suggestions.create')->with('levels',$levels);
}
/**
* Guarda la nueva sugerencia
* #param SuggestionRequest $request
* #return Response
*/
public function store(SuggestionRequest $request)
{
$suggestion = new Suggestion($request->all());
Auth::user()->suggestions()->save($suggestion);
return redirect('suggestions');
}
/**
* Despliega una sugerencia específica, basados en el id
*
* #param int $id
* #return Response
*/
public function show($id)
{
$openGraph = new Scrap();
$suggestion = Suggestion::find($id);
return view('suggestions.show')->with(['suggestion' => $suggestion, 'openGraph' => $openGraph]);
}
/**
* Despliega la forma para editar una sugerencia específica, basados en el id
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$suggestion = Suggestion::find($id);
return view('suggestions.edit')->with('suggestion',$suggestion);
}
/**
* Actualiza la sugerencia
*
* #param int $id
* #param SuggestionRequest $request
* #return Response
*/
public function update($id, SuggestionRequest $request)
{
$suggestion = Suggestion::find($id);
$suggestion->update($request->all());
return redirect('suggestions');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
here is my ajax method so far
$('#app_url').on('focusout',function(e){
var appURL = e.target.value;
console.log("appURL: "+appURL);
/* AJAX */
$.get('ajax_scrap_app?app_url='+appURL, function (data) {
console.log(data);
console.log("THIS IS THE TITLE: "+data[0].title);
console.log("THIS IS THE DESCRIPTION: "+data[0].description);
console.log("THIS IS THE IMAGE: "+data[0].image);
$('#app_title').val(data[0].title);
$('#app_description').val(data[0].description);
$('#app_image').val(data[0].image);
});
});
this is AjaxController
public function getAppOpenGraph(){
$scrap = new Scrap();
$url = Input::get('app_url');
$scrap::setUrl($url);
$title = $scrap::getOpenGraphTitle();
$description = $scrap::getOpenGraphDescription();
$image = $scrap::getOpenGraphImg();
$openGraph = [['title'=>$title,'description'=>$description,'image'=>$image]];
return Response::json($openGraph);
}
OUTPUT from home page (http://localhost/exaproject/public/home)
appURL: https://itunes.apple.com/us/app/crossy-road-endless-arcade/id924373886?mt=8&v0=WWW-NAUS-ITSTOP100-FREEAPPS&l=en&ign-mpt=uo%3D4
[Object]
THIS IS THE TITLE: Crossy Road - Endless Arcade Hopper
THIS IS THE DESCRIPTION: Get Crossy Road - Endless Arcade Hopper on the App Store. See screenshots and ratings, and read customer reviews.
THIS IS THE IMAGE: http://a3.mzstatic.com/us/r30/Purple7/v4/20/7a/c2/207ac26e-66f1-1ee0-1f70-c4733a9015a1/icon320x320.png
OUTPUT form create page (http://localhost/exaproject/public/suggestions/create)
appURL: https://itunes.apple.com/us/app/crossy-road-endless-
arcade/id924373886?mt=8&v0=WWW-NAUS-ITSTOP100-FREEAPPS&l=en&ign-mpt=uo%3D4
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Apprendiendo</title>
<link href="http://localhost/exaproject/public/css/app.css" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">-->
<!-- Fonts -->
<link href='//fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Apprendiendo</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>Home</li>
<li class="dropdown">
Sugerencias <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Crear Sugerencia</li>
<li>Búscar Sugerencias</li>
<li>Mis Sugerencias</li>
</ul>
</li>
<li>Mi Plan</li>
<li>Mi perfil</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
Angel Salazar <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Logout</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
</div>
<!-- Scripts -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="http://localhost/exaproject/public/js/app.js"></script>
</body>
</html>
THIS IS THE TITLE: undefined
THIS IS THE DESCRIPTION: undefined
THIS IS THE IMAGE: undefined
I would appreciate some help !!!
Views by default return a string content like you did:
public function create()
{
$levels = Level::all();
// here you are calling an hmlt/text output
return view('suggestions.create')->with('levels',$levels);
}
That is the main reason why you are receiving html response. There are two options:
Return the rendered view inside of json:
public function create()
{
$levels = Level::all();
// here you are calling an hmlt/text output
$output = view('suggestions.create')->with('levels',$levels)->render();
return response()->json(['html' => $output]);
}
By this way, you can read the response in ajax callable as json like data.html
Avoid returning views. If you want json plain data, then works for that:
public function create()
{
// Do some logic here
// Return json data
return response()->json(['foo' => 'bar']);
}
Finally, looks like you are working with RESTful controllers, that is ok, but resources controllers do not were made to return html data.
I made it work, I don't know exactly why, but those are the changes I made
Route.php
Route::get('suggestions/create/ajax_scrap_app',[
'as' => 'ajax_scrap_app_path',
'uses' => 'AjaxController#getAppOpenGraph'
]);
Ajax method
$('#app_url').on('focusout',function(e){
var appURL = e.target.value;
console.log("appURL: "+appURL);
/* AJAX */
$.get('create/ajax_scrap_app?app_url='+appURL, function (data) {
console.log(data);
console.log("THIS IS THE TITLE: "+data[0].title);
console.log("THIS IS THE DESCRIPTION: "+data[0].description);
console.log("THIS IS THE IMAGE: "+data[0].image);
$('#app_title').val(data[0].title);
$('#app_description').val(data[0].description);
$('#app_image').val(data[0].image);
},'json');
});

Resources