How to save a php variable value to javascript variable using $.get()? - javascript

I have a function like this:
jQuery.fn.stickyNotes.createNote = function(root) {
var record_no;
$.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
alert(resp);
record_no=resp;
})
var note_stickyid = record_no;
...
}
The max_record.php looks like this:
<?php
require_once('../../config.php');
global $DB;
$max_id = $DB->get_record_sql('
SELECT max(stickyid) as max_id
FROM mdl_block_stickynotes
');
$stickyid= $max_id->max_id+1;
echo $stickyid;
?>
I wondering why records_no has no value in it, while resp is showing right value in alert.

This line is your problem:
var note_stickyid = record_no;
The $.get() function above it is asynchronous, so it's trying to assign this value before the function has completed. Assign the variable inside the callback:
var note_stickyid;
$.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
alert(resp);
record_no=resp;
note_stickyid = record_no;
}).done(function() {
alert(note_stickyid); //Works because it waits until the request is done
});
alert(note_stickyid); //This will alert null, because it triggers before the function has assigned!
In your case, you'll probably want to pass in a callback function so you can actually use this variable, here's a sample callback function:
function callback(param) {
alert(param);
}
Now setup another parameter for your createNote:
jQuery.fn.stickyNotes.createNote = function(root, callback) {
Now use that callback inside the $.get:
var note_stickyid;
$.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
alert(resp);
record_no=resp;
note_stickyid = record_no;
callback(note_stickyid);
});

Try this:
var record_no= '';
$.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
alert(resp);
record_no+=resp;
})

Related

How to Store call back function name inside javascript object and call

i am trying to build this function data get an JavaScript object and process that some time it's need a call back function so i am trying pass that function inside the object but when i call this it's says function dosen't exist and yet still this function exist and when i pass this as parameter it's working this only happen when i get callback function name from JavaScript Object
function Ajax(data){
//ajax stuff
var filtered_respons = response_from_ajax;
//tryed this all not working
data['callback'](filtered_response,'loading');
var fun_name = data['callback'];
fun_name(filtered_response,'loading');//
}
Updated
and from html page i am calling this function as this
let data = {
url:'./assets/php/category.php',
type:'POST',
callback :'toprender',
data:{all_cats:1},
element_name:'cat'
}
Ajax(data);
And when i try this way it's working
AjaxCaller(data,topfunction,true);
This is the whole function
AjaxCaller(data,callback,need){
var loader= "";
if(typeof data['loader'] !== "undefined"){
loader = $("#"+data['loader']);
}else{
loader = $("#loading");
}
loader.show();
if(typeof data['url'] !== "undefined" && typeof data['type'] !== "undefined"){
var $self = this;
$.ajax({
url:data['url'],
type:data['type'],
data:data['data'],
success:function(response){
loader.hide();
var response = JSON.parse(response);
var filtered_response = $self.ajaxError(response);
if(need==true){
callback(filtered_response,data['element_name']);
}
}
});
}else{
console.log('Please Re Check The Objects');
}
}
You're trying to use a string as a function. You can't do that.
You probably just want to change callback :'toprender' to callback :toprender:
let data = {
url:'./assets/php/category.php',
type:'POST',
callback :toprender,
data:{all_cats:1},
element_name:'cat'
}
Ajax(data);
That sets callback to the fucntion, rather than a string.
Live Example:
function toprender() {
console.log("toprender called");
}
function Ajax(data) {
data.callback();
}
let data = {
url:'./assets/php/category.php',
type:'POST',
callback :toprender,
data:{all_cats:1},
element_name:'cat'
}
Ajax(data);

Passing a variable into a JavaScript Function

I have written a Javascript Function
jQuery(document).ready( function newbie($) {
//var email = 'emailaddress'
var data = {
action: 'test_response',
post_var: email
};
// the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
$.post(the_ajax_script.ajaxurl, data, function(response) {
alert(response);
});
return false;
});
Which I will call using
newbie();
But I want to pass in a variable (the email address) when I call the function but I am not sure how to do this. That $ sign seems to get in my way! Any thoughts much appreciated.
jQuery(document).ready(function(){
var email = 'emailaddress';
newbie(email);
});
function newbie(email) {
var data = {
action: 'test_response',
post_var: email
};
// the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
$.post(the_ajax_script.ajaxurl, data, function(response) {
alert(response);
});
return false;
}
OR
jQuery(document).ready(function(){
var newbie = function(email) {
var data = {
action: 'test_response',
post_var: email
};
// the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
$.post(the_ajax_script.ajaxurl, data, function(response) {
alert(response);
});
return false;
}
var email = 'emailaddress';
newbie(email);
});
Functions in javascript take 'arguments'. You can pass in as many arguments you want and define their name space in the function declaration. ie
function foo(bar,baz,etc){
console.log(bar,baz,etc);
}
foo(1,2,3)
//logs out 1 2 3
Sometimes you don't always know what's going to be passed in or how many arguments there are going to be, in this case inside of the function declaration we can use the 'arguments' object to pick out certain arguments passed into the function.
function foo(){
console.log(arguments);
}
foo(1,2,3)
//logs out an array object that looks like this [1,2,3]
jQuery(document).ready( function newbie($, email) {
//var email = 'emailaddress'
var data = {
action: 'test_response',
post_var: email
};
// the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
$.post(the_ajax_script.ajaxurl, data, function(response) {
alert(response);
});
return false;
});
you simply call the function by passing the values

How to pull JSON data from two different sources?

I was wondering if there is a way to pull and use JSON data from two different sources. Currently, the code looks like this:
//JSON1
$.getJSON('url1',function(data){
$.each(data,function(key,val){
//code
});
});
//JSON2
$.getJSON('url2',function(data){
$.each(data,function(key,val){
//code
});
});
When I do this, i seems that variables created from one JSON function aren't available in the other one, which makes it hard for them to be useful together.
Is there a better way to have these two work together?
This function takes an array of urls and a callback as parameters:
function getMultiJSON(urlList,callback) {
var respList = {};
var doneCount = 0;
for(var x = 0; x < urlList.length; x++) {
(function(url){
$.getJSON(url,function(data){
respList[url] = data;
doneCount++;
if(doneCount === urlList.length) {
callback(respList);
}
});
})(urlList[x]);
}
}
You would use it like this:
getMultiJSON(['url1','url2'],function(response) {
// in this case response would have 2 properties,
//
// response.url1 data for url1
// response.url2 data for url2
// continue logic here
});
You might want to add a timeout as the function will never call your handler should any of the URLs fail to load
Variable declared within the functions using var (or blocks, using let) are not available outside of the functions (or blocks).
$.getJSON('url1',function(data){
$.each(data,function(key,val){
var only_accessible_here = key;
});
});
So if you want variables that are accessible outside the scope of the function they are declared in, you need to declare them outside of the function they are used in.
var combined_stuff = ''
$.getJSON('url1',function(data){
$.each(data,function(key,val){
combined_stuff += val;
});
});
//JSON2
$.getJSON('url2',function(data){
$.each(data,function(key,val){
combined_stuff += val;
});
});
As Marc B says, there is no way to know which order the combined_stuff variable will be updated, either by JSON1 first, or by JSON2 first, or by only one, if one of the getJSON calls fail, or by neither if both fail.
If the order of updating is important, call the one you want to use second in the function of the one you want to call first.
var combined_stuff = ''
$.getJSON('url1',function(data){
$.each(data,function(key,val){
combined_stuff += val;
//JSON2
$.getJSON('url2',function(data){
$.each(data,function(key,val){
combined_stuff += val;
});
});
});
});
Easily using the open source project jinqJs (http://www.jinqJs.com)
var data1 = jinqJs().from('http://....').select();
var data2 = jinqJs().from('http://....').select();
var result = jinqJs().from(data1, data2).select();
The example does a sync call, you can do an async call by doing something like this:
var data1 = null;
jinqJs().from('http://....', function(self){ data1 = self.select(); });
Result will contain both results combined.
If you control the endpoint, you could make it return all of the data you want in one shot. Then your data would look like:
{
"url1_data": url1_json_data,
"url2_data": url2_json_data
}
If you still have 2 endpoints you need to hit, you can pass the result of your first ajax call to the second function (but this makes your 2 ajax calls synchronous):
function getJson1(){
$.getJSON('url1',function(data){
getJson2(data);
});
}
function getJson2(json1Data){
$.getJSON('url2',function(data){
//Do stuff with json1 and json2 data
});
}
getJson1();
I would recommend you to use $.when function available in jquery to execute both the methods in parallel and then take the action. See the code snipped below,
var json1 = [], json2 = [];
$.when(GetJson1(), GetJson2()).always(function () {
//this code will execute only after getjson1 and getjson2 methods are run executed
if (json1.length > 0)
{
$.each(json1,function(key,val){
//code
});
}
if (json2.length > 0)
{
$.each(json2,function(key,val){
//code
});
}
});
function GetJson1()
{
return $.ajax({
url: 'url1',
type: 'GET',
dataType: 'json',
success: function (data, textStatus, xhr) {
if (data != null) {
json1 = data;
}
},
error: function (xhr, textStatus, errorThrown) {
json1 = [];//just initialize to avoid js error
}
}
function GetJson2()
{
return $.ajax({
url: 'url2',
type: 'GET',
dataType: 'json',
success: function (data, textStatus, xhr) {
if (data != null) {
json2 = data;
}
},
error: function (xhr, textStatus, errorThrown) {
json2 = [];//just initialize to avoid js error
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
The returned data from each AJAX call are not available outside its own callback function. I'm sure there are more elegant (complex?) solutions, but a couple of simple, Occamic, solutions include global variables, or storing the received data in hidden input elements.
Within each callback function, just loop until the data from the other call is present:
function getJson1(){
$.getJSON('url1',function(data){
var d2 = '';
$('#hidden1').val(data);
while ( d2 == '' ){
//you should use a time delay here
d2 = $('#hidden2').val();
}
getJson2();
});
}
function getJson2(){
$.getJSON('url2',function(d2){
var d1 = '';
$('#hidden2').val(d2);
while ( d1 == '' ){
//you should use a time delay here
d1 = $('#hidden1').val();
}
//Do stuff with json1 and json2 data
});
}
getJson1();

jQuery getting jSon data but not returning/assigning value

I am using jQuery to call a controller, the controller is returning a value. the jQuery is getting the value however it is not setting it to my variable and returning it. what am I doing wrong here?
GetDepartmentID is called with a value of 1. It goes to the controler, the controller returns the departmentID which is 1.
console.log("Inside-DepartmentID " + data) in the console this shows 1 so I know the data is being returns from the controller.
I then assign data to departmentID. Return it. Then my outer function tries to console.log the return and it is undefined. I don't get it.
The .change function calls the GetdepartmentID(1);
function GetDepartmentID(functionID) {
var departmentID;
jQuery.getJSON("/MasterList/GetDepartmentID/" + functionID, null, function (data) {
console.log("Inside-DepartmentID " + data)
departmentID = data;
});
return departmentID;
}
jQuery('#functionID').change(function () {
var functionID = jQuery(this);
//console.log(functionID.val());
var value = GetDepartmentID(functionID.val());
console.log("test " + value);
//GetOwnerList(value);
});
You can try this way to process the data returned back from AJAX call.
function processResults(departmentID)
{
console.log("test " + departmentID);
GetOwnerList(departmentID);
// Someother code.
}
function GetDepartmentID(functionID, callBack) {
jQuery.getJSON("/MasterList/GetDepartmentID/" + functionID, null, function (data) {
console.log("Inside-DepartmentID " + data)
callBack(data); //Invoke the callBackhandler with the data
});
}
jQuery(function(){
jQuery('#functionID').change(function () {
var functionID = jQuery(this);
//console.log(functionID.val());
GetDepartmentID(functionID.val(), processResults); // pass function as reference to be called back on ajax success.
});
});
Or just do this way: This is as good as putting all your subsequent processing code inside your getJSON handler.
function processResults(data)
{
//handle the data here.
}
function GetDepartmentID(functionID) {
jQuery.getJSON("/MasterList/GetDepartmentID/" + functionID, null, processResults);
}
jQuery(function(){
jQuery('#functionID').change(function () {
var functionID = jQuery(this);
//console.log(functionID.val());
GetDepartmentID(functionID.val()); // pass function as reference to be called back on ajax success.
});
});

Passing data from variables in JavaScript

I have created a small JavaScript application with the following function that calls a function to retrieve JSON data:
var months = function getMonths(){
$.getJSON("app/data/Cars/12Months", function (some_data) {
if (some_data == null) {
return false;
}
var months_data = new Array();
var value_data = new Array();
$.each(some_data, function(index, value) {
months_data.push(index);
value_data.push(value);
});
return[months_data,value_data];
});
}
I have then created, in the same file, another function that does something when a specific page is loaded. In this function the variable 'months' is passed to the variable 'result'.
$(document).on('pageshow', '#chartCar', function(){
$(document).ready(function() {
var result = months;
var date = result[0];
var values = result[1];
//more code here...
});
}
the problem is that, based on the debugger, the getMonths() function works fine and produces the expected output, but the 'result' variable in the second function can't obtain the values passed to it by the variable 'months'. Do you know how to solve this issue?
The problem is that you $.getJSON() function is asynchronous, so your data gets loaded later then you read it. There're two workarounds:
1. Replace your $.getJSON with $.ajax and setting async: false;
2. Put your code in $.getJSON callback:
var months = function getMonths(){
$.getJSON("app/data/Cars/12Months", function (some_data) {
if (some_data == null) {
return false;
}
var months_data = new Array();
var value_data = new Array();
$.each(some_data, function(index, value) {
months_data.push(index);
value_data.push(value);
});
var date = months_data;
var values = value_data;
//more code here..
})
}
There must be a syntax error.
replace
});
}
With
});
});
$.getJSON() is a wrapper around $.ajax which is async by default. But you treat it like a sync call.
You can use $.ajaxSetup()
$.ajaxSetup( { "async": false } );
$.getJSON(...)
$.ajaxSetup( { "async": true } );
or use $.ajax with async: false
$.ajax({
type: 'GET',
url: 'app/data/Cars/12Months',
dataType: 'json',
async: false,
success: function(some_data) {
//your code goes here
}
});
or if possible change the behavior of your app so that you process your data in a callback function.

Categories