Assign the ajax response to a global variable - javascript

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();
});

Related

How to escape brackets in an ajax request?

I would like to send a GET request with only one parameter from an input form via AJAX, using jQuery.ajax().
To simplify things, instead of
data: $("#the_form").serialize()
I tried to explicitly pass the value of the input:
function lookupSearch(val){
$.ajax({
type: "get",
url: "/search",
data: {
tx_search_pi1['sword']: val
},
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
Now this breaks because of the brackets and quotes in
tx_search_pi1[sword]: val
(which is required by the recipient of the get request)
How do I escape the brackets (and maybe also single quotes inside= correctly?
I've tried-and-errored many combinations, eg. with
tx_search_pi1%5Bsword%5D
encodeURIComponent("tx_kesearch_pi1[sword]")
etc...
You can try this,
data: $("#the_form").serialize()+'&sword='val,
Full Code,
function lookupSearch(val){
$.ajax({
type: "get",
url: "/search",
data: $("#the_form").serialize()+'&sword='val,
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
And if you want to pass sword value then use,
data: {'sword':val}, // get using sword key
As per #Urs Comment the code should be,
// let it is initialised before,
// and it is an object like {}, tx_search_pi1 = {key:"1",...};
function lookupSearch(val){
tx_search_pi1['sword'] = val;
$.ajax({
type: "get",
url: "/search",
data: tx_search_pi1,
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
try putting tx_search_pi1['sword'] this in a variable and pass it.
Like
var temp = tx_search_pi1['sword'];
And pass temp

Sending variable to PHP with AJAX, receiving JSON back

Using the following jQuery, how can I read through the values of the JSON that's returned? With it how it is, the jQuery doesn't even run as there is an error in: alert("A" + obj.sender[0]);
var session_id = $(this).find(".session_id").val();
$.ajax({
type: 'POST',
url: '../php/read.php',
dataType: "json",
data: {sesh_id: session_id},
success: function (response) {
var obj = jQuery.parseJSON(response);
alert("A" + obj.sender[0]);
},
error: function (response) {
alert("Err: " + response.status);
}
});
The value of response is:
[{
"sender":"email#example.com",
"details":"details1",
"date":"2017-01-04 16:11:04"
},
{
"sender":"someone#example.com",
"details":"details2",
"date":"2017-01-04 16:11:05"
},
{
"sender":"blah#example.com",
"details":"details3",
"date":"2017-01-04 16:11:06"
}]
The issue you have is that your index accessor is in the wrong place as obj is an array, not the sender property, so it should be obj[0].sender.
You also don't need to call JSON.parse() on the response, as jQuery does that for you automatically as you specified dataType: 'json'. Try this:
$.ajax({
type: 'POST',
url: '../php/read.php',
dataType: "json",
data: { sesh_id: session_id },
success: function (response) {
console.log("A" + obj[0].sender);
},
error: function (response) {
console.log("Err: " + response.status);
}
});
Finally, note that console.log() is much more preferable when debugging over alert() as it doesn't coerce data types.

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

Javascript - Dependency injection and promises

I'm trying to pass an object around in JS (with some jQuery thrown in). :)
I want to call the FlappyBarHelper.getUserPropertyCount() method once the promise.success function has run. I've tried passing this.FlappyBarHelper to :
return $.ajax({
type: "GET",
url: 'get-the-score',
flappy: this.FlappyBarHelper,
});
But that still makes flappy undefined in promise.success
My full code is:
function Rating(FlappyBarHelper) {
this.FlappyBarHelper = FlappyBarHelper;
}
Rating.prototype.attachRaty = function(property_id)
{
var promise = this.getPropertyScoreAjax(property_id);
promise.success(function (data) {
$('#'+property_id).raty({
click: function (score, evt) {
$.ajax({
type: "GET",
url: '/set-the-score',
})
.done(function (msg) {
$('#extruderTop').openMbExtruder(true);
//**** FlappyBarHelper is undefined at this point ****///
FlappyBarHelper.getUserPropertyCount('.flap');
});
}
});
});
};
Rating.prototype.getPropertyScoreAjax = function(property_id)
{
return $.ajax({
type: "GET",
url: 'get-the-score',
});
}
Read from the documentation of ($.ajax](https://api.jquery.com/jQuery.ajax/)
The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
Therefore you should pass your variable along the multiple call you are doing:
Rating.prototype.attachRaty = function(property_id){
var promise = this.getPropertyScoreAjax(property_id);
// it's best to use done
promise.done(function (data) {
$('#'+property_id).raty({
// use proxy to keep context when the click will be received
click: $.proxy(function(score, evt) {
$.ajax({
type: "GET",
url: '/set-the-score',
// propagate your variable
FlappyBarHelper: this.FlappyBarHelper
}).done(function (msg) {
$('#extruderTop').openMbExtruder(true);
// here it should be defined
this.FlappyBarHelper.getUserPropertyCount('.flap');
});
}, this);
});
});
};
Rating.prototype.getPropertyScoreAjax = function(property_id) {
return $.ajax({
type: "GET",
url: 'get-the-score',
// propagate your variable
FlappyBarHelper: this.FlappyBarHelper
});
}
You can also consider making a closure variable:
Rating.prototype.attachRaty = function(property_id){
// here is the closure variable
var helper = this.FlappyBarHelper;
var promise = this.getPropertyScoreAjax(property_id);
// it's best to use done
promise.done(function (data) {
$('#'+property_id).raty({
click: function(score, evt) {
$.ajax({
type: "GET",
url: '/set-the-score'
}).done(function (msg) {
$('#extruderTop').openMbExtruder(true);
// you can still use the defined variable: power (and danger) of closures
helper.getUserPropertyCount('.flap');
});
}, this);
});
});
};
Rating.prototype.getPropertyScoreAjax = function(property_id) {
return $.ajax({
type: "GET",
url: 'get-the-score'
});
}

Get value from javascript into velocity

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.

Categories

Resources