I downloaded handlebars from GitHub
and it contained handlebars.js and plugin.js in the source folder.As for told in the documentation the way to use the render function to fetch template from a file is as follow:
$.handlebars({
templatePath: 'path/to/templates',
templateExtension: 'hbs'
});
// now this will fetch <path/to/templates/content.hbs>
$('#some-element').render('content', {
// ...
});
and what i did did to use it is:
<script type="text/javascript" src="js/jquery.js"></script>
<script src="js/handlebars.js" type="text/javascript"></script>
<script src="js/plugin.js" type="text/javascript"></script>
$.handlebars({
templatePath: 'lib/assets',
templateExtension: 'html'
});
var data = {"username":uname};
$('.container').render('lockscreen', data);
lib/assets/lockscreen.html contains code like this:
<div class="center">
<div class="headline text-center" id="time"></div>
<div class="lockscreen-name" style="font-weight:600;font-size:16px;"><b>{{username}}</b></div>
<div class="lockscreen-item">
<div class="lockscreen-image"><img src="images/avatar5.png" alt="user image"/></div>
<div class="lockscreen-credentials">
<div class="input-group">
<input type="password" class="form-control" placeholder="password" id="pa_asd"/>
<div class="input-group-btn">
<button class="btn btn-flat"><i class="fa fa-arrow-right text-muted"></i></button>
</div>
</div>
</div>
</div>
<div class="lockscreen-link">Or sign in as a different user</div>
</div>
And I still can't get it done.I tried it using otherway...using a static function created by koorchik
function render(tmpl_name, tmpl_data) {
if ( !render.tmpl_cache ) {
render.tmpl_cache = {};
}
if ( ! render.tmpl_cache[tmpl_name] ) {
var tmpl_dir = '/lib/assets';
var tmpl_url = tmpl_dir + '/' + tmpl_name + '.html';
var tmpl_string;
$.ajax({
url: tmpl_url,
method: 'GET',
async: false,
dataType: 'html',
success: function(data) {
tmpl_string = data;
}
});
render.tmpl_cache[tmpl_name] = _.template(tmpl_string);
}
return render.tmpl_cache[tmpl_name](tmpl_data);
}
var rendered_html = render('lockscreen', data);
but got some sort of error like
_ is undefined
Can anybody help me????
That's because your code uses underscore.js, which is an external utility library, and _.template() is actually a function from that library. Your code doesn't find it because you haven't included the underscore.js script.
Here is a link to the latest minified version of underscore.js: http://underscorejs.org/underscore-min.js
You should include it before loading your resources, like this:
<script src="http://underscorejs.org/underscore-min.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script src="js/handlebars.js" type="text/javascript"></script>
<script src="js/plugin.js" type="text/javascript"></script>
Related
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?.
I have this script inside a MS Sharepoint project. The javascript is using Papaparse to process a uploaded .CSV file. Could really use some help to get this script working. When I execute the code I get error: :TypeError: $(...).parse is not a function.
// Parse data from CSV file
function uploadCSV(callBack) {
try {
$('#fileInput').parse({
config: {
// base config to use for each file
delimiter: ";",
header: true,
//preview: 15,
async:true,
dynamicTyping: true,
skipEmptyLines: true,
complete: function(results, file) {
callBack(results.data);
}
},
before: function() {
show();
},
error: {
// executed if an error occurs while loading the file
// or if before callback aborted for some reason
},
complete: function(results) {
}
});
}
catch(err) {
alert('Error inside function uploadCSV :' + err);
}
}
It looks like the problem has to do with how I load the papaparse library. Here is the source code from the page that loads the library:
<html lang="nl">
<head>
<script language="javascript" type="text/javascript" src="/sites/RTZB000/Scripts/JS/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="/sites/RTZB000/Scripts/JS/papaparse.min.js"></script>
<script language="javascript" type="text/javascript" src="/sites/RTZB000/Scripts/DienstImport/uploadCSV.js"></script>
</head>
<body>
<style>
...
</style>
<div class="myTable">
<div class="myTableRow">
<div class="myTableCell fileUpload">
<p class="custom-para">Selecteer CSV</p>
<input type="file" name="csv" id="fileInput" class="upload">
</div>
<div class="myTableCell" id="uploadFile">
</div>
<div class="myTableCell" id="myUpload">
<input type="button" class="inputfile-2" onclick="myTrigger()" value="Uploaden" />
</div>
<div class="cssload-loader" id="loader">
<div class="cssload-inner cssload-one"></div>
<div class="cssload-inner cssload-two"></div>
<div class="cssload-inner cssload-three"></div>
</div>
<div class="myTableCell" id="mySpacer">
</div>
<div class="myTableCell" id="link1">
<a href="/sites/RTZB000/Dienststaten/Historie.aspx">
Historie
</a>
</div>
<div class="myTableCell" id="link2">
<a href="/sites/RTZB000/Lists/A_dienststaatTest/AllItems.aspx">
Alle items
</a>
</div>
<div class="myTableCell" id="link3">
<a href="/sites/RTZB000/Dienststaten/Vandaag.aspx">
Dienststaten
</a>
</div>
<div class="myTableCell" id="link4">
<a href="/sites/RTZB000/Lists/Telefoonlijst_ZHP/AllItems.aspx">
Telefoonlijst ZHP
</a>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#uploadFile').hide();
$('#myUpload').hide();
$('#loader').hide();
// Laat de bestandsnaam zien naast de knop
document.getElementById("fileInput").onchange = function () {
var myVal = this.value.split(/\\/).slice(-1);
console.log(myVal);
document.getElementById("uploadFile").innerHTML = myVal;
$('#uploadFile').show();
$('#myUpload').show();
};
});
</script>
</body>
</html>
Maybe good to clarify that this page is part of Microsoft Sharepoint. Above html is embedded inside another html.
There are a few possibilities here:
JQuery isn't loading properly. Check your console for errors.
Something else is overriding your $ variable, probably another version of JQuery. Try to retrieve the original jQuery with $.noConflict().
The Paraparse library isn't loading as expected. Check your version of Paraparse and look for any errors in your console.
Basically i find code on the internet to test and use it.
the problem is that when i reload the page, the data disappears.
what i want to happen is for the data or the value to just stay.
Thanks guys
Here is the code in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" class="btn btn-success" onclick="passData();" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function passData() {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function(data) {
$("#message").html(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
</script>
</html>
and here is my php code
<?php
$pass=$_POST['pass'];
echo json_encode($pass);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" id="success" class="btn btn-success" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$("#success").click(function () {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function (data) {
$("#message").html(data);
localStorage.setItem("data",data);
},
error: function (err) {
alert(err);
}
});
}
return false;
})
$(document).ready(function () {
var someVarName = localStorage.getItem("data");
console.log(someVarName)
$("#message").html(someVarName);
});
</script>
</html>
First of all i changed your js code to use more jquery syntax, as you already have included it (i trigger the on click event on the script and i don't put it in in html). After that in order not to lose your variable after refresh on ajax success i pass the value of data to localstorage, and after refresh (on document ready) i retrieve it and display it in the label.
Of course every time you put a new value and display it, it over-writes the previous one, so after refresh you display the latest value put in your input field.
I am not sure I understand what you mean but...
Before this line:
<!DOCTYPE html>
enter
<?php session_start(); ?>
In this line add
<input type="text" id="pass_data" class=" form-control" value="<?php echo $_SESSION['VAL']; ?>">
and in your php file:
<?php session_start();
$pass=$_POST['pass'];
$_SESSION['VAL'] = $pass;
echo json_encode($pass);
?>
I'm trying to do a simple hello world using jQuery and Ajax for getting a response from a php in the same folder.
The jQuery code is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="http://netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"
rel="stylesheet" type="text/css">
<link href="http://pingendo.github.io/pingendo-bootstrap/themes/default/bootstrap.css"
rel="stylesheet" type="text/css">
<script type="text/javascript">
function jsonIt(){
var x = document.getElementById("input1").value;
var y = document.getElementById("input2").value;
var obj = '{'
+'"id" : "'+x+'",'
+'"name" : '+y+''
+'}';
var person = {
id:x,
name:y
};
var str_json = JSON.stringify(person);
$.ajax({
type: 'get',
url: 'a.php',
dataType: 'text',
data: obj,
success: function(data) {
alert(data);
},
error: function(e){
console.log(e.message);
//alert('error');
}
});
alert("Pause");
}
</script>
</head>
<body>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="col-sm-2">
<label for="inputEmail3" class="control-label">Email</label>
</div>
<div class="col-sm-10">
<input type="text" class="form-control" id="input1" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<label for="inputPassword3" class="control-label">Password</label>
</div>
<div class="col-sm-10">
<input type="text" class="form-control" id="input2" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox">Remember me</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" onclick="jsonIt()">Sign in</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Simply, called using the HTML:
<button type="submit" class="btn btn-default" onclick="jsonIt()">Sign in</button>
And the php, in the same folder, called a.php is:
<?php echo "Helo world"; ?>
So when I click the button that calls the function jsonIt() I get the following response: "[object XMLDocument]" and not Hello world.
What could be?
EDITED
After the modifications the header code will be:
<head>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="http://netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
...
<script type="text/javascript">
$(document).ready(function() {
function jsonIt(){
$.ajax({
method: 'get',
url: 'a.php',
done: function(data) {
alert(data);
},
fail:function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
}
});
//alert("Pause");
}
$(document).on('click', 'button[type="submit"]', function(e) {
e.preventDefault(); // prevents the default click action
jsonIt();
});
});
</script>
</head>
And the markup of the button like:
<button type="submit" class="btn btn-default" >Sign in</button>
But it stills returning me "[object XMLDocument]" and not Hello world.
If you're going to add jQuery scripts to the top of the page you need to surround them with a document ready handler:
<script type="text/javascript">
$(document).ready(function() {
function jsonIt(){
$.ajax({
method: 'GET',
url: 'a.php',
//url: 'http://practica00.tk/a.php',
dataType: 'text'
})
.done(function(data) {
alert(data);
})
.fail (function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
alert("Pause");
}
$(document).on('click', 'button[type="submit"]', function(e) {
e.preventDefault(); // prevents the default click action
jsonIt();
});
});
</script>
The document ready handler insures that all of the DOM has loaded before the jQuery runs and attaches its event handlers. If you don't wrap in a document ready handler the jQuery may attempt to attach event handlers and methods to items which are not yet loaded into the DOM.
You really shouldn't use inline JavaScript to call functions, especially since you have jQuery available to you. If you are going to you still need to prevent default actions.
<button type="submit" class="btn btn-default" onclick="jsonIt(); return false;">Sign in</button>
If you'd like to use jQuery for the click you would remove the inline JavaScript from the button and add the following to your jQuery code:
$(document).on('click', 'button[type="submit"]', function(e) {
e.preventDefault(); // prevents the default click action
jsonIt();
});
I'm not sure why you're doing anything with a JSON string as you do not use it in your query anywhere. you never define the obj, so you shouldn't send it.
EDIT: I have updated my answer to reflect the more proper AJAX return methods with the version of jQuery being used.
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
If you want to do a simple "hello world" you should remove any code that distracts from the purpose before adding any complexity.
Additionally: To perform AJAX (and consequently PHP) you must execute the code from an operating web server, either your localhost or a test host where everything can be executed properly.
I am trying to crate an application with phonegap. In this code the 'window.location.href..' works very fine in browsers. But in the apk, I'll created with phonegap it doesn't work.
For testing i created one seperate js funktion, it will be triggered by an onclick on the button.
But this also do not work.
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
if (!(localStorage.getItem('session_id') && localStorage.getItem('user_id'))) {
window.location.href="login.html";
}
function test() {
window.location.href="menu.html";
}
function (){
$.ajax ({
url:'http://marcelkipp.com/quizapp/userinfo.php?user_id='+localStorage.getItem('user_id'),
dataType: 'json',
type: 'get',
cache: false,
success:function(data) {
console.log('JSON erfolgreich ausgelesen!');
var category = data.category_title;
if (category==null) category = "Keine Kategorie gewählt";
localStorage.setItem('username', data.username);
localStorage.setItem('role', data.role);
localStorage.setItem('points', data.points);
localStorage.setItem('total_questions',data.number_pq);
localStorage.setItem('category_title',data.category_title);
window.location.href="menu.html";
}
error:function(data) {
console.log('json failed');
}
});
}
</script>
</head>
<body>
<div class="spinner">
<div class="rect1"></div>
<div class="rect2"></div>
<div class="rect3"></div>
<div class="rect4"></div>
<div class="rect5"></div>
</div>
<button onclick="test()">woohoo</button>
<div style="margin:0px auto;text-align:center;color:#ffffff;">loading userdata</div>
</body>
Try
window.location.replace("menu.html");