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 AppHttpControllers;
use AppLevel;
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 AppHttpControllers;
use AppHttpRequests;
use AppHttpControllersController;
use AppHttpRequestsSuggestionRequest;
use AppLevel;
use AppScrap;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use AppSuggestion;
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><a href="http://localhost/exaproject/public">Home</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Sugerencias <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="http://localhost/exaproject/public/suggestions/create">Crear Sugerencia</a></li>
<li><a href="http://localhost/exaproject/public/search">Búscar Sugerencias</a></li>
<li><a href="http://localhost/exaproject/public/suggestions">Mis Sugerencias</a></li>
</ul>
</li>
<li><a href="http://localhost/exaproject/public/plan">Mi Plan</a></li>
<li><a href="http://localhost/exaproject/public/profile">Mi perfil</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Angel Salazar <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="http://localhost/exaproject/public/auth/logout">Logout</a></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 !!!
2
Answers
I made it work, I don't know exactly why, but those are the changes I made
Route.php
Ajax method
Views by default return a string content like you did:
That is the main reason why you are receiving html response. There are two options:
Return the rendered view inside of json:
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:
Finally, looks like you are working with RESTful controllers, that is ok, but resources controllers do not were made to return html data.