How to use 'This' inside an Ajax call in angular [duplicate] - ajax

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
I am trying to use 'this' once I get response from Ajax call.
but 'this' seems to be undefined. I found few articles using the 'bind', but I am not sure how to implement the bind.
I don't have any problem using 'this' inside the ajax call. I get response from backend as expected.
saveCart(data: any): void {
let body: any = {}
body.data = data
body = JSON.stringify(body)
// the 'this' works here as expected.
let config = this.config.getHeaders() as any
$.ajax({
url: environment.domain + '/cart',
type: "POST",
headers: config,
data: body,
contentType: "application/json",
dataType: "json",
async: false
}).done(function (response) {
// The 'this' below is undefined **********
this.profileService.logout().subscribe(result => {
console.log('User was logged out', result)
})
})
}
Update: Couple of folks had question about why I am not using httpClient.
This function is called when the user closes the browser. Using angular angular's httpclient is freezing the browser (heavy backend code) for few seconds before it closes. so opted for ajax call.
below is the code I am using everywhere else using angular httpClient
this.http.post(environment.domain + url, body, options)
.pipe(retryWhen(this.config.handleRetry))
.pipe(catchError(this.config.handleError))

Try this one.
saveCart(data: any): void {
/* Other code */
var that = this;
$.ajax({
url: environment.domain + '/cart',
type: "POST",
headers: config,
data: body,
contentType: "application/json",
dataType: "json",
async: false,
success:function(response){
//The 'this' below is undefined **********
that.profileService.logout().subscribe(result => { console.log('User was logged out', result) })
}
})

Try to use this way.
Option 1
Before Ajax call, set a new variable...
var that = this;
Now you can user that instead of this. It will work same as this.
Option 2
You can try with ES6 syntax. I haven't try with Ajax but I used this in my code regularly and it works fine for me.
$.ajax({
url: environment.domain + '/cart',
type: "POST",
headers: config,
data: body,
contentType: "application/json",
dataType: "json",
async: false,
success:(() =>{ <----------------Hear is the change
this...
}) =>{
}
})

Related

Empty arguments Ajax ASP.NET Core 3.0 MVC

I am using an ASP.NET Core 3.0 MVC application in which I make the following jQuery Ajax call:
return $.ajax({
type: type,
url: '/' + controller + '/' + action,
data: jsonData,
timeout: timeout,
contentType: "application/json; charset=utf-8",
success: function (returnedData) {
successFunc(returnedData);
},
error: function (errMsg) {
errorFunc(errMsg);
}
});
passing it the data object
{
input1: 'random',
input2: '1',
input3: '1',
},
But it always passes null arguments through:
I have also tried adding addnewtonsoftjson() in startup but it doesn't seem to change anything.
A similar question here, doesn't really have an answer:
.Net Core 3.0 AJAX POST Body Always Null
I think your problem is kinda relative to the HTTP method/type you are using and the contentType you are passing to the backend.
I've found a great summary of contentType here
If you don't wanna dive too deep into this you could change your contentType into application/x-www-form-urlencoded; charset=UTF-8 should resolve your problem
So keep the c# code as you have shown in your question.
In you js call:
var data = JSON.stringify({
'input1': ‘inputvalue’,
'input2':’inputvalue’,
‘input3’: ‘inputval’
});
$.ajax({
type: "POST",
url: same as you have in the question
data: data,
contentType: 'application/json',
success: function (returnedData) {
successFunc(returnedData);
},
error: function (errMsg) {
errorFunc(errMsg);
}
});
The error seems to com from defining the content type.
return $.ajax({
type: type,
url: '/' + controller + '/' + action,
data: jsonData,
success: function (returnedData) {
successFunc(returnedData);
},
error: function (errMsg) {
errorFunc(errMsg);
}
});
has no contentType defined and passes through to the action in the controller correctly.

Weird object returned from AJAX request

I have this method:
var chineseCurrency = getChinese();
function getChinese(){
return $.ajax({
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny"
});
}
That is what printed when console.log(chineseCurrency);:
I am not able to make chineseCurrency equal to "price", so it would be "6.80071377". How can I do that? Tried chineseCurrency.responseText, nope, chineseCurrency['responseText'], nope. Tried to JSON.parse(chineseCurrency), nope. Nothing works!
Sorry if repeated, couldn't find any answer at Stackoverflow.
How do I return the response from an asynchronous call?
Data that is received as response to asynchronous ajax call cannot be returned from the function that calls $.ajax. What you are returning is XMLHttpRequest object (see http://api.jquery.com/jquery.ajax/) that is far from the desired data.
var chineseCurrency = null;
function getChinese(){
return $.ajax({
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny",
success: function(data) {
alert("success1: chineseCurrency=" + chineseCurrency);
chineseCurrency = data.ticker.price;
alert("success2: chineseCurrency=" + chineseCurrency);
// do what you need with chineseCurrency
}
});
}
You are not taking the data from that is returned from the Ajax call. instead you are just returning the ajax object.
Change your code to :
$.ajax(
{
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny"
data :{},
error : function(data)
{
console.log('error occured when trying to find the from city');
},
success : function(data)
{
console.log(data); //This is what you should return from the function.
}
});

JQuery Ajax call often not working on Safari 6

My Ajax call is really simple as below:
function ajax(reqUrl, params , callback) {
console.log("Request URL "+reqUrl);
var cond;
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
error:function(){ alert("some error occurred") },
success: callback
});
console.log("Server response "+cond.readyState);
}
// Call it as
var url = "/getResult";
var params = {};
params.param1 = "test1";
params.param2 = "test2";
ajax(url, params, function(returnCallback) {
console.log(returnCallback);
alert("Success");
});
That works fine in most cases. But sometimes (about 1 times in 3) it doesn't return anything to callback.
I found many questions and answers for Not working ajax in Safari but fine in chrome and FireFox. My problem is different from them, because it's fine most of the time (I don't mean it was not fine usually because when I refresh my browser, that may cause my ajax call to work).
My main question is why does my ajax call sometimes fail? I don't get any errors on my JS console. When this situation, I refresh my browser to get my ajax call to. Any Ideas?
Update:
I found that sometimes my ajax call method didn't call out because console.log("Request URL "+reqUrl); did not execute. When I don't want to refresh my browser, I clicked many times on my page's link to produce result. will something late to execute?
Finally, I found error .. Safari doesn't reload my JavaScript files again even disable Cache. So I put all of my JS code into:
$(document).ready(function(){
// start load my js functions
init();
});
to reload my JS files when my page was ready. Cheer !
I also met this problem.
When I moved all code into $(function() {}), it worked.
After that, I found I had defined a variable named key, which caused the problem.
Just rename it, all things will be running.
This seems to be a Safari issue. In this post there is a suggestion to add a beforeSend to your ajax-request.
In your case:
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
beforeSend: function (event, files, index, xhr, handler, callBack) {
$.ajax({
async: false,
url: 'closeconnection.php' // add path
});
},
error:function(){ alert("some error occurred") },
success: callback
});
Please Test below Code. it is working fine.
$.ajax({
type: "POST",
url:'#Url.Action("getResult","Controller")',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.toString());
});
This is use for MVC application.
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
For Asp.net Application :
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
if u have still the issue than please post ur complete code here. i will test and reply soon

jQuery AJAX post callback doesn't seems to work

I did this lots of times:
var url = '/offers/1/voting';
var params = { 'direction': 'up' };
$.post(url, params, function() {
alert('callback');
}); // post
(I'm hardcoding the values for this example, but nothing)
So, through firebug I receive the desired JSON response (200 status), but the callback doesn't execute. It's pretty much the only javascript I'm using. Tried with jquery 1.6.4 and 1.7.1 and it's the same thing with both. I don't know what I'm missing.
Help me, Stack Overflow. You're my only hope.
If you use $.ajax instead of $.post ($.post is really an overwrite of $.ajax with fewer parameters), you can add a handler for error and see if it fires:
jQuery.ajax({
type: "POST",
async: true,
url: '/offers/1/voting',
data: { 'direction': 'up' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
try this
$.post(url, params, function(callback) { alert(callback); });

jQuery.ajax returns 400 Bad Request

This works fine:
jQuery('#my_get_related_keywords').click(function() {
if (jQuery('#my_keyword').val() == '') return false;
jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
function (data) {//do something}
This returns 400 Bad Request (Just a reformulation of the above jQuery using .ajax to support error handling).
jQuery('#my_get_related_keywords').click(function()
{
if (jQuery('#my_keyword').val() == '') return false;
jQuery('#my_loader').show();
jQuery.ajax(
{
url: "http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
success: function(data)
{//do something}
I think you just need to add 2 more options (contentType and dataType):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
Add this to your ajax call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.
$.ajax({
type: 'get',
must be met with
app.get('/', function(req, res) {
===============
and for post
$.ajax({
type: 'post',
must be met with
app.post('/', function(req, res) {
I was getting the 400 Bad Request error, even after setting:
contentType: "application/json",
dataType: "json"
The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.
This was my initial code:
var data = {
"TestId": testId,
"PlayerId": parseInt(playerId),
"Result": result
};
var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
url: url,
method: "POST",
contentType: "application/json",
data: JSON.stringify(data), // issue with a property type in the data object
dataType: "json",
error: function (e) {
console.log(e); // logging the error object to console
},
success: function () {
console.log('Success saving test result');
}
});
Now after making the request, I checked the console tab in the browser development tool.
It looked like this:
responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.
Changing the data object creation like below fixed the issue for me:
var data = {
"TestId": String(testId), //converting testId to a string
"PlayerId": parseInt(playerId),
"Result": result
};
I assume other possible errors could also be identified by logging and inspecting the error object.
Your AJAX call is not completed with the following two params.
contentType: "application/json; charset=utf-8",
dataType: "json"
contentType is the type of data you're sending
dataType is what you're expecting back from the server
In addition try to use JSON.stringify() method. It is used to turn a javascript object into json string.

Resources