Problem with jQuery AJAX scope - javascript

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.

Related

Trying to pass variable from input radio to PHP via jQuery.post()

I'm trying to load a html table created by a php code. The table should be generated by an sql query that depends on a variable from a radio input selector, but somehow i can't pass that variable via jQuery.post(). I made a simple version that has the same issue so I hope someone can help me with that:
test.php:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function(){
$("input[name$='selectOP']").on("change", function() {
var op = $(this).val();
$.post('ajax.php', {varphp: op});
$("#div1").load('ajax.php', function(){
});
});
});
</script>
<body>
<label class="radio-inline"><input type="radio" value="110" name="selectOP" id="selectOP">110 </label>
<label class="radio-inline"><input type="radio" value="115" name="selectOP" id="selectOP">115 </label>
<div id="div1">
</div>
</body>
</html>
ajax.php:
<?php
$var= "Something";
echo $var;
//$varphp = $_POST['varphp'];
//echo $varphp;
?>
So, with the two last lines of ajax.php commented, code successfully runs and the var $var loads inside div1. But if i uncomment those lines, apparently the code stops, and nothing is loaded on div1. What am I doing wrong?
You are calling $.post where you pass the argument and then calling load with no arguments. Of course you can't get $_POST['varphp'] when you call 'load' because you are not passing this variable.
you must use one of them.
you can do with this:
$.post('ajax.php', {varphp: op}, function(data){ $("#div1").html(data); }, 'html' );
or
$("#div1").load('ajax.php', {varphp: op});
but not both
thus, your code can be
$(document).ready(function(){
$("input[name$='selectOP']").on("change", function() {
var op = $(this).val();
$.post('ajax.php', {varphp: op}, function(data){ $("#div1").html(data); }, 'html' );
});
});
or
$(document).ready(function(){
$("input[name$='selectOP']").on("change", function() {
var op = $(this).val();
$("#div1").load('ajax.php', {varphp: op});
});
});
$.post('ajax.php', {varphp: op});
$("#div1").load('ajax.php', function(){
$});
These two lines are actually making two separate ajax requests, which means the server will pick them up separately. Only the first one has a POST parameter, and only the second one sets the content of the DOM object.
Try something like this:
$("#div1").load('ajax.php', {
varphp: op
});
A good practice I like is to use AJAX w/ deferred promises. You can try converting your code to the following:
$.ajax({
type: 'post', // you can switch to GET, POST, etc.
url: 'ajax.php',
data: {varphp: op},
})
.done(function(data) {
$('#div1').html(data);
})
.fail(function(data) {
// if your code fails, you can see the errors here in the console
console.log(data);
})
.always(function(data) {
// do something every time
});
The codes within the done, fail, or always callback functions will run depending on whether the AJAX call is a success, fail, or neither respectively. With this, you can troubleshoot your code easily as well, especially when the AJAX call error'd out (look inside the fail function).

Ajax - setInterval not triggerd

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.

JQuery AJAX call to php function

I am trying to replace page reloading PHP scripts in a web page with AJAX calls.
I am using JQuery to run the AJAX scripts but it doesn't seem to be doing anything so I attempted to write an incredibly basic script just to test it.
My directory is as follows
public_html/index.php
/scripts/phpfunctions.php
/jqueryfunctions.js
index.php contains
<!DOCTYPE html>
<html>
<head>
<!-- jquery functions -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts/jqueryfunctions.js"></script>
<!-- php functions -->
<?php include 'scripts/phpfunctions.php' ?>
</head>
<body>
<button type="button" id="testButt">TEST</button>
</body>
</html>
Then the phpfunctions.php page which I am trying to call contains just an echo if an argument is set
<?php
if(isset($_GET["action"])) {
echo "test has been run";
}
?>
The jqueryfunctions.js script I am trying to run is
$(document).read(function () {
$('#testButt').on('click', function () {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test',
type: 'GET',
success: function (data) {
$('#ajaxdata').html(data);
},
error: function (log) {
console.log(log.message);
}
});
});
});
I see that the jqueryfunctions.js function is being called by the first console.log but it doesn't seem to be calling my phpfunctions.php function.
I was expecting to see the php echo "test has been run" but this doesn't happen.
Did I miss something?
You should use isset() method:
<?php
if(isset($_GET["action"])) {
if($_GET["action"] == "run_test") {
echo "test has been run";
}
}
?>
and if you are using ajax then why do you need to include it on index page:
<?php include 'scripts/phpfunctions.php' ?>
and i can't find this element $('#ajaxdata') on your index page.
Also you can check the network tab of your inspector tool to see the xhr request to the phpfunctions.php and see if this gets successfull or there is any error.
I think problem is here:
$(document).read(function() {
$('#testButt').on('click', function() {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php',
type: 'GET',
data: {action:'run_test'}, // <------ Here
success: function(data) {
$('#ajaxdata').html(data);
},
error: function(log) {
console.log(log.message);
}
});
});
});
jQuery says:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.
So you should set data: {key:'value'}
Most things look fine, but your data attribute is designed for "POST" requests, try to add the data to the url as follows:
$( document ).read( function ()
{
$( '#testButt' ).on( 'click', function ()
{
console.log( "jquery call worked" ); // this bit does run when button is clicked
$.ajax( { // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test', // Add the GET request to the end of the URL
type: 'GET',
//data: 'action=run_test', Unrequired noise :P (this is for post requests...)
success: function ( data )
{
$( '#ajaxdata' ).html( data );
},
error: function ( log )
{
console.log( log.message );
}
} );
} );
} );
And also (as mentioned in my comments), you need to finish your bodys closing tag:
</body> <!-- Add the closing > in :P -->
</html>
I hope this helps :)
Where do you load ajaxfunctions.js? It look like in your code you never load the resource
And change
<button id="xxx">
In
<button type="button" id="xxx">
So the page isn't reloaded

How to return back json data from script page?

I had a json file results.json Which shown below. And I had a html file contain some script. This is for retrieve data data. When I am enter into the html page which call a script function get_machFollow(que_script) this function is for receive json file data. The function is works fine and which alert correct output, But after this function return some data to my HTML page.
My JSON file
{"mach_fol_4": {"match_l":
["7","8","99"],"attempts":"0","feedback_true":"You are right!",
"feedback_false":"Sorry! wrong answer."}}
This is my script function. This function is works fine but I can't alert the return value from HTML page. That shows undefined.
function get_machFollow(que_script)
{
var return_var;
$.getJSON('results.json', function(data) {
return_var=data[que_script].match_r;
alert(return_var);//Working alert show correct output
return return_var;
});
}
This is my html file
<html>
<head>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script>
$(document).ready(function(){
var mach_follow_js;
mach_follow_js=get_machFollow('mach_fol_4');
alert(mach_follow_js);//Wrong output
});
</head>
<body>
<p>Hello world</p>
</body>
</html>
are you intending return return_var; to be inside the get_machFollow scope, because right now its inside the jquery function scope and will not return value to the main page
Here below JSON data fetched by AJAX. It passing JSON Data Object in Alert.
You can use it as you want. also can Iterate data using for loop or $.each function.
$(document).ready(function(){
var mach_follow_js;
// mach_follow_js=get_machFollow('mach_fol_4');
//JSON Data Fetched by AJAX
$.ajax('results.json',{
type:'GET',
dataType: "json",
jsonCallback: 'successCallback',
async: true,
beforeSend: function () {
//if you want to show loader
},
complete: function () {
//hide loader after download data
},
success: function (resultJSON) {
mach_follow_js = resultJSON; // assigning to Global variable ProductResult
alert(mach_follow_js);
console.log(mach_follow_js);
},
error: function (request, error) {
alert('Network error has occurred please try again!');//error
}
})
});
There are multiple ways by which you can do it. One of them is pass a callback handler to your method which will be called when you get the response. Try this:
function get_machFollow(que_script, sCallback)
{
var return_var;
$.getJSON('results.json', function(data) {
return_var=data[que_script].match_r;
alert(return_var);//Working alert show correct output
sCallback.call(null /* context */, return_var);
});
}
$(document).ready(function(){
var mach_follow_js;
get_machFollow('mach_fol_4', function(output) {
alert(output);
match_follow_js = output;
});
});
Use ajax callback function $.getJSON() is actually an ajax function. So you need to apply callback to perform this action.

using AJAX results variable throughout code

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.

Categories