i am trying to append a div to other div here :
<script>if($(window).width()>500){
$("body").append("<?php include('includes/middle.php') ?>");
}
</script>
Which becomes:
<script>if($(window).width()>500){
$("body").append("<div class='middle'>
<div class='middleOne'>
<a href='http://localhost/jhandwa/story/11-illustrations-that-perfectly-capture-how-life-changes-when-we-grow-up'>
<img src='https://files.brightside.me/files/news/part_31/310360/12086810-10111660-1-0-1487765591-1487765607-0-1488442321-0-1488458395-1488458410-650-1-1488458410-650-0c369e17e2-1488484030.jpg'>
<div class='miniTitle'>11 Illustrations That Perfectly Capture How Life Changes When We Grow Up<br /><span>2017-03-17 17:12:36</span></div>
</a>
</div>
<div class='middleOne'>
<a href='http://localhost/jhandwa/story/10-things-you-didnt-know-about-the-us-secret-service'>
<img src='https://www.whitehouse.gov/sites/whitehouse.gov/files/images/first-family/44_barack_obama%5B1%5D.jpg'>
<div class='miniTitle'>10 Things You Didn't Know About<br /><span>2017-03-17 15:15:29</span></div>
</a>
</div>
<div class='middleOne'>
<a href='http://localhost/jhandwa/story/who-is-actually-dumb-and-dumber-after-watching-these-crime-serials'>
<img src='https://s-media-cache-ak0.pinimg.com/originals/36/45/e6/3645e66b26b611a30fabf923f7247d23.jpg'>
<div class='miniTitle'>Who is Actually 'dumb' and 'dumber' after this? <br /><span>2017-02-28 00:00:00</span></div>
</a>
</div>
</div>");
}
</script>
what am i doing wrong here? i feel its something wrong because of double or single quotes.why isn't it working?
Updating my original answer:
First, you need to wrap your code in document.ready(). It should append when the dom is ready.
Second, it is not working because your outputted HTML is on multiple lines. If you look at your console, you would see the following errors:
Uncaught SyntaxError: Invalid or unexpected token
There are many ways to solve this issue, the simplest would be to use template literals, this means you should wrap your code within backtick.
$(document).ready(function () {
if ($(window).width() > 500) {
$("body").append(`<?php include('includes/middle.php') ?>`);
}
});
However, this solution may not be compatible with all browsers as this feature has been introduced in ES6.
A much better way would be to call the sidebar.php via ajax.
$(document).ready(function () {
if ($(window).width() > 500) {
$.get("includes/middle.php", function (data, status) {
$("body").append(data);
})
}
});
This script can not execute because your PHP file have multiple line. And multiple line will make your JS syntax wrong.
You need include this php file in a hidden script, and use jQuery to get this div content and append into body.
And as #Hyder B say, you need put this script execute when document has been ready.
You can try this way:
<div id="included_content" style="display:none">
<?php include('includes/middle.php') ?>
</div>
<script>
$(document).ready(function() {
if($(window).width() > 500){
$("body").append($("#included_content").html());
}
});
</script>
Try this:
if($(window).width()>500){
$.ajax({
url: 'includes/middle.php',
success: function(html) {
$("body").append(html);
}
});
}
Based on this answer and as you directly echo inside the included page, you can use backtick (`) to wrap multiline string in js properly.
<script>
$(document).ready(function() {
if($(window).width()>500){
$("body").append(`<?php include('includes/middle.php'); ?>`);
}
});
</script>
Related
I've got a single page application inside of my larger application that will send data to the DB, and will also display that same table's data. Currently, I have AJAX dynamically sending the data. However, to get the data just inserted to appear in the table that I want it to, I have to refresh. I've been trying things all morning, but below is the current state of things.
The View:
<html>
<head>
<!--I took some stuff out to make it easier to look at -->
</head>
<body onresize="resizeRecalc()">
<div class="container-fluid">
<div class="row header">
<div class="col-12">
<img src="{{ URL::asset('images/takeStatsLogo.png') }}" id="header-logo" />
</div>
</div>
<div class="mainArea row">
<div class="left col-8">
<div onclick="playPause()" class="embed-responsive embed-responsive-16by9">
<video id="gameFilm" src="{{ URL::asset('images/basketball.mp4') }}" preload="metadata"></video>
</div>
<div class="timebar">
<span class="timeItem" id="timestamp"></span>
<div onclick="changeVidTime()" onmousemove="moveLine(event)" onmouseout="REmoveLine()" id="outerBox"> <div id="progressBox"> <div id="placeMarker">
</div></div></div>
<span class="timeItem" id="duration-place"></span>
</div>
<!-- This is a key part -->
<div id="statList">
#include('partials.statList')
</div>
</div>
<div id="right" class="right col-4">
<!--Checking if we should make the user select starters. If we have them, no need to do that...-->
#if ($game->starters != null)
#include('partials.areStarters')
#else
#include('partials.noStarters')
#endif
</div>
</div>
</div>
<script>
//Add Stat Form
//This part here will add the stats, but it won't refresh them!
$('input#addStatButton').click( function() {
$.post( '{{action("StatController#store")}}', $('form#new_stat').serialize(), function(data) {
$('#statList').load('/take-stats/{{$game->id}}');
},
'json' // I expect a JSON response
);
clearStat();
});
</script>
<script src="{{ URL::asset('js/takeStats/genJavascript.js') }}"></script>
<script src="{{ URL::asset('js/takeStats/videoJS.js') }}"></script>
<script src="{{ URL::asset('js/takeStats/dataJS.js') }}"></script>
</body>
</html>
Here is the controller method:
public function loadStatList($id) {
$userType = Auth::user()->user_type;
if(Auth::check() && Game::where('id', '=', $id)->exists() && ($userType == 'statistician' || $userType == 'admin')) {
$game = Game::find($id);
$players = $game->team->users->where('user_type', 'player');
$stats = Stat::orderBy('video_timestamp', 'desc')->where('game_id', $game->id)->get();
$statMeta = Stat_Meta::all()->where('type', 'recorded');
return view('partials.statList', compact('game', 'players', 'stats', 'statMeta'));
} else {
abort(404);
}
}
I might be missing something but I thought this would do what I am trying to achieve.
I figured it out!Thank #Get Off My Lawn for giving me a bit of a hint that I couldn't just use the #include. I went ahead and figured out how to pre-render the HTML and then bring it in. It is actually not that hard. The idea here is to use a JQuery function to do an AJAX POST upon hitting submit, then use .done to get then new full webpage. After you have that (you can console.log it to see what you're working with at that point, it will be the entire webpage) you can just get the specific div you want to refresh from the .get you performed, and stick it in the same div. Here is the code:
HTML/#include:
<div id="statList">
#include('partials.statList')
</div>
The AJAX/JQuery:
$('input#addStatButton').click( function() {
$.ajax({
type: 'POST',
url: '{{action("StatController#store")}}',
data: $('form#new_stat').serialize(),
})
.done(function(refresh) {
clearStat();
$.get('{{action("StatController#show", [$game->id])}}', function(data) {
var newData = $("#statList" , data)
$( "#statList" ).html( newData );
//console.log(newData);
});
});
});
I'M SO HAPPY Y'ALL!!!
As discussed this is not an answer on your question but a simple explanation you asked in the comments. And it can help somebody else
Laravel and JQuery
How powerfull :-)
First i will try to fit this as much as possible to your needs with the information your provided.
Secondly jquery contains some cool ass functions a lot of people don't know about.
As you described you have a single page website or something like that. That means you have 1 route to show the single page i suggest /take-stats/{{$game->id}}.
In your controller and i use as example the GameController you have something like the following.
class GameController
{
public function __construct()
{
}
//the single page view
public function index()
{
//your singlepage logic here....
return view('games.index'); //something like this?
}
public function create() //this is where you post to
{
//logic to store the game stats...
//this is where you return a succes message or something.
//lets return the index instead :-)
//dont't return $this->index! use redirect to the route.
return redirect()->route('the.route.to.your.index');
}
}
As you see above, we return the single page in the post response. SSo when you post to the store method, and it succeeds it returns the index page.
Now the jquery.
$('input#addStatButton').on( function() {
//this is where to do the post.
$.post(`{{ route('to.your.store.route') }}`, $('form#new_stat').serialize(), (response) => {
//clear the stats because the post is succeeded in here
//also reload the content. The response contains the new html content
//now what we can do is replace the whole content....
//something like $(`html`).html('response);
//or we get the content we need from the response and this is where jquery comes in handy. The response is simply a html response so jquery can create a new dom from it.
let statsList = $(response).find(`#statslist`).html(); //create a dom element of the response.
$(`#statslist`).html(statslist); //put the filtered html in the current list.
//thats all :-)
}).fail(() => {
// a fail save. When the post fails it will come in here.
}).always(() => {
clearStats();
//this is called always even when it fails. You can clear the stats or something in here.
});
});
A short description :
Onclick post button, post to post.route
Controller method does logic and returns as success the index url.
jquery parses the html response and replaces the original content.
done.
I hope this helps you or somebody else. When using a structure like above this code is simply cleaner and faster for it only executes one request.
I have a php file coming from a global assets folder, in the footer I have this:
<?php
include('../global/includes/footer_template.php');
?>
and in that template I have something like this:
<a href="<?php echo $legalUrl;?>"target="_blank">
<?php echo ($isLangSpanish?'Nota Legal':'Legal Notices');?>
</a>
so in the view you will see 'Legal Notices', for one of the pages the client is asking me to uncapitalize the 'N' in Notices. So I did this with jQuery
<?php
include('../global/includes/footer_template.php');
?>
<script type="text/javascript">
$(document).ready(function(){
$('.footer p a').text().replace('Notices', 'notices');
});
</script>
And it works in the browser console:
But I can't see that change in the view.
What can I do?
NOTE:
I can't change the footer template in the assets because it's been used for other projects.
You have to assign the value back.
$(document).ready(function(){
$('.footer p a').text($('.footer p a').text().replace('Notices', 'notices'));
});
a little cleaner:
$(document).ready(function(){
var link = $('.footer p a'),
updatedText = link.text().replace('Notices', 'notices');
link.text(updatedText);
});
Posting an alternative solution using a callback to text(),
$('.footer p a').text(function(){
return $(this).text().replace('Notices', 'notices')
});
.text( function )
A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.
I'm really new at this and I need a random button on my page that would show a new line of information in a div every time someone click on the random button. I was also wondering if there is over 800 lines is it possible to put it in an outside file as txt or html.
Here is what I got so far and well it doesn't work and I'm getting confuse... Please help
<script type="text/javascript" src="jquery-2.2.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#text').hide();
$('a#random').click(function(){
$('#text').toggle();
})
function RndText() {
var rannum= Math.floor(Math.random()*textarray.length);
document.getElementById('#text').innerHTML=textarray[rannum];
}
var textarray = [
"Hello",
"How are you",
"Good Bye"
];
$("#text").load()
})
</script>
<body>
<div id="text">Line to Show</div>
RANDOM
</body>
Uh. Pretty much this:
$('a#random').click(function(){
$('#text').toggle();
RndText(); //you're good
});
Although I will point out that RndText() uses document.getElementById when it could use $("#text") instead. (there's a .html() method that will write the value instead of the .innerHTML property).
document.getElementById is also not currently working because you used "#text" instead of "text", jQuery uses CSS selectors, getElementById does not.
Add execution of RndText when you clicks on Random button.
$('a#random').click(function(){
$('#text').show();
RndText();
})
This will give you a button and you can run this code by clicking the button below. However, I did not quite understand you second part of the question: 800 lines in separate file, what do you wanna do with it? Tell me so that I can helo you further...
Editted:
<?php
$data = file_get_contents('demo.txt');
$lines= split("\n",$data);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
var textarray = <?php echo json_encode($lines); ?>;
function RndText() {
var rannum= Math.floor(Math.random()*textarray.length);
$('#text').text(textarray[rannum]);
console.log(textarray[rannum]+" "+rannum+" "+textarray.length);
}
$(document).ready(function(){
$('#text').hide();
$('#random').click(function(){
$('#text').show();
RndText();
});
});
</script>
<body>
<div id="text"></div>
<button id="random">RANDOM</button>
</body>
<html>
<head>
<script src="edvTextGame.js"></script>
<link rel="stylesheet" href="placeholder.css">
</head>
<div class="firstScreen">
<div class="Title Fade">Placeholder</div>
<button class="Fade" onclick="setTimeout(Start)"> Start </button>
</div>
<div class="introStoryScreen">
<div class="JSGameText">
<p id="intro" ></p>
</div>
</div>
</html>
The used HTML
window.onerror = function(msg, url, linenumber) {
alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
return true;
}
//FUNCTIONS
// Intro sequence
function Start() {
document.getElementById("intro").innerHTML = test;
}
// Creator. -> Origin asign, name asign, stat asign
function CharCreation() {
}
The used JavaScript
The problem in these files is that the document.getElementById part is not functioning, it gives me an empty error.
My notepad++ also doesn't recognize/autofill when I type .innerHTML behind the document.getElementById part.
According to examples i've seen, this should work. Can someone help me out?
The error message will probably be about the assignment... what does 'test' reference to?
Maybe you meant:
document.getElementById("intro").innerHTML = "test";
Use the body.onload function to ensure that the document was loaded and ready, then set the value. Note that by default, Javasciprt expects enclosed strings, or variables on operations.
function aFunction(){
var aString = "test"
document.getElementById("intro").innerHTML = aString;
}
<body onload="aFunction()">
You are missing the quotes in test :
function Start() {
document.getElementById("intro").innerHTML = "test";
}
I found the problem, in the HTML I was trying to add what I wanted to add to a P tag, I got rid of the P tag and made it write to the DIV tag instead, it works now.
Previously I am using JQuery library from here
http://jquery.com/download/
http://code.jquery.com/jquery-migrate-1.2.1.min.js
I try to include the following code, it work perfectly.
Javascript
$(document).ready(function(){
function loading_show(){
$('#loading').html("<img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax
({
type: "POST",
url: "listcontact.php",
data: "page="+page,
success: function(msg)
{
$("#con").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#con").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#con .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val("").focus();
return false;
}
});
});
HTML
<div id="con">
<div class="data"></div>
<div class="pagination"></div>
</div>
And Then I try to use JQuery js from Google instead from JQuery.com
https://developers.google.com/speed/libraries/devguide#jquery
ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js
The Tab menu still can work, however I cannot get any data from listcontact.php
How can I make it work in Google JQuery?
this is all my script tag
<script src="jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript" src="ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
This is my tab menu
<nav>
<div id="tabs">
<ul>
<li><b>More Details</b></li>
<li><b>Contact</b></li>
<li><b>Files</b></li>
<li><b>Sales pipeLine</b></li>
<li><b>Call report</b></li>
</ul>
<div id="tabs-1">
<?php //include('viewdetail.php') ;?>
</div>
<div id="tabs-2">
<?php
if( $view == 0)
{
include('contact.php');
}
else
{
include('newcontact.php') ;
}
?>
</div>
<div id="tabs-3">
<?php //include('filemanagement.php') ;?>
</div>
<div id="tabs-4">
Under Development
</div>
<div id="tabs-5">
<?php //include('callReport.php') ;?>
</div>
</div>
</nav>
The code is inside my contact page, when I try to include it inside my tab
Are you developing locally? Or remotely?
If you are local....you usually have to attach http:// to the google apis
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
If not then just....
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
Should work...
This should also be replaced...from .live() to .on() as .live() is now deprecated
$('body').on('click','#go_btn', function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
EDIT / UPDATE
You posted this...
<script src="jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript" src="ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
Change to this...
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
The jquery needs to be above the jquery-ui, as the ui has a dependancy on Jquery, and you can remove v1.9 no sense in loading jquery twice
EDIT 3
I would change this...you don't need that ajaxComplete call, since the success function is doing that anyway...
$.ajax
({
type: "POST",
url: "listcontact.php",
data: {page: page},
success: function(msg)
{
loading_hide();
$("#con").html(msg);
}
});
And you made sure to change both your live()'s???
You had two, the other one should look like this...
$('body').on('click','#con .pagination li.active' function(){
var page = $(this).attr('p');
loadData(page);
});
try to include the same version JQuery from google :
Number of version JQuery from google should be equal number of version JQuery from Jquery website
but if you want to use recent version, there are some changes , and you should modify something in your code, see log console for more info about problem and check documentation of JQuery here
Looks like live might not work with the latest version
Replace
.live('click'
with
.on('click'
If there are any dynamically added elements on the page replace your events with this syntax
$(staticContainer).on('click', 'selector' function(){
Where staticContainer is the closest static ancestor of the element.
selector is the element to which you want to attach the event.
I had experience with similar issue, it may deal with deprecated functions! check EACH piece of function, so that deprecated methods are corrected :) Hope this help you go to somewhere right :)
deprecated-ajax-or-jquery-command-cause-no-result-returned
Enjoy!