I have a javascript function which returns me a value . I need to get this value in a variable of my velocity template can someone please help me .
Below is the code I am trying . I know it is not correct I am not getting the value
<script type="text/javascript">
function getCurrentUserTime(key)
{
var user;
$.ajax({
url: "/rest/1.0/compute/TST-30",
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
user = data.sla;
}
});
return user[0].remainingTime;
}
</script>
$key="test"
#set($time=getCurrentUserTime('$key'))
$time
The problem is that the function is trying to return user[0].remainingTime before ajax call has completed. I recommend you handle the return value with callback:
function getCurrentUserTime(key, callback) {
var user;
$.ajax({
url: "/rest/1.0/compute/TST-30",
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
user = data.sla;
if(callback && typeof callback === 'function') {
callback(user[0].remainingTime);
}
}
});
}
getCurrentUserTime('$key', function(val) {
// handle val
});
You can find lots of guides about using callback in javascript via google.
Related
im using the function below to get image names. I also use the json code to get data of a different url, but somehow it isnt working at this. (im new to javascript. Just writing php normally.
function getImgname(name) {
$.getJSON("http://url.com/info.php?name="+name, function(json321) {
return json321.js_skininfo;
});
}
Try this:
function getImgname(myName) {
$.ajax({
url: 'http://url.com/info.php',
data: {
name: myName
},
type: 'POST',
dataType: 'json',
success: function(data) {
// do what you want with your data
return data.js_skininfo;
}
});
}
I tried this now:
function getImgname(myName) {
$.ajax({
url: "http://url.com/ninfo.php",
type: 'POST',
dataType: 'json',
success: function (data) {
return data.js_skininfo;
},
error: function () {
}
});
}
This isnt working (undefinied), but if i alert the data.js_skininfo it shows me the correct value.
I am trying to insert the value of parent into the "getFaculties()" function when i call the function using Ajax.
function ajaxfunction(parent)
{
$.ajax({
type: 'GET',
url: 'Connection.php?getFaculties('+parent')',
success: function(data) {
$("#selFaculty").html(data);
}
});
}
please use a proper way to pass data from ajax to php
function ajaxfunction(parent)
{
$.ajax({
type: 'GET',
url: 'Connection.php',
data: {method:'getFaculties', value:parent}
success: function(data) {
$("#selFaculty").html(data);
}
});
}
The correct syntax is
url: 'Connection.php?faculties='+getFaculties(parent),
Since that is query parameter, given a name to it.
use like this function Declaration was wrong
function ajaxfunction(parent)
{
$.ajax({
type: 'GET',
url: 'Connection.php?getFaculties='+getFaculties(parent),
success: function(data) {
$("#selFaculty").html(data);
}
});
}
Call your function first and get return value in variable and then send your ajax request.
function ajaxfunction(parent)
{
var data_in = getFaculties(parent);
$.ajax({
type: 'GET',
url: 'Connection.php?getFaculties='+data_in,
success: function(data) {
$("#selFaculty").html(data);
}
});
}
Once again I've been beating my head against the wall, trying to pull this part of returned data from ajax to a variable outside the function.
When I return the value it always comes up undefined when I alert() inside it shows the proper values.
function getItemInfo(itemHashPass) {
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
return data.Response.data.inventoryItem.itemName;
}
});
}
I've also tried
function getItemInfo(itemHashPass) {
var tmp = null;
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
tmp = data.Response.data.inventoryItem.itemName;
}
});
return tmp;
}
Like Jonathan said you should write your business logic in the callback or you can try Deferred syntax. In this case it will looks like
function yourBusinnesLogicFunction() {
...
getItemInfo("password_hash_value").done(
function(data){
alert(data.Response.data.inventoryItem.itemName);
}
)
}
function getItemInfo(itemHashPass) {
var tmp = null;
return $.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
})
}
I have below ajax function, which is working fine when I input values for all the fields, but it doesn't work when I do not supply value to any of the three fields (pname,psection, and rinput-json)
<script type="text/javascript">
function saveprof() {
$('.spinner').show();
$.ajax({
type: "POST",
url: "saveprof",
enctype: 'multipart/form-data',
async: true,
data: {
'pname_Aj': $('#pname').val(),
'psection_Aj': $('#psection').val(),
'rinput_Aj' : JSON.stringify(fun()),
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
success: function (data, textStatus, jqXHR) {
$('#message').html(data);
window.location.href = 'myprofile';
window.location('myprofile');
$('.spinner').fadeOut();
}
});
}
</script>
How can I make it work even if the values for any of the fields are not supplied ?
For your information, this call is made to the Django view which does save the fields in the database.
It sounds like those values are optional?
If so, perhaps you can check to see if those values exist, and if not, just submit an empty string:
data: {
'pname_Aj': ( $('#pname').val() || ""),
'psection_Aj': ( $('#psection').val() || ""),
'rinput_Aj' : (JSON.stringify(fun()) || ""),
'csrfmiddlewaretoken':$("input[name=csrfmiddlewaretoken]").val()
},
So if the user has entered values in those sections (and fun() returns something that can be stringified, those variables get submitted. Otherwise, an empty string gets submitted.
If the parameters need to be absent when no value
function saveprof() {
$('.spinner').show();
$.ajax({
type: "POST",
url: "saveprof",
enctype: 'multipart/form-data',
async: true,
data : function() {
var data = {};
var addToData = function(name, val) {
if(val) {
data[name] = val;
}
}
addToData('pname_Aj', $('#pname').val());
addToData('psection_Aj', $('#psection').val());
addToData('rinput_Aj', JSON.stringify(fun()));
addToData('csrfmiddlewaretoken', $("input[name=csrfmiddlewaretoken]").val());
return data;
}(),
success: function (data, textStatus, jqXHR) {
$('#message').html(data);
window.location.href = 'myprofile';
window.location('myprofile');
$('.spinner').fadeOut();
}
});
}
In this code, I would want my "userid" from postgresql, which will be the "response" of ajax or variable "res", to be stored in a global variable "id" so I can use it into future use.
var id;
function addUser()
{
$.ajax({
url: siteloc + scriptloc + "adduser.py",
data: {username:$("#login").val(), password:$("#password").val(), email:$("#email").val()},
dataType: 'json',
success: function (res) {
window.id = res;
console.log(id);
}
});
}
It all goes well in the console.log(id), showing the id in the console. But when I proceed to the next function,
function setpersonalinfo()
{
$.ajax({
url: siteloc + scriptloc + "setpersonalinfo.py",
data: {userID:id,
fullname:$("#fullname").val(),
birthday:$("#birthday").val(),
gender:$("#gender").val() },
dataType: 'json',
success: function (res) {
console.log("Successfully added.");
}
});
}
The id in "userID:id" is not recognized. How do I do this?
Creating an object with the property id like so...
var data = new Object({id: ""});
And then set data.id as the output,
function addUser()
{
$.ajax({
url: siteloc + scriptloc + "adduser.py",
data: {username:$("#login").val(), password:$("#password").val(), email:$("#email").val()},
dataType: 'json',
success: function (res) {
data.id = res;
console.log(data.id);
}
});
}
and in your other function reference data.id,
function setpersonalinfo()
{
$.ajax({
url: siteloc + scriptloc + "setpersonalinfo.py",
data: {userID:data.id,
fullname:$("#fullname").val(),
birthday:$("#birthday").val(),
gender:$("#gender").val() },
dataType: 'json',
success: function (res) {
console.log("Successfully added.");
}
});
}
Sorry about the formatting.
Asynchronously: Inside the addUser()'s ajax success function, call setpersonalinfo() which makes sure that the window.id is already set and ready to use.
Single-ajax: A better way to do this is to simply call setpersonalinfo() and let the server determine if the user exists already, or if no id value is submitted then assume that a new user would have to be created first. Proper input validation would have to detect duplicate user credential anyway, so that's not unnecessary work. setpersonalinfo() would then return a user id and you could set global variables at that time. Or ideally, instead of using globals, you would use closure to protect the value of the user id from being reset using the javascript console.
Synchronous: Just use the "asysc": false property when calling addUser() so that setpersonalinfo() is not called until the user id property is set.
Try this: create a closure that encapsulates your user data handling, then make the returned id a variable within your closure. It's also a good idea to use the following pattern in your js (called 'module').
function Users() {
//Global vars
var newUserId;
var methods = {
add: function(callback) {
$.ajax({
url: siteloc + scriptloc + "adduser.py",
data: { username: $("#login").val(), password: $("#password").val(), email: $("#email").val() },
dataType: 'json',
success: function (res) {
newUserId = res;
console.log(newUserId);
if (typeof(callback) == "function") {
callback();
}
}
});
},
updatePersonalInfo: function () {
$.ajax({
url: siteloc + scriptloc + "setpersonalinfo.py",
data: {
userID: newUserId,
fullname: $("#fullname").val(),
birthday: $("#birthday").val(),
gender: $("#gender").val()
},
dataType: 'json',
success: function (res) {
console.log("Successfully added.");
}
});
}
};
return methods;
}
//Usage example. add() could also pass the new user's id to the callback as a parameter, so
//you wouldn't have to store it at all.
var users = new Users();
users.add(function () {
users.updatePersonalInfo();
});