The code below is not triggered as per the interval set in the setInterval. When the page is loaded the first time the result set is returned, but the Ajax script does not run after first time page load.
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>
<!-------------------------------------------------------------------------
1) Create some html content that can be accessed by jquery
-------------------------------------------------------------------------->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output"></div>
<script id="source" language="javascript" type="text/javascript">
$(function getEvent()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'get_events.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
var time = row[2];
$('#output').append("<b>id: </b>"+id+"<b> name: </b>"+vname+"<b> time: </b>"+time)
.append("<hr />");
}
}
});
});
$(document).ready(function () {
var run = setInterval(getEvent, 1000);
});
</script>
</body>
</html>
I have looked at all the similar posts in this forum, but I still can't get my function to be triggered by setInterval. Please see my code below. Any help is appreciated.
Looks like your function is not in the global scope. Setinterval doesn't know about it.
Use var getEvent = function() { ... } to declare the function rather than $ wrapper.
By doing this
$(function functionName(){/*function body*/})
you are passing a function to another function called $. This doesn't create a function called functionName anywhere. So, when you are starting your interval, you are trying to call a function which does not exist.
Remove $() from around your function declaration. This will define a function rather than pass it as a parameter.
Related
I need to store JSON result in some variable and then i want to use that variable inside BODY of html.
Below is my code in which i am getting nothing in "test" alert.
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var msg;
$(document).ready(function () {
var msg1;
$.ajax({
url: "http://rest-service.guides.spring.io/greeting"
//var msg2;
}).then(function(data) {
json_list = data.id;
msg= data.id;
msg1= data.id;
var $temp = $('.class1').append(data.content);
//alert($temp);
//msg2= data.id;
/* $('.greeting-content').append(data.content); */
alert("Inside AJAX "+data.content);
$('#content').html(data.content);
//msg=$('#content').html();
//return msg;
// $('.greeting-id').append(data.id);*/
// alert(msg);
});
});
</script>
<div id="content"></div>
<div class="class1">
</div>
<script>
var test1=$('#content').contents();
alert("Test Result -- " +test1);
</script>
</body>
</html>
Can you pls suggest me how i can achieve this ?
I want to store JSON value in test1 variable (in BOLD).
Let me know if any further info required.
Ajax is not time travel.
Your code:
Sets up a document.ready event handler
Takes the content of #content and puts it in a variable and then alerts it.
(in response to the ready event firing) makes an Ajax request and sets up an event handler for when an HTTP response is received
(in response to the HTTP response) changes the contents of #content
By that stage the code that assigns the variable has already run. The code that alerts the value of that variable has already run.
If you want to do anything with that content, then do so inside the success handler.
Just pass the data into parseJSON(data) and than use
$(document).ready(function () {
var msg1;
$.ajax({
url: "http://rest-service.guides.spring.io/greeting"
//var msg2;
}).then(function(data) {
// see here i change.
var data_json = jQuery.parseJSON(data);
json_list = data_json.id;
//bellow is function.
passinganotherscript(json_list);
msg= data_json.id;
msg1= data_json.id;
var $temp = $('.class1').append(data_json.content);
$('#content').html(data_json.content);
});
function passinganotherscript(data){
//here you are able to access your value of data.
}
I hope this will help you
I'm using YQL and jQuery.ajax to retrieve an inline JavaScript variable from another website. This variable contains a complete XML document that base64 encoded.
While the AJAX request is working, I can't figure out how to take the res.query.results and append it to a dynamically made <script> element.
Here's the jQuery:
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql/dj/fsp?format=json",
type: "GET",
success: function(res) {
var sc = $('script');
$(sc).append(document.createTextNode('var '+$(res.query.results)));
$('head').append(sc);
}
});
Here's what the console log is telling me:
Any ideas or suggestions would be greatly appreciated. Thanks, everyone!
Three things:
To create a script element, you do $('<script>'), not $('script'). The latter searches for all script elements.
No need for createTextNode, jQuery will handle that for you.
You're over-doing it with the calls to $():
var sc = $('<script>');
sc.append(document.createTextNode('var '+res.query.results));
// ^ #1 (see below) ^ #2
You don't want to do $(sc) again, it's pointless, it's already a jQuery instance.
You don't want to parse res.query.results into a jQuery instance, you want to grab the string into a JavaScript variable (apparently).
Live example:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<script>
(function() {
"use strict";
display("Doing query...");
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql/dj/fsp?format=json",
type: "GET",
success: function(res) {
display("Got result, creating <code>script</code>...");
var sc = $('<script>');
sc.append('var '+res.query.results);
$('head').append(sc);
display("length of <code>txt</code> global variable: " + window.txt.length);
}
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
I'm using jQuery AJAX to get an array from a PHP file which is getting data from a MySQL database. I'm now trying to use that array outside my ajax call. Specifically I'm loading multiple videoIDs for YT.Player but I'm stumbling on getting my array to another function.
Here's my testing code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var data = new Array();
$(document).ready( function() {
$.ajax({
type: 'POST',
url: 'test.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
data = result;
$('#div1').html(result[4]);
},
});
});
$("button").click(function(){
alert(data[4]);
});
</script>
</head>
<body>
<button id="button">Test</button>
<div id="div1"><h2>div1</h2></div>
</body>
</html>
The div changes a half second after the page loads as expected. The click function for testing doesn't work, and its not working in the real function I'm working on:
function onPlayerStateChange(event) {
if(event.data === 0) {
++i;
player.loadVideoById(data[i]);
}
}
This is my first project with jQuery and JS so I'm hoping I'm missing something simple
You should put
$("button").click(function(){
alert(data[4]);
});
inside
$(document).ready( function() {
});
Also, if you put var before variable then it becomes local variable.
So, you should either remove var before
data = new Array();
or just put as a additional parameter
function onPlayerStateChange(event, data) {
if(event.data === 0) {
++i;
player.loadVideoById(data[i]);
}
}
but then you also need to call it inside
$(document).ready(function() {} );
scope.
I currently have this javascript/ajax request for my advanced search page
<script>
// window.setInterval(function()
// {
$(function ()
{
var SearchTerm = '<?php echo $_POST['Search']; ?>';
$.ajax({
url: 'Ajax/AjaxAdvSearch.php?SearchTerm='+SearchTerm, dataType: 'json', success: function(rows)
{
$('#output').empty();
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var FunctionName = row[1];
$('#output').append("<a href='Page.php?ID="+id+"'>"+FunctionName+"</a><br>");
}
}
});
});
// }, 5000);
</script>
The $_POST['Search']; is obtained from a HTML textarea:
<textarea name='Search' style='width: 100%; height: 150px;'></textarea><br>
I want to dynamically update my javascript var each time the user types into the textarea, without the user having to press the submit..
so whilst the user is typing, the var SearchTerm is dynamically updated each time the textarea is updated with content.
Could anyone provide some assistance?
Use the .change() method in jQuery
var variableToUpdate = '';
$('#Search').change(function() {
variableToUpdate = $(this).val();
// call your search from within if you want
});
For search-as-you-type tutorials and plugins...
http://dbachrach.com/blog/2007/04/spotlight-like-search-as-you-type-with-css-ajax-js/
http://www.jquery4u.com/plugins/14-jquery-live-search-plugins/
Let me provide you an example
<html>
<head><style>
</style>
<script>
var DataCon;
function UpdateDIV(){
document.getElementById('updater').innerHTML=DataCon;
}
</script>
</head><body>
<div id="updater">
</div>
<textarea onkeydown="DataCon=this.value;UpdateDIV()"></textarea>
</body>
</html>
And here you can see, as you type a global variable updates and along with it, to check its working a UpdateDIV function also given which updates the div with id updater...
Now just assign certain vars and get your job done
I am having trouble with jQuery with trying to modify a global variable from within the success callback:
<html>
<head>
<script type="text/javascript" src="javascript/jquery.min.js"></script>
<script type="text/javascript">
// Define items in the global scope
items = null;
// Get items from XML for a given category ID
function getItems(categoryID)
{
$.ajax({
type: 'GET',
url: 'items.xml',
dataType: 'xml',
success: function(xml){
items = $(xml).find('category[id="'+categoryID+'"]').children().first();
// This works (returns the name of the first item)
alert( items.attr('name') );
}
});
}
</script>
</head>
<body>
<script type="text/javascript">
$(function(){
getItems(1);
// This doesn't work (returns null)
alert( items.attr('name') );
});
</script>
</body>
</html>
What am I doing wrong?
This is because the callback hasnt finished by the time you are executing the alert.
the Get request is asynchronous so execution continues even if it has not finished. So when the alert() statement executes, the success callback has not yet executed, therefore items is still null.
You can either do a synchronous call, or include whatever you are trying to do inside the success callback.