I'm having a problem changing the string content of a particular DIV tag when using AJAX.
For some reason I can change string content when using an onclick function. This works;
<div id="demo">Will change on click? </div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Yes, Successfully changes" ;
}
</script>
However this does not;
<div id="demo2">Will this change?</div>
<script>
window.onload = function() {
document.getElementById("demo2").innerHTML = "Yes, Successfully changes" ;
}
</script>
Both approaches work on the page itself, but import that page using AJAX, and only the onclick method works. This issue persists when trying both JavaScript and JQuery. What am I missing?
Try registering an event handler using jQuery's .ajaxcomplete http://api.jquery.com/ajaxcomplete/ . This event gets fired when an AJAX request finishes which is probably what you are looking for.
User the following way to update the content using Ajax
<div id="demo">Let AJAX change this text</div>
<button type="button" onclick="loadDoc()">Try it</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
Go to following link for more ajax examples.
Ajax Examples
<script>
$(document).ready(function(){
$.ajax({
url: "ajax_info.txt"
}).done(function( data ) {
$("#demo").html(data);
});
});
</script>
on ready function you can call ajax and change the content
Use jquery ready function and call your function inside ready function.
like this :
$(document).ready(function(){
myFunction();
});
/* jQuery Onload String Replace OR jQuery Onload String Change */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var strNewString = $('body').html().replace(/\On hold/g,'Processing');
$('body').html(strNewString);
});
</script>
Related
I need to load a file in div on click of another div :
My code so far :
<div id="load_home">HOME </div>
<div id="content"></div>
<script>
$(document).ready(function(){
$("#load_home").click(function(){
$("#content").load('code.html');
});
});
</script>
You can use javascript inside the click function to get the HTML file content and attach to the content div like this
<div id="load_home">HOME </div>
<div id ="content"></div>
<script>
$(document).ready(function(){
$("#load_home").click(function(){
document.getElementById('content').innerHTML = loadContent();
});
});
function loadContent(){
var xmlhttp = new XMLHttpRequest();
var pathToFile = 'code.html';
xmlhttp.open("GET", pathToFile , false);
xmlhttp.send();
return xmlhttp.responseText;
}
</script>
Notice that pathToFile variable holds the actual path of the html file you want to render.
I have the following script in my HTML, however I get a Question mark instead of the actual IP:
<script type="application/javascript">
var myButton = document.getElementById("clickButton");
var myText = document.getElementById("helloText");
myButton.addEventListener('click A', doSomething(), false);
function doSomething(json) {
myText.textContent = (json.ip);
}
function getIP(json) {
return json.ip;
}
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP">
</script>
The problem is that doSomething doesn't receive the JSON as an argument. You need getIP to put the returned IP into a global variable, and then doSomething can display it.
var myButton = document.getElementById("clickButton");
var myText = document.getElementById("helloText");
myButton.addEventListener('click', doSomething, false);
function doSomething() {
myText.textContent = IP;
}
<script type="application/javascript">
var IP;
function getIP(json) {
IP = json.ip;
}
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP">
</script>
<button id="clickButton">Show IP</button>
<div id="helloText"></div>
Also, the second argument to addEventListener should just be the function name, not a call to the function. And the first argument should just be the name of the event. There's no click A event, just click.
The function getIP() gets called when the //api.ipify.org script is loaded. Your getIP() function just returns the ip address. Other than that it does not do anything. Try doing something like this:
<div id="mydiv"></div>
<script>
var getIP = function(json) {
document.getElementById("mydiv").innerHTML = json.ip;
}
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP">
</script>
I am using a PHP Simple HTML DOM Parser to save a website as a htm file. I then use jQuery to extract a div from the file and put it into a div. I want to create a
Previous and Next button but the problem I have is that to do this I have to change the URL so the parser can get the page. I would really appreciate if you can help. Below is the code I am using.
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=1');
$html->save('site/rtnews.htm')
?>
<script type="text/javascript" src="site/jquery.js"></script>
<script type="text/javascript">
$('document').ready(function() {
$('#wrap').click(function (event){
event.preventDefault();
});
$("#wrap").load('site/rtnews.htm #postsArea');
});
</script>
</head>
<body>
<div id="wrap">
</div>
</body>
You will have to create a new php file for this and make an AJAX request to that file. I assume you have already realised that you cannot make a cross-domain request due to CORS.
Here is your new php file, let's call it proxy.php. It will proxy the request, responding with the page that is passed to it via GET :
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=' . $_GET["page"]);
echo $html;
?>
Your new JavaScript;
$('document').ready(function() {
var $wrap = $('#wrap'),
page = 1;
$('#next').on('click', function () {
getPage(++page);
});
$('#prev').on('click', function () {
getPage(--page);
});
var getPage = function (page) {
$wrap.load('proxy.php?page=' + page + ' #postsArea');
};
getPage(page);
});
For jQuery template:
http://api.jquery.com/category/plugins/templates/
I want to be able to dynamically load the templates from a server, rather than predefining it on the page.
The demos I saw on the projects are using predefined templates. After some research I found out that it is possible.
I try doing this and it doesn't work:
<script src="child.html" type="text/x-jquery-tmpl"></script>
I tried doing this and it doesn't work:
$(function () {
$.get("child.html", function (data) {
//Add template
$.template("tmplChild", data);
});
//template binds before async call is done
$.tmpl("tmplChild").appendTo("body");
});
And finally, I have get it down to the following hack:
so.html (This is the main page):
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
<script type="text/javascript" src="so.js"></script>
<script type="text/javascript">
$(function () {
initTemplates(templateReady);
});
function templateReady() {
$.tmpl("tmplChild").appendTo("body");
}
</script>
</body>
</html>
child.html (This is the child template)
<h1>Child Loaded</h1>
so.js (This is my hack for ajaxly loading the js templates)
function initTemplates(callback) {
var templateUrl = "child.html";
var templateName = "tmplChild";
initTemplate(templateUrl, templateName, callback);
}
function initTemplate(url, name, callback) {
var opts =
{
type: "GET",
url: url,
dataType: ($.browser.msie) ? "text" : "xml",
success: function (data) {
xmlCallback(data, name, callback);
},
error: function (x) {
xmlCallback(x.responseText, name, callback);
}
}
$.ajax(opts);
}
function xmlCallback(data, name, callback) {
if (typeof data != "string") {
if (window.ActiveXObject) {
var str = data.xml;
data = str;
}
// code for Mozilla, Firefox, Opera, etc.
else {
var str = (new XMLSerializer()).serializeToString(data);
data = str;
}
}
//only takes strings!
$.template(name, data);
callback();
}
And here's what I don't like about it.
This doesn't work on Chrome
It seems like a lot of code just to load some template
I lost the ability to use $(document).ready(). I must now put all my code in this templateReady() method to be "template safe".
Is there a way around this?
Thanks,
Chi
Just load the template body as simple text and forget about putting it in a dummy <script> block. You can use $.tmpl(body, params) to populate the template and turn it into a string for appending to the DOM.
The whole thing with "not really script" <script> blocks is just a convenience useful in some situations.
edit — example:
$.get("/some/url/for/a/template", function(templateBody) {
var expandedTemplate = $.tmpl(templateBody, { param1: 0, param2: "Hello World" });
});
If the goal is to fetch a unique template each time you get data via ajax, then you might try fetching the template at the same time and include it in your data, that is if you have the luxury of modifying the returned object (anonymous object in .Net). Then you can store the template anywhere you want and you only need 1 ajax call for both the data and the template.
Refer here:
https://www.npmjs.com/package/jlate
use CDN:
<script src="https://cdn.jsdelivr.net/combine/npm/lodash,npm/jlate#0.0.2/jlate/JLate.min.js"></script>
HTML Code:
<body>
<div>
<jlate id="my_temp" src="template/jlate_title.html" type="template">
Loading...
</jlate>
</div>
</body>
Javascript:
$$("#my_temp").jlate({ title: "sample title"});
I'm trying to retrieve data from a php file named return that just contains
<?php
echo 'here is a string';
?>
I'm doing this through an html file containing
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var x;
$.get("return.php", function(data){
x = data;
})
function showAlert() {alert(x);}
$(document).ready(function(){
alert(x);
});
</script>
</head>
<body>
<input type = "button" value = "Click here" onClick="showAlert();">
</body>
</html>
When the button is clicked it retrieves and displays the code fine, but on the $(document).ready thing, it displays "undefined" instead of the data in return.php. Any solutions?
Thanks.
the document.ready is running before the $.get has returned the msg probably
var x;
function showAlert() {alert(x);}
$(document).ready(function(){
$.get("return.php", function(data){
x = data;
showAlert();
})
});
that should work fine
The ajax probably has not loaded yet.
var x;
function showAlert() {alert(x);}
$(document).ready(function(){
$.get("return.php", function(data){
x = data;
alert(x);
});
});
It isn't a question of scope, it's a question of order of events. $.get is an asynchronous call, so it may not finish yet by the time your page loads in the browser (it's a fairly small page so I imagine it loads quite quickly).