Bad request:Error function and timeout in ajax never fired - javascript

Here is my ajax call
var settings = {
"async": true,
"crossDomain": true,
"url": "http://sample.com/customer/api/v1/meetings/meeting",
"method": "POST",
"headers": {
"x-api-key": token
},
"dataType":'json',
"data": {
"title": meetingData.title,
"end_date": meetingData.endtdate,
"from_date": meetingData.startdate,
"description": meetingData.description,
"reminder_type": meetingData.remainder,
"priority": meetingData.priority
}
}
$.ajax(settings).done(function (response) {
console.log(response);
},function(err){
alert('error');
});
Problem is error callback function is never fired if any error is present.
Also i want to add a timeout this ajax call ,how can i do that??
I've added timeout:20000 parameter in my settings variable but the error call back is not fired
UPDATE
I will get a bad request error from the console ,how to solve that error??

I doubt the .done() has a error callback, instead you should use .then(successCB, errorCB) which has both callbacks:
$.ajax(settings).then(function (response) {
console.log(response);
},function(err){
alert('error');
});
Update
As per updates: I will get a bad request error from the console ,how to solve that error??
Then in this case the doubtful entities could be your data object you are sending, one of them or more might have some data which is causing this error. So you can inspect what data is getting through here:
"data": {
"title": meetingData.title,
"end_date": meetingData.endtdate,
"from_date": meetingData.startdate,
"description": meetingData.description,
"reminder_type": meetingData.remainder,
"priority": meetingData.priority
}

Write success and error within settings variable itself:
var settings = {
"async": true,
"crossDomain": true,
"url": "http://sample.com/customer/api/v1/meetings/meeting",
"method": "POST",
"headers": {
"x-api-key": token
},
"dataType":'json',
"data": {
"title": meetingData.title,
"end_date": meetingData.endtdate,
"from_date": meetingData.startdate,
"description": meetingData.description,
"reminder_type": meetingData.remainder,
"priority": meetingData.priority
},
"success":function(resp){
//your work here
},
"error":function(resp){
//your work here
}
}
$.ajax(settings);
Or remove it from settings and bind it globally to document as
$(document).ajaxSuccess(function( event, xhr) {
//error code here
}).ajaxError(function(event,xhr){
//error code here
});

Related

Axios response returning empty string

axios.post(
'http://localhost:3001/users',
{
username:user.username
}
).then((res)=> console.log(res.data))
Response From FrontEnd : data: ""
Response i get from postman :
[
{
"Username": "john4",
"Password": "",
"Email": "",
"ProfileImg": "data:image/png;base64,iV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ULnOfveF/O4N2Xb9BZom3gJes3F9X5Zze8/6Yt09b4CrqsEjUv8oFBaR2rl+6CZr2xVrp24o/WitBKuGrrpl1+bFkmK2qXTON4VpbdfLa7o7y/WdLxG7lm2Lqh2clOwTegbvc/vj2U78CwhA87Bn8G5Nk3eOb0Nsr9flz3sG78UUtue4kpv1xvjg3TMay62BMlTlP+vrOMnJsRmt/ze0jsfkPPYdAH57hK+34PeOyc8XIXu5xT2HsUkdZz+adwg8HGFfQ3K5jtDvbUiO4Di9/ywHGrL88pDizZ++oTp+an+SMX/ndymUCwmHMdO7yuOx83pUx/eEMU0AvxWndwgidAqOZ8ypCwdEfvvEo6D9HwpA8wzvmOJEqAg9ySu8g4x0Hb9hSB/BANEKJ+LbPBU0lzbAJs4xt1AoshKkUGQmiH8/jJ0gdhTTLmSegHlPE0oOdXALnqDjKYh3px//fSgSWG8UqfrrIICzYYSJXRr9BSPbpNzw7gBjKjKOYI7ReIGqQRIap5+5MdjyvuDkExvGeXSlONWZAP3/AZBwJohU7QJRGU+cTVH18ELmRPNBmibW6MT/k1b0XhdkRBvyT6SB6EYv/GvhSmRNpGngRULsAlxMCGNXp7w3FfdEbTEEDdLI9TdIKRUzUesa3I461ER8cpNT7gMRhpKmYVS9ELOgCUQsa4SsulciKiLbY+AnHD8cpuhISsnxpamI84sbDq9qYJgf8wiiOBrC7Ml7M7ZECCqKoiiKoiiKoiiKoijv5AvJxlZRyNWWLwAAAABJRU5ErkJggg==",
"Followers": [],
"Following": [],
"__v": 0
}
]
im trying to post data and get a response from my server , the server is returning the right data when i use postman but when i use axios i get an empty string any help?
when i console.log(res)
{
"data": "",
"status": 205,
"statusText": "Reset Content",
"headers": {
"content-length": "2042",
"content-type": "application/json; charset=utf-8"
},
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
"method": "post",
"url": "http://localhost:3001/users",
"data": "{\"username\":\"john4\"}"
},
"request": {}
}
You should handle your HTTP requests asynchronously with axios, utilizing async await. It just makes it so much cleaner.
Example:
const sendGetRequest = async () => {
try {
const response = await axios.post('http://localhost:3001/users', { username: user.username });
console.log(response.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
Calling the function sendGetRequest() in this case will send the post request, get the response and console log the response. And since it is utilizing try catch, if something goes wrong, it will console log the error.
Also make sure that your axios is properly setup. The correct headers etc. to match whatever you have with postman.
The issue was on my backend i sent res.status(205).json(user) instead of res.status(208).json(user) which somehow bugged it and caused it to send no data.

Can I trigger a Power Automate workflow from custom JavaSript?

How can I start/trigger any flow from my custom JavaScript code?
I am not asking about the button flow, and not any Out of the Box feature, I just want to trigger my flow from my JavaScript code
Create the flow triggers by 'Request – when a HTTP request is received', you could find the script in TechNet wiki page.
function StartMicrosoftFlowTriggerOperations() {
try {
var dataTemplate = "{\r\n \"emailaddress\":\"{0}\",\r\n \"emailSubject\": \"{1}\",\r\n \"emailBody\": \"{2}\"\r\n}";
var httpPostUrl = "<Supply with the HTTP POST Url>";
//Call FormatRow function and replace with the values supplied in input controls.
dataTemplate = dataTemplate.FormatRow($("#txtEmailAddress").val(), $("#txtEmailSubject").val(), $("#txtEmailBody").val());
var settings = {
"async": true,
"crossDomain": true,
"url": httpPostUrl,
"method": "POST",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache"
},
"processData": false,
"data": dataTemplate
}
$.ajax(settings).done(function (response) {
console.log("Successfully triggered the Microsoft Flow. ");
});
}
catch (e) {
console.log("Error occurred in StartMicrosoftFlowTriggerOperations " + e.message);
}
}

Sendgrid integration with SAPUI5 app returns '400 Bad Request' on POST but works on Postman

I'm developing a cordova hybrid app that utilizes UI5 library. I need to be able to send as Email from the app so I decided to use Sendgrid API and, since I had issues with the NodeJS module, I'm creating an AJAX request. I've previously tested the request with Postman, being able to successfully send emails. But, as I tried to do the same request from the app, I've stumbled upon a status '400 Bad Request' without further information. Here goes the code snippet:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.sendgrid.com/v3/mail/send",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer [REDACTED]",
"cache-control": "no-cache"
},
"processData": false,
"data": {
"personalizations": [
{
"to": [
{
"email": "myemail#gmail.com"
}
],
"subject": "Contato do app"
}
],
"from": {
"email": "anotheremail#gmail.com"
},
"content": [
{
"type": "text/plain",
"value": formatEmail //variable with the email text
}
]
}
}
$.ajax(settings).then(
function success(response, status) {
dialog.close();
if (status == 202){
MessageBox.confirm('Mensagem enviada com sucesso', {
actions: [sap.m.MessageBox.Action.OK],
onClose: function(sAction){
that.onNavBack()
}
});
} else {
MessageBox.error('Erro!');
}
},
function fail(data, status){
dialog.close();
MessageBox.error('Request failed. Returned status of ' + status + ' DEBUGDATA: ' + JSON.stringify(data));
}
);
I really can't figure out the reason as to why this happens because the snippet generated by Postman is very similar to my code. Any help would be highly appreciated!
Thanks in advance
usually HTTP 400 means bad request and it means that you're passing the wrong parameters to the HTTP POST request.

JQuery Ajax function not being executed in chrome extension

I am creating a chrome extension which uses simple HTTP POST requests. It's my first javascript code ever. I used POSTMAN to generate this code which fulfills the requirement (POSTMAN worked with the POST request).
var form = new FormData();
form.append("email", "XXX");
form.append("password", "XXX");
var settings = {
"async": true,
"crossDomain": true,
"url": "http://xxx.xxx.in/xxx/",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "fa86846e-4030-d90f-701a-82e36e6117b0"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
};
chrome.extension.getBackgroundPage().console.log("outside")
try {
chrome.extension.getBackgroundPage().console.log("inside try block")
$.ajax(settings).done(function (response) {
chrome.extension.getBackgroundPage().console.log("inside")
chrome.extension.getBackgroundPage().console.log(response);
});
} catch (e) {
chrome.extension.getBackgroundPage().console.log("Exception caught")
chrome.extension.getBackgroundPage().console.log(e)
} finally {
}
I tried it with a chrome extension but my console does not log after the inside try block. I can't understand what happened in this line
$.ajax(settings).done(function (response) {
The error is not caught anywhere else. I have given appropriate permissions in my manifest.json file.
I have some very specific questions to ask:
What is the best workaround for requests? XmlHttpRequests or JQuery
What are some best ways of debugging javascript applications? That would help a lot, thanks.

JSONP ajax callback failing

I have following script running on my local test drive. It imports a JSON file and builds a webpage, but for some reason, there is an error in handling the data. No data is shown...
But whenever I use (the same) data hard-coded, I get the result I want. So this made me think it has something to do with the way I handle the JSON import...
This is my AJAX callback:
getGames: function(fn) {
$.ajax({
type: "GET",
url: App.Config('webserviceurl')+'games-payed.js',
dataType: "jsonp",
success: function (data) {
console.log('streets', data);
if(fn){
fn(data);
}
},
error: function (msg) {
if(fn){
fn({status:400});
}
}
});
}
And this code isn't working, nor am I getting any errors in my console...
When I load the data hard coded, it works perfectly:
getGames: function(fn) {
var games = App.Config('dummyGames');
if(fn){
fn(games);
}
}
Is there something wrong with my AJAX callback?
EDIT:
The JSON file looks like this:
jsonp1({
"status": "200",
"data": [
{
"id": "1",
"title": "Title 1",
"publishDate": "2013-03-27T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game1.png",
"html5": "http://mysite.com/index.html"
},
{
"id": "2",
"title": "Title 2",
"publishDate": "2013-03-20T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game2.png",
"html5": "http://mysite.com/index.html"
},
{
"id": "3",
"title": "Title 3",
"publishDate": "2013-03-18T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game3.png",
"html5": "http://mysite.com/index.html"
}
]
});
In your example, I see that you wrap your json data inside jsonp1. I suppose that is a fixed name. If that's the case, try this:
getGames: function(fn) {
$.ajax({
type: "GET",
url: App.Config('webserviceurl')+'games-payed.js',
jsonp: false,
jsonpCallback:"jsonp1",
dataType: "jsonp",
success: function (data) {
console.log('streets', data);
if(fn){
fn(data);
}
},
error: function (msg) {
if(fn){
fn({status:400});
}
}
});
}
Notice the jsonpCallback:"jsonp1" and jsonp: false. The reason for this is: by default, jquery will generate the callback function name automatically and randomly and append ?callback=generatedFunctionName to the end of your url. Thanks to the callback parameter, the code on server side could use the same function name to call the callback on browser.
In your case, you're using fixed function name (jsonp1), so you have to:
Specify your function name explicitly using jsonpCallback="jsonp1"
Set jsonp = false to prevent jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation.

Categories

Resources