Hey I got a problem which my functions which are chained with .then doesn't work correctly, not in the order they should.
my code:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
var users = [];
var user = null;
function restCallA() {
return $.ajax({
url: "https://reqres.in/api/users?page=2",
type: "GET",
success: function(response) {
users = response.data;
console.log("users", users);
}
});
}
function restCallB() {
return $.ajax({
url: "https://reqres.in/api/users/2",
type: "GET",
success: function(response) {
user = response.data;
console.log("user", user);
}
});
}
function myFun(testArg) {
users.push(user);
console.log("why users is null?", testArg, users);
}
$(function() {
restCallA()
.then(restCallB)
.then(myFun("test"));
});
</script>
</body>
</html>
output:
users variable on the myFun function should have all the data from the first restCall and push the data from the second restCall to the same variable.
The variables does get the data, but the myFun function runs before them so the users variable inside it is null.
result pic:
how can I fix that?
.then accepts a function as a parameter, but in
restCallA()
.then(restCallB)
.then(myFun("test"));
you're invoking myFun immediately, and passing its return value to the second .then. It evaluates to:
restCallA()
.then(restCallB)
.then(undefined);
The myFun runs immediately, while the interpreter attempts to put together the Promise chain (before the response has come back).
Pass a function that invoked myFun instead:
restCallA()
.then(restCallB)
.then(() => myFun("test"));
You may also use .bind, which will create a function with the desired parameters, but won't call it:
restCallA()
.then(restCallB)
.then(myFun.bind(undefined, "test"));
var users = [];
var user = null;
function restCallA() {
return $.ajax({
url: "https://reqres.in/api/users?page=2",
type: "GET",
success: function(response) {
users = response.data;
console.log("users", users);
}
});
}
function restCallB() {
return $.ajax({
url: "https://reqres.in/api/users/2",
type: "GET",
success: function(response) {
user = response.data;
console.log("user", user);
}
});
}
function myFun(testArg) {
users.push(user);
console.log("why users is null?", testArg, users);
}
$(function() {
restCallA()
.then(restCallB)
.then(() => myFun("test"));
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
Only invoke a function inside a .then's parameter list if the function returns a function, eg:
const fnThatReturnsFn = arg => resolveValue => console.log(arg, resolveValue);
someProm()
.then(fnThatReturnsFn('somearg'));
$.ajax returns a promise-like object. so use that to your advantage, by returning the data from your ajax calls in a then within your functions.
Note that I've used one of #CertainPerformance's suggestions in their answer to fix the myFun issue.
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
function restCallA() {
return $.ajax({
url: "https://reqres.in/api/users?page=2",
type: "GET"
}).then(response => response.data);
}
function restCallB(users) {
return $.ajax({
url: "https://reqres.in/api/users/2",
type: "GET"
}).then(response => {
return {
// ES2015 method for adding a property named "users" with the value of the users variable
users,
user: response.data
};
});
}
function myFun(testArg, usersAndUser) {
usersAndUser.users.push(usersAndUser.user);
console.log(testArg);
}
$(function() {
restCallA()
.then(restCallB)
.then((usersAndUser) => myFun("test", usersAndUser));
});
</script>
</body>
</html>
Note that I'm using an object to collect both users and user into a single object; you could just as easily use an array.
Related
I am having an MVC application. In the application I am calling a controller method from the javascript function using the below code:
function settingViewBagData(e) {
$.ajax({
type: "GET",
url: "/Home1/SetViewBag",
success: function (result) {
alert("Success");
},
error: function (req, status, error) {
alert("Error");
}
});
Below is the controller method:
public void SetViewBag()
{
ViewBag.data = "Test";
}
Now I want to access this viewbag data on another javascript function called on button click, which will be fired after the first function. Below is the javascript function for accessing the viewbag data:
function accessVal()
{
var variable3 = '#ViewBag.data';
alert(variable3);
}
But I am getting blank in the alert box. Please help me to fix the issue.
Thanks
You are not returning View, so it will not show VIewBag. Do this:
public class Home1Controller : Controller
{
// GET: Home1
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult SetViewBag()
{
return Json(new { Msg = "Test" }, JsonRequestBehavior.AllowGet);
}
}
The above is controller. Below is the index view:
//View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
settingViewBagData();
});
function settingViewBagData() {
$.ajax({
type: "GET",
url: "/Home1/SetViewBag",
dataType: "json",
success: function (result) {
alert(result.Msg);
},
error: function (req, status, error) {
alert("Error");
}
})
};
</script>
</body>
</html>
Now it will work.
I have an ajax call as i have mentioned below. The data (ÇçİıĞğÖöÜü) appears to be correct until POST, but data is corrupted when a character set is specified while data is being sent. I have tried it in the following three different character sets, unfortunately nothing has changed.
Character Set
<meta charset="utf-8" />
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-9">
Ajax Call
var approve = {
stu_list: stu,
crn: listCrn,
cterm:termCode,
code:listRovr,
list_other_crn:listOtherCrn,
list_inst_resp:listInstResp
};
$.ajax({
type: "POST",
url: "approve.p_send",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
//dataType: "json",
async:false,
data: approve,
success: function() {},
error: function (xhr, stat, err) {console.log("Error in p_send " + err);}
});
P_SEND Procedure Spec
procedure p_send(cterm in varchar2 default null,stu_pidm in number default null,code in varchar2 default null,crn in varchar2 default null,list_other_crn in varchar2 default null,list_inst_resp varchar2 default null)
Debugging
Network
list_inst_resp=%C3%87%C3%A7%C4%B0%C4%B1%C4%9E%C4%9F%C3%96%C3%B6%C3%9C%C3%BC
Please check the data type of list_inst_resp.If the posted data(list_inst_resp) is a list of objects you can use this code.
public async Task<IActionResult> Details(string stu,string listCrn,string termCode, string listRovr,string listOtherCrn, JObject list_inst_resp)
{
List<inst_resp> listIR = list_inst_resp.ToObject<List<inst_resp>>();
//... something code
//await...
//...
return Json("good lucky");
}
I'm receiving a data from AJAX response and I'm trying to update a jQuery plugin with that value in the success callback:
$.ajax({
url: '/some/url',
type: 'GET',
dataType: 'json',
success: (data) => {
$(".my-rating").starRating('setRating', data.rating);
}
});
I'm using the star-rating-svg plugin to show ratigns (http://nashio.github.io/star-rating-svg/demo/). The problem is that I'm having an error:
Uncaught TypeError: $(...).starRating is not a function
However, this function works perfectly when is called outside AJAX callback. Do you know how to deal with this?
EDIT:
Larger piece of my code:
show.ejs
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/star-svg/src/jquery.star-rating-svg.js"></script>
<link rel="stylesheet" type="text/css" href="/star-svg/src/css/star-rating-svg.css">
</head>
<body>
<div class="my-rating mb-1"></div>
<script>
function getUserRating() {
$.ajax({
url: '/some/url/rating',
type: 'GET',
dataType: 'json',
success: () => {
$(".my-rating").starRating('setRating', data.rating);
}
});
}
function webpageReady() {
if($(".my-rating").is(':visible')) {
$(".my-rating").starRating({
starSize: 20,
disableAfterRate: false,
callback: function(currentRating, $el){
$.ajax({
url: '/some/url/setRating',
type: 'POST',
data: {'rating' : currentRating}
});
}
});
getUserRating();
}
}
</script>
<script type="text/javascript">webpageReady();</script>
</body>
</html>
rating.js
router.get("/some/url/rating", function (req, res) {
Rating.findOne({'author.id': req.user._id}).populate("ratings").exec(function(err, rating){
if(err){
console.log(err);
}
else{
res.send({userRating : rating});
}
});
});
I had the same question, and I figured it out like this - I use jQuery StarRatingSvg v1.2.0:
callback: function(rating, $el){
$.post(
URL,
{ rating: rating, _token : "csrf_token" }
).done(function (resp) {
$el.starRating('setRating', parseFloat(resp.rating), false);
});
}
The callback function has two parameters: rating - the value set by a user when they click the stars, and $el - the rating element.
I hope it helps someone.
Here is simple demo for this plugin
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/star-rating-svg#3.5.0/src/jquery.star-rating-svg.js"></script>
</head>
<body>
<div class="my-rating"></div>
<script>
$(document).ready(function(){
$(".my-rating").starRating({
starSize: 25,
callback: function(currentRating, $el){
// make a server call here
}
});
});
</script>
</body>
</html>
Problem solved: In a footer there was another link to a jquery.
I'm new to Programming and have this assignment of using JQUERY Ajax method in Javascript to get the data of a Gateway and attach some of it's value to the properties of an object. That I have already done but in the object is an "ip" property and it's value should be the ip in the url in the get request. I have over this for for hours and can't figure it out but i believe there's a simple way to go about it. Below is code and i hope someone out there can help out.
<!DOCTYPE html>
<html>
<head>
<title>Gateway Object</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<script src="jquery-2.1.4.js"></script>
<script>
gateway = {
ip: "",
hwv: "",
ver: "",
sid: ""
};
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://192.168.55.146/command?XC_FNC=GetSI",
timeout: 2000,
error: function (err) {
console.log("gateway error: check ip address and try
again");
},
success: function (data) {
if(data) {
if(data.substr(0,8) === "{XC_SUC}") {
var jString = (data.slice(8));
var obj;
try {
var obj = JSON.parse(jString);
} catch(e){}
gateway.hwv = obj.HWV;
gateway.ver = obj.VER;
gateway.sid = obj.SID;
console.log(gateway);
}
else{
console.log("Error:" + "" + data);
}
}
else{
console.log("error with the gateway");
}
}
});
});
</script>
</head>
<body></body>
</html>
I have a web page that works great in Chrome but not in IE9. The error that comes on the console from this error is
SCRIPT5022: Unable to parse bindings.
Message: [object Error];
Bindings value: foreach: statlist.
HTML is below:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="statsarea" data-bind="foreach: statlist">
<p> TypeCount: <strong data-bind="text: TypeCount"></strong>, Priority: <strong data-bind="text: SentDate"></strong>
<br/>
</p>
</div>
<script src="js/jquery-1.9.0.js" type="text/javascript"></script>
<script src="js/knockout-2.2.1.js" type="text/javascript"></script>
<script src="models/messagecount.js" type="text/javascript"></script>
</body>
</html>
Javascript:
function MessageCountDataModel() {
var self = this;
var allCounts = (function() {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "http://localhost:8080/API/getstats.json",
'datatype': "json",
'success': function(data) {
self.statlist = data;
}
});
})();
}
ko.applyBindings(new MessageCountDataModel());
One more piece of info is that that the json that comes out of the API looks something like this. I'm not sure if it's because the TypeCount is not a string?
[
{
"TypeCount": 102,
"SentDate": "2014-08-18T00:00:00.000Z"
}
]
It's not a good idea to use async: false. Maybe this is the problem because you don't initialize statlist as attribute in yout ViewModel. Better solution will be to make statlist to be an observable array, then make a async call and when it is ready to set the data.
Example:
function MessageCountDataModel() {
var self = this;
self.statlist = ko.observableArray();
self.loadData = function() {
$.ajax({
'url': "http://localhost:8080/API/getstats.json",
'datatype': "json",
'success': function(data) {
self.statlist(data);
}
});
};
self.loadData();
}
ko.applyBindings(new MessageCountDataModel());