Is there a way to handle scripts loading through Ajax page calls? I would like to not load those already loaded in the first place by the base page as they are in conflict.
Is the solution to create multiple pages one for the normal call (with the scripts) one for the ajax ones (without the scripts that are duplicates)?
Example:
base_page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
</head>
<body>
<div id="ajax_page"> </div>
<div id="other_ajax_call"> </div>
<div id="second_result"> </div>
</script>
$(document).ready(function(){
$.ajax({
url: '/ajax_page',
type: 'GET',
success: function (result) {
$('#ajax_page').html(result)
}
});
});
$( "#other_ajax_call" ).on( 'click', function() {
$.ajax({
url: '/another_page',
type: 'GET',
success: function (result) {
$('#second_result').html(result)
}
});
});
</script>
</body>
</html>
ajax_page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
</head>
<body>
<div id="ajax_second_page"> </div>
</script>
$(document).ready(function(){
$.ajax({
url: '/a_third_page',
type: 'GET',
success: function (result) {
$('#ajax_second_page').html(result)
}
});
});
</script>
</body>
</html>
In this example, on the 'base_page' I load through Ajax 'ajax_page' that itself is using Ajax (this page is usually called without Ajax and therefore will need to keep the script).
The problem is that when this is done, the jquery scripts are in conflict and the second ajax call of the 'base_page' (for "#other_ajax_call") is not working and I receive the following exception :
Uncaught TypeError: $.ajax is not a function
This is a repost of Ajax call - Loading page script only if not there in the base page that was closed as I first didn't put enough details and my question was not clear enough and I have no way to reopen it.
Since you are getting the full pages anyway it doesn't make sense to do that with ajax, especially when it breaks proper HTML. What you could do is to use an iframe to display your pages, and then manage them with some simple javascript in the parent document.
For example:
<!-- iframe for one of your pages -->
<iframe id="page-foo-iframe"
title="page foo"
width="100%"
height="100%"
src="/a_third_page">
</iframe>
<script>
/*
* You can have a button, or something else, call these functions
* whenever you need to show/hide a page.
*/
function showIframePage(id) {
let page = document.getElementById(id);
page.style.display = "block";
}
function hideIframePage(id) {
let page = document.getElementById(id);
page.style.display = "none";
}
</script>
I would also suggest that you look into using a framework, in particular the JS ones like Vue/React/Angular, because they will make handling things like this a lot simpler and easier to maintain. If you have to load full documents though, iframes are the best way to do that.
Related
I've been trying to make a small php script run through an ajax request. The bigger picture is that I want to store the data in an html form to my database on the click of a button, without actually submitting that form on the same click. However, since I'm new to programming, I'm trying to get the basic principles to work first.
For testing, I made a minimal example. In ajaxtest.hml, I made a button that should execute the function click(). That function is supposed to execute an ajax request to execute testing.php (located in the same folder). testing.php should just return 'Hello World'. However, the button does nothing, and I can't figure out what's wrong.
My code for ajaxtest.html:
<html>
<meta charset="UTF-8">
<body>
<button type="button" onclick="click()">Click Me</button>
<p id="p"></p>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
function click(){
$.ajax({
type: 'POST',
url: 'testing.php',
success: function(data) {
alert(data);
}
});
}
</script>
</body>
</html>
and for testing.php:
<?php
echo "Hello World"; ?>
It is probably a typical rookie mistake I'm making here, but the jungle of different posts on this and similar topics hasn't helped me so far... Any help is greatly appreciated!
There are a few things wrong with your code:
First of all, it is not a proper HTML file. Every HTML file should have a <head></head> tag and <body></body> tag within the <html></html> tag.
Secondly, you want to load your scripts in the <head> section. Where you can also define a title, meta tags, stylesheets, etc.
Thirdly, your <script>tag is wrong. You load a script and at the same time, you define a function. This should be two actions.
I think your script then will look something like:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</head>
<body>
<button type="button" onclick="click()">Click Me</button>
<p id="p"></p>
</body>
<script>
function click(){
$.ajax({
type: 'POST',
url: 'testing.php',
success: function(data) {
alert(data);
}
});
}
</script>
</html>
For information about HTML see W3schools
You should delete the parenthesis in the attribute "onclick=click()", otherwise the function will be immediately executed on page load, and this is why you are not able to see the action of the button.
I suggest this way: (replace it instead of your code into Body tag.)
<button type="button" id="ajaxBtn">Click Me</button>
<p id="p"></p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
const btn=document.getElementById('ajaxBtn');
btn.addEventListener('click',click);
function click(){
$.ajax({
type: 'POST',
url: 'testing.php',
success: function(data) {
alert(data);
}
});
}
</script>
It seems to me that you have 3 things you need to fix:
You are missing the opening <script> tag for your function since the opening script tag you have at the moment is for the jquery library you are referencing.
Also, don't use the reserved word "click" for your function name. I have changed it below to "myfunction"
Move the function definition to an appropriate place within your page.
If you try the code below it should work. I hope this helps.
<html>
<meta charset="UTF-8">
<body>
<script>
function myclick(){
alert('posting!');
$.ajax({
type: 'POST',
url: 'testing.php',
success: function(data) {
alert(data);
}
});
}
</script>
<button type="button" onclick="myclick()">Click Me</button>
<p id="p"></p>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"/>
</body>
</html>
You can try calling the function implicitly
<html>
<meta charset="UTF-8">
<body>
<button id="testbutton" type="button">
Click Me
</button>
<p id="p"></p>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$('body').on('click', '#testbutton', function(){
$.ajax({
type : 'POST',
url : 'testing.php',
success : function(data) {
alert(data);
}
});
});
</script>
</body>
It works without a problem, but since I am a beginner, I am not sure if this is the right way to do this. On my main html page I have a div that contains some product details. I want them to be loaded from my database and shown on the page as soon as the page loads. Something like on the www.amazon.com page. As soon as we load the page there are products with pictures, prices etc... This is the way I do it...
My HTML Page:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="style.css">
</head>
<body >
<div id="PictureDiv"></div>
<div id="NameDiv"></div>
<div id="PriceDiv"></div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="javascriptjs"></script>
</body>
My JavaScript File:
OnPageLoad (); // executes as soon as the page loads
function OnPageLoad () {
$.ajax({
url: 'getProducts',
method: 'GET',
success: function (data) {
$("#PictureDiv").html(data.pic);
$("#NameDiv").html(data.name);
$("#PriceDiv").html(data.price);
},
error: function (error) {
// handle error
}
});
}
So is this the way it is done or? Some advice will be much appreciated.
I'm trying to use a same HTML block in several places and pages, while keeping in low number of lines of code and a low redundancy.
Basically, I need something that is similar to a function that when it's called, it will just load a HTML code into the page - this will be done on page load, so no click or other actions that needs to trigger it.
I don't want to use PHP include.
Example:
<div class="x">
<div class="y">
<div class="z"></div>
</div>
</div>
I'll need to use the same class X into 100+ pages and it will have the same content.
What's the best method to insert just the X class and the inside content to be added automatically?
You could put your code in a different .html file and load it with .load() http://api.jquery.com/load/
$('#targetid').load('somewhere/a.html'); // loads the .html in the #targetid
main.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Main page</title>
<sript src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$('#commonsection').load('reusablefile.htm');
// which is eqvivalent to:
//
// $.ajax({
// url: 'reusablefile.htm',
// dataType: 'html',
// success: function(data){
// $('#commonsection').html(data);
// }
// });
});
</script>
</head>
<body>
<div id="commonsection"></div>
</body>
</html>
reusablefile.html:
<script>
(function($){ //separate scope to keep everything "private" for each module
//do additional javascript if required
})(jQuery);
</script>
<p>...Some non-trivial content...</p>
If you have any javascript frameworks in use they usually have an option as well.
AngularJS uses directives to handle repetitive html code.
https://docs.angularjs.org/guide/directive
Also possibly repeat question of:
How to reuse the html code in every html page?
Try this if you don't mind use the dirty way. :)
$(".reuseTarget").html($(".x").text());
$(".reuseTarget").html($(".x").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="x">
<div class="y">
<div class="z">aabb</div>
</div>
</div>
<div class="reuseTarget">
</div>
i'm just trying the ajax Jquery function in GSP, here is the GSP:
<%# page contentType="text/html;charset=UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta name="layout" content="main" />
<title>Insert title here</title>
<g:javascript library='jquery' plugin='jquery' />
<script type="text/javascript">
function callAjax(){
$(document).ready(function(){
$('button').click(function(){
var URL="${createLink(controller:'book',action:'checkJquery')}"
$.ajax({
url:URL,
data: {id:'1'},
success: function(resp){
console.log(resp);
$("#author").val(resp.author)
$("#book").val(resp.bookName)
}
});
});
});
}
</script>
</head>
<body>
<button class="testMe" onclick="callAjax();">test</button>
<div class="body" id="divBody">
<g:textField name="author" id="author"/>
<g:textField name="book" id="book"/>
</div>
</body>
</html>
here is the checkJquery action in the controller :
def checkJquery() {
def s=Book.get(params.id)
render s as JSON
}
the problem that when i click the button ,it doesn't do anything , but if i clicked it again it prints the below in chrome console, the question why from the first click it didn't work , and why printing the response twice.
Object {class: "test.Book", id: 1, author: "a1", bookName: "book1"}
Object {class: "test.Book", id: 1, author: "a1", bookName: "book1"}
So there are a couple things to point out here.
function callAjax(){
$(document).ready(function(){
$('button').click(function(){
var URL="${createLink(controller:'book',action:'checkJquery')}";
$.ajax({
url:URL,
data: {id:'1'},
success: function(resp){
console.log(resp);
$("#author").val(resp.author);
$("#book").val(resp.bookName);
}
});
});
});
}
Lets start with just the logic. So this is creating a function that contains a document ready. What this means is when the function executes it will give the function to the document ready method which will delay the execution of it until the page's body is parsed and in the dom.
Now lets look at the html.
<button class="testMe" onclick="callAjax();">test</button>
This is defining a button that will call the callAjax() method when it is clicked. So lets follow the logic. You create your function that will be executed later. Your page is rendered and the button exists.
You click the button which executes the method. That method then gives the function to the document ready to wait for the page to be parsed. But... we already know it is. Cause you called it based on an interaction with the page. So the document ready is pointless.
Another point, that call is going to happen -every- time that button is clicked. Meaning your method will happen multiple times, which means your binding will happen multiple times, and so on and so forth.
You should really consider binding in your javascript instead of inline in order to separate your concerns and to minimize/eliminate the redundancy.
So first off the html would change to be something like..
<button class="testMe">test</button>
And your javascript...
$(document).ready(function(){
$('.testMe').click(function(){
var URL="${createLink(controller:'book',action:'checkJquery')}";
$.ajax({
url:URL,
data: {id:'1'},
success: function(resp){
console.log(resp);
$("#author").val(resp.author);
$("#book").val(resp.bookName);
}
});
});
});
Now your markup would be only your markup, and your bindings would happen after the page loads, and only once.
I am trying to use ajax to change the content of a div (as html), when a link is clicked in that same div. I am not very skilled in ajax, so I am pretty sure that this is a noob question. I have tried searching the web for solutions, but I didn't manage to make anything work.
I have a div with the id "main" and inside it I am trying to make a link with the id "link01". When "link01" is clicked, I want "main" to load content from another div in another page ("txt2"-div in site2.html). But I can't get it to work.
Firstly, this is my index.html page:
<head>
<title>site1</title>
<meta charset="UTF-8">
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#link01').click(function() {
$('#main').load('site2.html #txt2', function() {});
});
});
</script>
<div id="main">
<a>
<div id="link01">link</div>
</a>
Main div where the content will change</div>
<br>
<br>
</body>
</html>
And this is my site2.html page:
<!DOCTYPE html>
<html>
<head>
<title>Site2</title>
<meta charset="UTF-8">
</head>
<body>
<div id="txt2">Text that will go into the main div at the index-page when link01 is clicked (contains links, images, etc)</div>
</body>
</html>
I have probably misunderstood something completeley.
There is a very bad practice way that may work... But you should really have a server side code that listens you your ajax call, and returns just the desired HTML fragment as a response. Having said that, try this, it MIGHT work (didn't check):
$(function() {
$('#link01').click(function(){
$.ajax({
url: 'site2.html',
type: 'GET',
success: function(data){
data = $(data);
var $div = $('#txt2', data);
$('#main').html($div);
}
});
});
});