I've been trying to get my website to do live comments (so the comments appear without refreshing the page) using AJAX with jQuery (the rest of the code being in PHP and HTML). This is the code I have been using, however it doesen't seem to want to work - comments.php is the file which displays the comments, the $comments being variable for the comments.
<script type="text/javascript">
var int=self.setInterval("showComments()",5000);
function showComments(){
$.post( "ajax_comments.php", function( data ) {
$("#comments).html( data );
});
}
</script>
<script type="text/javascript">
var int=self.setInterval(showComments,5000);
function showComments() {
$.post( "ajax_comments.php", function( data ) {
$("#comments").html( data );
});
}
</script>
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
In the setInterval function the first parameter should be a reference to the function, not a string with the name of the function. The string gets executed using the eval() function, which is not recommended and even though it might not be a problem here it is simply best to avoid.
Related
I am going crazy with .getjson. I am trying to get data from a Wikipedia API using .getjson and it works fine. Let's say the Wikipedia API returns 10 selections, and before looping over each selection, I am trying to find the length of array in a for loop. The data is not available yet from the '.getjson'.
Here is my work in codepen. Look at console.log(sp.length); and sp.length in the for loop. They should give similar data, but one of them is undefined and other is working fine.
Here is my JS code:
$( document ).ready(function() {
var api_wiki="https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&titles=Main+Page&srsearch=cat&srwhat=text&callback=?";
var sp;
$.getJSON(api_wiki,function(data){
sp=data.query.search;
// console.log(sp.length);
}); //End of getJSON
for (var i=0;i<sp.length;i++){
}
});//End of get ready
Why does console.log give two different answers even though they both refer to the same variable? One is undefined and the other is working fine.
I edited the question so that it only reflect the problem facing.
You can't ask javascript to use data it doesn't have yet. You need to wait for the data to arrive. Try putting the for loop inside a function and calling the function in the onReady event of the getJSON:
$( document ).ready(function() {
var api_wiki="https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&titles=Main+Page&srsearch=cat&srwhat=text&callback=?";
var sp;
$.getJSON(api_wiki,function(data){
sp=data.query.search;
console.log(sp.length);
workWithTheData(sp);
}); //End of getJSON
function workWithTheData(sp){
for (var i=0;i<sp.length;i++){
console.log(sp[i]);
}
}
});//End of get ready
$('#loadHere').load('https://www.google.com'); - At present, this loads the Google homepage in <div id="loadHere"></div>.
What I would like to do is somehow store that output as an HTML string in a var instead.
Pseudo-code:
var googleString = parseString($.load('https://www.google.com'));
When googleString is output, it would spit out <html>...<head>...<body>...</html>.
Is this possible?
My ultimate intention is to search through the string for a particular id.
Thank you kindly.
Index.html:
<!--snip-->
<script src="https://.... jQuery file"></script>
<div id="loadHere"></div>
<script src="changePage.js"></script>
<!--snip-->
changePage.js
$(document).ready(function(){
$('#loadHere').load('https://www.google.com');
}
[Edit] - Included snippets of the two files.
The load method of jQuery is a shorthand for the jQuery ajax method. The load method executes the ajax method and outputs the result in an element you provide.
Now, what you would want to do is execute a post or get (or essentially an "ajax") jQuery function that has a success callback.
$.get( "https://www.google.com", function( data ) {
var result = data;
console.log(data);
});
See:
https://api.jquery.com/jquery.ajax/
https://api.jquery.com/jquery.get/
https://api.jquery.com/jquery.post/
You could do that upfront with the load method. From the jquery documentation:
$( "#b" ).load( "article.html #target" );
or for your case
$('#loadHere').load('https://www.google.com #specialDivYoureLookingFor');
If you don't want to do that, you could make the .load return a jquery object then search from there.
$($('#loadHere').load('https://www.google.com')).find('#specialDivYoureLookingFor');
before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>
I am trying to use jQuery to post a variable to the same page using the following code
file.js
$('#sidebar-nav').on('click', 'li', function() {
var theID = $(this).attr('id');
$.post(location.href, {theID: theID});
});
file.php
<?php
if (isset($_POST['theID'])) {
// do something
}
?>
<html>
<!-- the rest of the page -->
</html>
UPDATED
But theID is not posted to the php file for some reason. My code inside the if statement won't execute. In addition, I used this exactly same method for other removeID in the same js and same php files, it's working well for removeID, but not theID.
And to clarify what location.href is in this situation; it is file.php.
Anyone can help me on this?
You have a syntax error on this line:
var theID = $(this).attr('id'));
// -----------------^
You need to remove the extra closing ). Or even better don't call two functions when the property can be accessed directly:
var theID = this.id;
Or better still, since theID is used in only one place get rid of that variable altogether:
$.post(location.href, {theID: this.id});
To send ajax request to the same page you can keep url parameter empty/removed
TRY
<script type="text/javascript">
$.post({
theID: theID,
success: function (data) {
alert("Data Loaded:");
}
});
</script>
How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php