call a js function inside a blade file in laravel - javascript

I am following this jQuery tutorial and trying to replicate this inside my laravel project. I cannot call the getMovie() function defined inside movie-info.js to work when movie.blade.php view is loaded. The routes are properly assigned, and I do not get any error but the console print in getMovie() is not accessed. What am I doing wrong?
I used ziggy library to call the named routes.
app.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Movie Info</title>
#routes
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/cyborg/bootstrap.min.css"
integrity="sha384-nEnU7Ae+3lD52AK+RGNzgieBWMnEfgTbRHIwEvp1XXPdqdO6uLTd/NwXbzboqjc2" crossorigin="anonymous">
<link rel="stylesheet" href="{{ asset('css/dist/movie-info.css') }} ">
</head>
<body>
<nav class="navbar navbar-default>">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">MovieInfo</a>
</div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h3 class="text-center">Search for any movie</h3>
<form id="searchForm">
<input type="text" class="form-control" id="searchText" placeholder="Search movie">
</form>
</div>
</div>
<div class="container">
#yield('content')
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="{{ asset('js/dist/vendor.js') }}"></script>
<script src="{{ asset('js/dist/manifest.js') }}"></script>
<script src="{{ asset('js/dist/movie-info.js') }}">
#yield('slug')
</script>
</body>
</html>
index.blade.php
#extends('layouts.app')
#section('content')
<div id="movies" class="row"></div>
#endsection
movie.blade.php
#extends('layouts.app')
#section('content')
<div id="movie" class="row"></div>
#endsection
#section('slug')
getMovie();
#endsection
movie-info.js
import $ from 'jquery';
$(() => {
$('#searchForm').on('submit', (e) => {
let searchText = $('#searchText').val();
console.log(searchText);
getMovies(searchText);
e.preventDefault();
});
$('#movies').on('click', '.movie-details', (e) => {
const elementID = e.target.id;
const imdbid = $('#' + elementID).data('imdbid'); //custom attribute
console.log(elementID, imdbid);
movieSelected(imdbid);
});
});
function getMovies(searchText) {
axios.get('http://www.omdbapi.com?s=' + searchText + '&apikey=thewdb')
.then((response) => {
console.log(response);
let movies = response.data.Search;
let output = "";
$.each(movies, (index, movie) => {
output += `
<div class="col-md-3">
<div class="well text-center">
<img src="${movie.Poster}">
<h5>${movie.Title}</h5>
<a data-imdbid='${movie.imdbID}' class="btn btn-primary movie-details" id="movie_${movie.imdbID}" href="#">Movie Details</a>
</div>
</div>
`;
});
$('#movies').html(output);
})
.catch((err) => {
console.log(err);
});
}
function movieSelected(id) {
sessionStorage.setItem('movieId', id); //pass data from one page to another
window.location.href = route('show-movie-details');
console.log('my route', route('show-movie-details'));
// getMovie();
return false;
}
function getMovie() {
console.log("in get movie");
}

It's because you call getMovie() inside a script tag with src attribute. Just move it to another script tag without src then it will work as expected. Something like:
...
<script src="{{ asset('js/dist/movie-info.js') }}"></script>
<script>
#yield('slug')
</script>
...
You can get more info here: What does a script-Tag with src AND content mean?.

Related

select tag created in ajax request doesn't be shown in HTML file

I want to load some options via ajax request and show them into select tag HTML. After I get data and create a select tag manually, the HTML file doesn't show the select tag. I used jquery and put the codes in other files.
I try to put ajax request in both $(document).ready() and function but it doesn't work.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- META SECTION -->
<title>Atlant - Responsive Bootstrap Admin Template</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="icon" href="favicon.ico" type="image/x-icon"/>
<!-- END META SECTION -->
<!-- CSS INCLUDE -->
<link rel="stylesheet" type="text/css" id="theme" href="/public/css/theme-default.css"/>
<!-- EOF CSS INCLUDE -->
</head>
<body onload="onLoadCenterName()">
<!-- START PAGE CONTAINER -->
<div class="page-container">
<!-- PAGE CONTENT -->
<div class="page-content ">
<!-- PAGE CONTENT WRAPPER -->
<div class="page-content-wrap">
<div class="row">
<div class="col-md-12">
<form id="addSiteForm" class="form-horizontal"
style="margin-top: 20px;margin-left: 50px;margin-right: 50px">
<div class="panel panel-default">
<div class="panel-heading ">
<h3 class="panel-title "><strong>Add New Site</strong></h3>
</div>
<div class="panel-body">
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label">Select User Type</label>
<div class="col-md-6 col-xs-12">
<select id="addSiteSelectCenterInput" class="form-control select">
</select>
<span class="help-block">Select type of the user account </span>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- END PAGE CONTENT WRAPPER -->
</div>
<!-- END PAGE CONTENT -->
</div>
<!-- END PAGE CONTAINER -->
<!-- START PRELOADS -->
<audio id="audio-alert" src="/public/audio/alert.mp3" preload="auto"></audio>
<audio id="audio-fail" src="/public/audio/fail.mp3" preload="auto"></audio>
<!-- END PRELOADS -->
<!-- START SCRIPTS -->
<!-- START PLUGINS -->
<script type="text/javascript" src="/public/js/plugins/jquery/jquery.min.js"></script>
<script type="text/javascript" src="/public/js/plugins/jquery/jquery-ui.min.js"></script>
<script type="text/javascript" src="/public/js/plugins/bootstrap/bootstrap.min.js"></script>
<!-- END PLUGINS -->
<!-- START THIS PAGE PLUGINS-->
<script type='text/javascript' src='/public/js/plugins/icheck.js'></script>
<script type="text/javascript" src="/public/js/plugins/jquery/jquery.mCustomScrollbar.js"></script>
<!-- END THIS PAGE PLUGINS-->
<!-- START TEMPLATE -->
<!-- <script type="text/javascript" src="/public/js/settings.js"></script>-->
<script type='text/javascript'
src='/public/js/plugins/validationengine/languages/jquery.validationEngine-en.js'></script>
<script type='text/javascript' src='/public/js/plugins/validationengine/jquery.validationEngine.js'></script>
<script type="text/javascript" src="/public/js/plugins/bootstrap/bootstrap-select.js"></script>
<script type='text/javascript' src='/public/js/plugins/noty/jquery.noty.js'></script>
<script type='text/javascript' src='/public/js/plugins/noty/layouts/topCenter.js'></script>
<script type='text/javascript' src='/public/js/plugins/noty/layouts/topLeft.js'></script>
<script type='text/javascript' src='/public/js/plugins/noty/layouts/topRight.js'></script>
<script type='text/javascript' src='/public/js/plugins/noty/themes/default.js'></script>
<script type="text/javascript" src="/public/js/plugins.js"></script>
<script type="text/javascript" src="/public/js/actions.js"></script>
<script type="text/javascript" src="/public/js/addSite.js"></script>
<!-- END TEMPLATE -->
<!-- END SCRIPTS -->
</body>
</html>
addSite.js
function onLoadCenterName() {
$.ajax({
type: 'GET',
url: '/centers/getAllCenters',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log("SUCCESS : ", data);
let selectList = document.getElementById("addSiteSelectCenterInput");
$.each(data, function (key, value) {
console.log(key, value._id, value.centerName);
const option = document.createElement("option");
option.value = value._id;
option.text = value.centerName;
selectList.appendChild(option);
// $('#addSiteSelectCenterInput')
// .append($("<option></option>")
// .attr("value", )
// .text(value.centerName));
});
console.log(selectList);
noty({
text: 'Successful load centers ',
layout: 'topRight',
type: 'success',
timeout: true
}).setTimeout(5000);
$.mpb("update", {
value: 100, speed: 5, complete: function () {
$(".mpb").fadeOut(200, function () {
$(this).remove();
});
}
});
},
error: function (e) {
console.log("ERROR : ", e);
noty({
text: 'There was an error',
layout: 'topRight',
type: 'error',
timeout: true
}).setTimeout(5000);
$.mpb("update", {
value: 100, speed: 5, complete: function () {
$(".mpb").fadeOut(200, function () {
$(this).remove();
});
}
});
}
});
}
in chrom console, result is here:
<select id="addSiteSelectCenterInput" class="form-control select" style="display: none;">
<option value="5d0f86f0a2b7a41bdcd3c91f">sdf</option><option value="5d0f9c4067731820fcabf1eb">scaasdad</option></select>
According to your console result, the <select> is not visible because it has the attribute style="display: none;".
There is nothing in the code that you have provided that would add that attribute, so you obviously haven't given us all the relevant code.
So you either need to remove that attribute... or don't hide the control in the first place.
To show it via jQuery use .show()...
$("#addSiteSelectCenterInput").show()
Or in vanilla JS change the style.display property...
document.getElementById("addSiteSelectCenterInput").style.display = "";

Iterate through a JSON list with JS function

I'm looking for a way to append some JSON results, I'm working with a list (array?) and there's multiple elements, I know I can add some styling directly in the JS code but I'm more comfortable with this method. How can I iterate through elements and implement in some divs, then create similar divs with the next elements.
The only way to achieve that goal afaik is like this:
$("#article").append(data[i].datetime + data[i].headline + "<br />" + "<hr />" + data[i].summary);
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Project JS 02</title>
<link rel="stylesheet" href="assets/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container container-table">
<div class="row vertical-center-row">
<div class="col-md-4 col-md-offset-4">
<button type="submit" class="btn btn-primary" style="width: 100%" class="search" id="getnews">Get News!</button>
<h1 id="headline"></h1><br>
<h3 id="datetime"></h3><br>
<div id="summary"></div><br>
<h6 id="source"></h6><br>
</div>
</div>
</div>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script>
document.getElementById("getnews").addEventListener("click", function () {
var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news"
$.getJSON(newsurl, function (data) {
for (i in data)
{
$("#headline").append(data[i].headline);
$("#datetime").append(data[i].datetime);
$("#summary").append(data[i].summary);
$("#source").append(data[i].source);
}
})
})
</script>
</body>
</html>
You can do this by creating the elements (with jQuery) as needed, and appending them to a container:
$("#getnews").on("click", function () {
var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news"
$('#data').text("...loading...");
$.getJSON(newsurl, function (data) {
$('#data').html("");
data.forEach(function (article) {
$('#data').append(
$('<h1>').text(article.headline),
$('<h3>').text(article.datetime),
$('<div>').text(article.summary),
$('<h6>').text(article.source)
);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-primary search"
style="width: 100%" id="getnews">Get News!</button>
<div id="data"></div>
First: remove the ids. If you want to create similar containers, the ids will be there multiple times, that won't work.
Second: Take the div with $('.row.vertical-center-row') and clone it.
Third: set the values at the cloned HTMLNode und append it to $('.container.container-table')
Something like that (untested):
<div class="container container-table">
<div class="row vertical-center-row">
<div class="col-md-4 col-md-offset-4">
<button type="submit" class="btn btn-primary" style="width: 100%" class="search" class="getnews">Get News!</button>
<h1 class="headline"></h1><br>
<h3 class="datetime"></h3><br>
<div class="summary"></div><br>
<h6 class="source"></h6><br>
</div>
</div>
</div>
<script>
document.getElementsByClassName("getnews").forEach((el)=>el.addEventListener("click", function () {
var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news"
$.getJSON(newsurl, function (data) {
var $elClone = $('.row.vertical-center-row').clone(true).appendTo($('.container.container-table'));
for (i in data) {
$(".headline", $elClone).append(data[i].headline);
$(".datetime", $elClone).append(data[i].datetime);
$(".summary", $elClone).append(data[i].summary);
$(".source", $elClone).append(data[i].source);
}
})
}));
</script>

AngularJS $location directory

Main page URL: http://localhost:3000/
Current second page URL: http://localhost:3000/#/titleDetails.html
Expected second page URL: http://localhost:3000/titleDetails.html
Currently when I click on the title in my main page, the URL contains an extra /# which causes the page to be redirected to titleDetails.html.
The directory of titleDetails.html and index.html is in the same directory.
May I know how can I fix this?
Original Post: AngularJS Display 1 Post in New Page
app.js
(function () {
angular
.module("BlogApp", [])
.config(function($locationProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
})
.controller("BlogController", BlogController);
function BlogController($scope, $http, $rootScope, $location) {
$scope.createPost = createPost;
$scope.deletePost = deletePost;
$scope.editPost = editPost;
$scope.updatePost = updatePost;
$scope.titleDetails = titleDetails;
$scope.postDetail = null;
function init() {
getAllPosts();
}
init();
function titleDetails(post)
{
$scope.postDetail = post;
$location.path('/titleDetails.html');
}
function updatePost(post){
console.log(post);
$http
.put("/api/blogpost/"+post._id, post)
.success(getAllPosts);
}
function editPost(postId){
$http
.get("/api/blogpost/"+postId)
.success(function(post){
$scope.post = post;
});
}
function deletePost(postId){
$http
.delete("/api/blogpost/"+postId)
.success(getAllPosts);
}
function getAllPosts(){
$http
.get("/api/blogpost")
.success(function(posts) {
$scope.posts = posts;
});
}
function createPost(post) {
console.log(post);
$http
.post("/api/blogpost",post)
.success(getAllPosts);
}
}
})();
index.html
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<input ng-model="post.title" class="form-control" placeholder="title"/>
<textarea ng-model="post.body" class="form-control" placeholder="body"></textarea>
<button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>
<button ng-click="updatePost(post)" class="btn btn-success btn-block">Update</button>
<div ng-repeat="post in posts">
<h2>
<a ng-click="titleDetails(post)">{{ post.title }} </a>
<a ng-click="editPost(post._id)" class="pull-right"><span class="glyphicon glyphicon-pencil"></span></a>
<a ng-click="deletePost(post._id)" class="pull-right"><span class = "glyphicon glyphicon-remove"></span></a>
</h2>
<em>{{post.posted}}</em>
<p>{{post.body}}</p>
</div>
</div>
</body>
</html>
titleDetails.html:
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<div>
<h2>
<a>{{ postDetail.title }} </a>
</h2>
<em>{{postDetail.posted}}</em>
<p>{{postDetail.body}}</p>
</div>
</div>
</body>
</html>
Console Error in index.html:
angular.js:13708 Error: [$location:nobase] http://errors.angularjs.org/1.5.7/$location/nobase
at angular.js:38
at sf.$get (angular.js:13384)
at Object.invoke (angular.js:4709)
at angular.js:4508
at d (angular.js:4655)
at e (angular.js:4679)
at Object.invoke (angular.js:4701)
at R.instance (angular.js:10234)
at m (angular.js:9147)
at g (angular.js:8510)
Angular has 3 routing operates:
Hashbang Mode
HTML5 Mode
Hashbang in HTML5 Mode
You can configure: $locationProvider.html5Mode(true).hashPrefix('!');
Check documentation

Laravel 5.3 impossible to put script on view (autocomplete field)

I’m currently working on Laravel 5.3 for my internship.
And as you guessed, I have an annoying issue let me explain it:
On a page, I have to put an « autocomplete » field but It’s not working at all.
I have this error I can’t solve:
[Vue warn]: Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed. app.js:139
Furthermore, I need to keep the larvel « template » like the top bar with the login name, etc…
I tried a lot of solutions found on the internet but nothing worked.
I’m totally desperate, do you have any solutions ?
ps: Sorry for the awful grammar, I'm french and I'm learning, thanks for your comprehension.
selectcr.blade.php
#extends('layouts.app')
#section('content')
<!DOCTYPE html>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Selection de Compte-Rendu</div>
<div class="panel-body"> Selectionnez le client:
<input id="intervenant-name" type="text" class="form-control pd-l-50" placeholder="Recherche par nom d'entreprise">
<script src="{{asset('js/jquery-1.12.4.js')}}"></script>
<script src="{{asset('js/jquery-ui.js')}}"></script>
<script>
(function () {
src = "/prefcard/maker-search-intervenant";
$("#intervenant-name").autocomplete({
source: function (request, response)
{
$.ajax({
url: src,
dataType: "json",
data:
{
term: request.term
},
success: function (data)
{
response(data);
}
});
},
min_length: 2,
select: function (event, ui)
{
//console.log(ui.item.value);return false;
var test = ui.item.value ? ui.item.value : '';
if (test != '')
{
var url = '/prefcard/maker-search-intervenant';
var formAutocomplete = $('<form action="' + url + '" method="post">' +
'<input type="hidden" name="_token" value="{{ csrf_token() }}">' +
'<input type="text" name="term" value="' + ui.item.value + '" />' +
'</form>');
$('body').append(formAutocomplete);
formAutocomplete.submit();
}
}
});
})();
</script>
</div>
</div>
</div>
</div>
</div>
#yield('javascript')
#endsection
SelectCRController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class SelectCRController 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('selectcr');
}
public function searchIntervenant(Request $request) {
$query = $request->get('term', '');
$results = DB::table('intervenant')->where('intervenantEntreprise', 'LIKE', '%' . $query . '%')->orWhere('intervenantFonction', 'LIKE', '%' . $query . '%')->take(5)->get();
$data = array();
foreach ($results as $result) {
$data[] = array('value' => $result->intervenantEntreprise . ' ' . $result->intervenantEmail, 'id' => $result->id);
}
if (count($data))
return $data;
else
return ['value' => 'No Result Found', 'id' => ''];
}
public function postSearchIntervenant(Request $request) {
//Do whatever you want to search accordingly name and then return
return view('dashboard')->with('intervenant', $intervenant);
}
}
web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Route::get('/', function () {return view('welcome');});
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::get('/configuration', 'ConfigurationController#index');
Route::get('/selectcr', 'SelectCRController#index');
Route::get('/prefcard/maker-search-intervenant', 'SelectCRController#searchIntervenant');
Route::post('/prefcard/maker-search-intervenant', 'SelectCRController#postSearchIntervenant');
Route::get('/intervenant', function () {return view('intervenant');});
Route::get('/api/intervenant/{id?}', 'IntervenantController#index');
Route::post('/api/intervenant', 'IntervenantController#store');
Route::post('/api/intervenant/{id?}', 'IntervenantController#update');
Route::delete('/api/intervenant/{id?}', 'IntervenantController#destroy');
Route::get('/utilisateur', function () {return view('utilisateur');});
Route::get('/api/utilisateur/{id?}', 'UtilisateurController#index');
Route::post('/api/utilisateur', 'UtilisateurController#store');
Route::post('/api/utilisateur/{id?}', 'UtilisateurController#update');
Route::delete('/api/utilisateur/{id?}', 'UtilisateurController#destroy');
Route::post('register', 'Auth\RegisterController#register');
//Route::auth();
app.blade.php
<!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">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Styles -->
<link href="/css/app.css" rel="stylesheet">
<!-- Scripts -->
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
</head>
<body>
<div id="app">
<nav class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<!-- Collapsed Hamburger -->
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- Branding Image -->
<a class="navbar-brand" href="{{ url('/') }}">
{{ config('app.name', 'Laravel') }}
</a>
</div>
<div class="collapse navbar-collapse" id="app-navbar-collapse">
<!-- Left Side Of Navbar -->
<ul class="nav navbar-nav">
</ul>
<!-- Right Side Of Navbar -->
<ul class="nav navbar-nav navbar-right">
<!-- Authentication Links -->
#if (Auth::guest())
<li>Login</li>
#else
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
{{ Auth::user()->name }} <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="{{ url('/logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
</li>
#endif
</ul>
</div>
</div>
</nav>
#yield('content')
</div>
<!-- Scripts -->
<script src="/js/app.js"></script>
</body>
</html>
UPDATE
Now and with some modifications the error disappeared but the scripts are not working at all.
<!DOCTYPE html>
#extends('layouts.app')
#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">Selection de Compte-Rendu</div>
<div class="panel-body"> Selectionnez le client:
<input id="intervenant-name" type="text" class="form-control pd-l-50" placeholder="Recherche par nom d'entreprise">
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script src="{{asset('js/jquery-1.12.4.js')}}"></script>
<script src="{{asset('js/jquery-ui.js')}}"></script>
<script>
(function () {
src = "/prefcard/maker-search-intervenant";
$("#intervenant-name").autocomplete({
source: function (request, response)
{
$.ajax({
url: src,
dataType: "json",
data:
{
term: request.term
},
success: function (data)
{
response(data);
}
});
},
min_length: 2,
select: function (event, ui)
{
//console.log(ui.item.value);return false;
var test = ui.item.value ? ui.item.value : '';
if (test != '')
{
var url = '/prefcard/maker-search-intervenant';
var formAutocomplete = $('<form action="' + url + '" method="post">' +
'<input type="hidden" name="_token" value="{{ csrf_token() }}">' +
'<input type="text" name="term" value="' + ui.item.value + '" />' +
'</form>');
$('body').append(formAutocomplete);
formAutocomplete.submit();
}
}
});
})();
</script>
#endsection
#yield('javascript')
1) You have a Vuejs error (add tag plz). Looks like you need to move script tags out of vuejs container.
2) !DOCTYPE html must be at the top of your document, not in the middle.
Blade is powerful to "inject" your view into a skeletonized html page. If you need some clean way to call your layout/app.blade.php, I made an example right below :
layout/app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>#yield('title')</title>
#yield('links')
</head>
<body>
#yield('content')
<!-- Here is the perfect place for the javascript libraries that you think will be used in ANY page -->
<script src="jquery/jquery.min.js"></script> <!-- for example if you use jQuery -->
<script src="bootstrap/js/bootstrap.min.js"></script> <!-- same if you need Bootstrap-Twitter-3 in any pages -->
<!-- And then, your specific scripts are hooked below -->
#yield('scripts')
</body>
</html>
Then, it is as simple as it looks to "inject" your content inside your <body> tag, like following :
selectcr.blade.php (juste an example)
#extends('layout.app')
<!-- Some additionnals css, specific to this page -->
#section('links')
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
#ensection
#section('title')
My awesome title
#endsection
#section('content')
<div class="container">
<div class="row">
<div class="col-lg-12">
<h3>Greetings user !</h3>
</div>
<div class="col-lg-12">
<div class="form">
<input type="text" />
<button type="submit">Go !</button>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script>
alert('This is my custom javascript !');
</script>
#endsection
So, whenever Blade encounters a #section tags, it automatically injects its content right inside the place it belongs, meaning in every #yield that represent this section.
Hope it helps.
Move #yield('javascript') out of the section put if after the #endsection tag, you could also just use #end.
Comment out all scripts within your section Tag also! because this is what the error is saying.
TRY:
All your script code should be inside
#section('scripts') .... #endsection.
And also please close content section before your javascript.
Solved it, I made a special "app.blade.php" just for the specified view and put all my scripts in it.
Not very beautiful, but It's working.

Naming ng-app breaks data-binding in angularjs

I am working on my first website with AngularJS. My app works fine when I declare ng-app in the html tag. However, data binding stops working when I try to assign a name to the ng-app directive so that I can create a module with controllers and filters.
Here is my working code:
<!doctype html>
<html data-ng-app>
<head>
<meta charset="utf-8">
<title>Twittiment</title>
<link href="search_client.css" type="text/css" rel="stylesheet" />
<link href="tweet.css" type="text/css" rel="stylesheet" />
<script src="jquery.min.js"></script>
<script src="search_client.js"></script>
<script src="/js/highcharts.js"></script>
</head>
<body data-ng-controller="TweetCtrl">
<div id="main">
<div id="search_box">
<h1 id="title">Twitter Sentiment Analysis</h1>
<input name="search_terms" autofocus="autofocus" data-ng-model="query" />
<button id="search_button" data-ng-click="search()">Search</button>
<div id="data"></div>I can add:{{1+3}}</div>
<div id="search_results">Search tweets:
<input name="filter" data-ng-model="text" /><span>Displaying {{(tweets|filter:text).length}} of {{tweets.length}} tweets</span>
<div class="tweet" data-ng-repeat="tweet in tweets | filter:text">
<div class="tweet_left">
<div class="tweet_image"> <a href="https://twitter.com/{{tweet.user.screen_name}}">
<img src="{{tweet.user.profile_image_url}}">
</a>
</div>
</div>
<div class="tweet_right">
<div class="tweet_triangle"></div>
<div class="tweet_row">
<div class="tweet_username"> {{tweet.user.screen_name}}
<span class="tweet_name">{{tweet.user.name}}</span>
<span class="delete_tweet">Mark as irrelevant</span>
<input class="close_button" type="image" src="/xmark.jpg" alt="submit" ng-click="delete($index)">
</div>
</div>
<div class="tweet_row">
<div class="tweet_text">{{tweet.text}}</div>
</div>
<div class="tweet_row">
<div class="tweet_timestamp">
<img class="stream_bluebird" src="bird_16_blue.png"> <span class="retweets">{{tweet.retweet_count}} retweets</span>
{{tweet.created_at}}
<img src="reply.png" class="imageof_reply"> Reply
<img src="retweet.png" class="imageof_retweet"> Retweet
<img src="favorite.png" class="imageof_favorite"> Favorite
</div>
</div>
</div>
<div class="sentiment" data-ng-controller="RatingCtrl">
<div class="rating" data-ng-model="tweet.polarity">{{tweet.polarity}}</div>
<button data-ng-click="changeRating('Positive')">
<img class="positive" src="/thumbs-up-button.jpg">
</button>
<button data-ng-click="changeRating('Neutral')">
<img class="neutral" src="/thumbs-sideways-button.jpg">
</button>
<button data-ng-click="changeRating('Negative')">
<img class="negative" src="/thumbs-down-button.jpg">
</button>
</div>
</div>
</div>
</div>
<div class="total">
<h2 id="totalTitle"></h2>
<div>{{tweets.length}}</div>
<div id="totalPos"></div>
<div id="totalNeut"></div>
<div id="totalNeg"></div>
</div>
<div id="container" style="width:40%; height:400px;"></div>
<script src="/ang-Twittiment/app/lib/angular/angular.js"></script>
</body>
</html>
JS:
function TweetCtrl($scope, $http) {
$scope.search = function () {
$http({
method: 'GET',
url: 'http://localhost:8080/search_server.php?q=' + $scope.query
}).success(function (data) {
$scope.tweets = data;
})
.error(function (data) {
alert("search error")
});
};
$scope.delete = function (idx) {
$scope.tweets.splice(idx, 1);
};
}
function RatingCtrl($scope) {
$scope.changeRating = function (rating) {
$scope.tweet.polarity = rating;
}
}
And here is the code that doesn't work:
<html data-ng-app="myApp">
JS:
var myAppModule = angular.module('myApp', []);
myAppModule.controller('TweetCtrl', function ($scope, $http) {
$scope.search = function () {
$http({
method: 'GET',
url: 'http://localhost:8080/search_server.php?q=' + $scope.query
}).success(function (data) {
$scope.tweets = data;
})
.error(function (data) {
alert("search error")
});
};
$scope.delete = function (idx) {
var person_to_delete = $scope.tweets[idx];
$scope.tweets.splice(idx, 1);
};
});
myAppModule.controller('RatingCtrl', function ($scope) {
$scope.changeRating = function (rating) {
$scope.tweet.polarity = rating;
}
});
Can anyone tell me why data binding stops whenever I assign a name to the ng-app directive? Is there a step I'm missing when configuring the module? Any help would be greatly appreciated, please let me know if more information is needed.
actually you need to put your angular.js file reference before angular.module statement so it can identify angular otherwise when you will check the javascript error it shows angular is not define
var myAppModule = angular.module('myAppModule', []);
This should do it.
When you declare ng-app="myApp", angular compiler searches for controllers registered with "myApp", but the controllers are registered with "myAppModule"

Categories

Resources