using AJAX results variable throughout code - javascript

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.

Related

Chargebee: Uncaught TypeError: this.page.urlFetcher(...).then is not a function

I am currently trying to include the chargebee drop in script into a website, but when I call it with the hosted page object, I get the error
Uncaught TypeError: this.page.urlFetcher(...).then is not a function
I wrote a small script to replicate the error:
<!DOCTYPE html>
<html>
<head>
<script src="https://js.chargebee.com/v2/chargebee.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
/* Initialize a Chargebee instance after mounting the root component. */
var chargebeeInstance = Chargebee.init({
site: "..."
});
// You can access the above created instance anywhere using the following code
var chargebeeInstance = Chargebee.getInstance();
});
$( document ).ready(function() {
$("button").click(function() {
var chargebeeInstance = Chargebee.getInstance();
chargebeeInstance.openCheckout({
hostedPage: function() {
return {"expires_at":...,"updated_at":...,"created_at":..,"id":"...","state":"created","embed":true,"type":"checkout_new","resource_version":...,"url":"...","object":"hosted_page"};
},
success: function(hostedPageId) {
// success callback
}
});
});
});
</script>
</head>
<body>
<button> click me </button>
</body>
</html>
After checking back with the support, it turned out that the hosted page function should return an ajax call (promise).
Here is an example from the docs:
return $.ajax({
method: "post",
url: "http://localhost:8000/api/generate_checkout_new_url",
data: {
plan_id: "cbdemo_scale"
}
});

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.

Ajax: link in ajax response is not working

I have tried all possible solutions suggested, but it is still not working for me.
I am using ajax call to a php page, say livesearch.php, from index page to get live search result.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$("#livesearch").on("click", "a.alert", function() {
alert("here");
});
</script>
<script>
function showResult(str) {
if (str.length == 0) {
$("#livesearch").empty();
$("#livesearch").css('display', 'none');
return;
}
$.ajax({
type: "GET",
url: "livesearch.php?q=" + str,
success: function(responseText) {
$("#livesearch").html(responseText);
$("#livesearch").css('display', 'block');
$("#livesearch").css('background', '#fff');
}
});
}
</script>
</head>
<body>
<form>
<input type="text" size="30" onkeyup="showResult(this.value)" onblur="showResult('')" placeholder="search here">
<div id="livesearch" style="height:500px;width:900px;overflow-y:scroll;display:none;z-index:99999;"></div>
</form>
<div id="gentext" style="position:fixed;top:40px;z-index:-1;">This is just a dummy text to check if result div overshadow this line or not.</div>
</body>
</html>
It works fine and list possible search.
Now from search results, a user can click on a page to browse it - simple. As soon as one click's on the link, I want to catch that and do some processing. See below section in above code:
$("#livesearch").on("click", "a.alert", function() {
alert("here");
});
To begin with, I am testing, if I am able to capture click on this link returned from ajax search or not - so alert("here"), but it is not working.
Please hep
Define the click method after appending the links:
success: function(responseText)
{
$("#livesearch").html(responseText);
$("#livesearch").css('display', 'block');
$("#livesearch").css('background', '#fff');
$("#livesearch").on("click", "a.alert", function()
{
alert("here");
});
}
Try this, and let us know what the console returns:
$.ajax({
type: "GET",
url: "livesearch.php?q=" + str,
success: function(responseText) {
console.log(responseText); //CHECK YOUR CONSOLE
$("#livesearch").append(responseText);
$("#livesearch").css('display', 'block');
$("#livesearch").css('background', '#fff');
$("#livesearch").find(".alert").click(function(e) {
e.preventDefault();
alert("here");
});
}
});
Another way to accomplish this is to build your anchor tag like this , then create the JS function:
myFunction(){
alert("here")
return false;
}

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.

AJAX load page and reload/add after success

So I have a page which, when requested, updates my database. For example when I go to database_update.php it just updates the database and doesn't show anything.
Index.php shows user database content.
So I have function in JavaScript called update which must use AJAX to run this page and after the page loads (after all queries run successfully) it must load index.php and show updated page to the user (reload the page without refresh effect).
My code is like:
$.get('ajax_update_table.php', {
// The following is important because page saves to another table
// users nick which call update:
update: UserLogin
}, function (output) {
// The following is unimportant:
$(myDiv).html(output).show();
});
Two suggestions:
Return a "success" or "error" code from your database_update script. Returning a JSON string is very easy. For example:
echo '{"success":"success"}';
Use the $.ajax function. Then add the success, error, and complete parameters. You can call any javascript function(s) when the AJAX request is complete.
$.ajax({
url: 'update_database.php',
dataType: 'json',
success: function (data) {successFunction(data)},
error: function () { error(); },
complete: function () { complete(); }
});
function successFunction(data) {
if ('success' in data) {
// Do success stuff here.
} else {
// Show errors here
}
}
// .... etc
I might be missing something, but I'll try to answer your question.
I would setup a blank page that on loading it sends the index.php to a div on that page. For example, make a page titled blank.php.
blank.php would have the following:
function Index(){
$.ajax({
url:"index.php",
type: "GET",
success:function(result){
$("#web-content").html(result);
}
});
}
<script type="text/javascript">Index();</script>
<div id="web-content"></div>
You would then have your index execute the Index function to update the web-content div with the index.php data without reloading the blank.php page.
Got it to work!
my index.php
<html>
<head>
<script type="text/javascript" language="Javascript" SRC="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript" language="Javascript">
function update_and_replace()
{
$.ajax({
url: 'ajax_update_table.php',
dataType: 'json',
success: function (data) {successFunction(data)},
error: function () { error(); },
complete: function () { complete(); }
});
}
function successFunction(data) {
if ('success' in data) {
$("#content").load("index.php");
}
}
</script>
</head>
<body>
<div id='content'>
Now is: <?php echo date("Y-m-d, H:i:s");?>
<br/><br/><br/><br/>
Aktualizuj
</div>
</body>
</html>
Ajax_update_table.php
<?php echo '{"success":"success"}'; ?>
Thank You all for your help.
I know that my English is bad but with your help I made it!

Categories