Sending data to Firebase Cloud Function via Ajax - javascript

I am trying to send data through post OR get to firebase cloud function but couldn't get it work.
Here is my ajax:
$.ajax({
url: 'https://us-ceXXX1-reXXXts-fXXa-pr.cloudfunctions.net/helloWorld',
dataType: "json",
method: 'GET',
crossDomain: true,
body: {
mobileNo: "WzkyMzXXXXXXXXXXXc5ODBd"
},
success: function(data){
console.log('succes: '+data);
}
});
And Here Is Cloud Function:
exports.helloWorld = functions.https.onRequest((request, response) => {
var responsez = response;
console.log("DATA IS:"+request.data); //prints undefined
console.log("BODY IS:"+JSON.stringify(request.body)); //prints BODY ID: {}
var mobNo = request.body.mobileNo;
var options = {
body: {mobileNo: mobNo, applicationVersion: "1.0"},
url: 'http://nxxxpi.fixxxa.wxb.pk/GetxxxxxxoUxr',
headers: {
'appKey':'jDxxxxxxxOr',
'appId':'2xxxxx9'
},
json: true
}
cors(request, response, () => {requestz.post(options, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
responsez.send(JSON.stringify(body));
})});
});
And It console logs.
DATA IS: undefined
BODY IS: {}
EDIT: HERE IS THE FIREBASE CONSOLE:
After adding:
console.log("BODY MOBILE:"+JSON.stringify(request.body.mobileNo));
console.log("ONLY MOBILE:"+JSON.stringify(request.mobileNo));

There are few issues in your code
change the method to POST instead of GET in your ajax call as you are passing the data in request body
use the data property instead of body in the ajax call . it should work now. The data will be available in request.body inside the firebase function
$.ajax({
url: 'https://us-ceXXX1-reXXXts-fXXa-pr.cloudfunctions.net/helloWorld',
dataType: "json",
method: 'POST',
crossDomain: true,
data: {
mobileNo: "WzkyMzXXXXXXXXXXXc5ODBd"
},
success: function(data){
console.log('succes: '+data);
}
});

Related

ajax type : patch is not working 400 (Bad Request)

i'm trying to update data in my local database server using ajax query in client server with api but it's not working i always get this error
jquery.min.js:4 PATCH http://127.0.0.1:3000/todo/62ff7276c2776726906f49d9 400 (Bad Request)
and this my code
const _update = (docId,itemId,content) => {
$.ajax({
type: 'PATCH',
url: docId + "/" + itemId,
data: {content:content},
contentType: 'application/json',
success: function (response, textStatus, xhr) {
console.log(response)
},
error: function (xhr) {
console.log(xhr);
}
});
}
i tested my api by postman and it worked perfectly , this id my router
router.patch('/todo/:id', async (req, res) => {
try {
const id = req.params.id
const todo = await Todo.findByIdAndUpdate(id, req.body, { new: true })
if(!todo)res.status(404)
res.send(todo)
} catch (e) {
res.status(400).send(e)
}
})

Javascript AJAX + JQuery posts empty data

I am new to web programming and am struggling with a basic task. I am trying to do a simple POST from my frontend to my backend and with it send data in the form of a JSON object. I specifically do not want to embed my javascript code in my HTML file. Please note that all the code shown is all the code used for this POST purpose, so if it looks like I am missing something I most likely am. My frontend JS code is as follows:
/**/
function Test_Button_Pressed() {
$.ajax({
type: "POST",
url: "/test",
dataType: "json",
data: {Name: "Rikus", Value: 123},
contentType: "application/json",
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (err) {
console.log("Error: ", err); //just use the err here
}
});
}
/**/
function Activation_Button_Pressed(Button_ID) {}
/**/
function Button_Pressed(Button_ID) {}
The following is logged in the Chrome console when the backend response was made:
Error: [object Object]
The backend code is as follows:
const Api = require("./Api");
var Communication = {};
/**/
Communication.SetUp = function (PanelApp, DataApp) {
PanelApp.post('/test', (req, res) => {
console.log(req);
console.log(req.params);
console.log(req.body);
res.send("Done");
});
};
module.exports = Communication;
Bothe the
console.log(req.body)
and
console.log(req.params)
returns: {}
so from what I can see my routing is correct, it's only my data sending that does not work. Please help and thank you in advance.
After some help the working code is as follows:
Frontend:
/**/
function Test_Button_Pressed() {
$.ajax({
type: "POST",
url: "/test",
dataType: "json",
data: {Name: "Rikus", Value: 123},
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (err) {
console.log("Error: ", err); //just use the err here
}
});
}
/**/
function Activation_Button_Pressed(Button_ID) {}
/**/
function Button_Pressed(Button_ID) {}
Backend
const Api = require("./Api");
var Communication = {};
/**/
Communication.SetUp = function (PanelApp, DataApp) {
PanelApp.post('/test', (req, res) => {
console.log(req.body.Name);
console.log(req.body.Value);
res.json("Done");
});
};
module.exports = Communication;

React - WP_Mail works with jQuery but not axios

I have a contact form in my React app and I am attempting to have the form send an email using WP_Mail. I am trying to do that using Axios, but I can't seem to get it to work. I get a 400 error on the admin-ajax call.
axios.post(url, {
action: 'send_form',
data: {
email: 'test#test.com',
message: 'testing'
}
})
.then(function (response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
I am able to get it to work using jQuery, but I'd rather not have to use that if possible:
$.ajax({
url: url,
dataType: 'json',
data: {action: 'send_form', email: 'test#test.com'},
cache: false,
success: function(data) {
console.log(data);
}.bind(this),
error: function(xhr, status, err) {
alert(err.toString());
}.bind(this)
});
I think the issue has to do with the format of the payload header. When I use Axios, the data comes through as JSON payload header, but when I use jQuery it comes through as query string parameters.
Can you try:
let form_data = new FormData;
form_data.append('action', 'send_form');
form_data.append('email', 'test#test.com');
form_data.append('message', 'testing');
axios.post(url, {
form_data
})
.then(function (response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});

Make another ajax call to get headers before each actual ajax call - jquery

I have to make an async call which uses cookie to get bearer token which has to be passed to make actual ajax call for the resource.
And I have written the following code which works awesome and get's me the result.
Can I use ajaxPrefilter or beforeSend options to get the tokens, I tried to find documentation for ajaxPrefilter which says it accepts a function, but does that waits for that function to be finished before making actual call?
Token retrieval function
function getTokenUsingCookieAsync() {
return new Promise(function (resolve, reject) {
$.ajax('/retrieve-token').done(function (result) {
resolve(result.token);
}).fail(function (message) {
reject(message);
});
});
}
Actual execute function:
function execute(url, method, data) {
var deferred = $.Deferred();
getTokenUsingCookieAsync().then(function (response) {
var reqSettings = {
async: true,
url: url,
cache: false,
type: method,
headers: {
Authorization: 'Bearer '+ response,
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: data ? JSON.stringify(data) : null
};
$.ajax(reqSettings).done(function (result) {
deferred.resolve(result);
}).fail(function (message) {
deferred.reject(message);
});
}).catch(function (message) {
deferred.reject(message);
});
return deferred.promise();
}
So the following pseudo code is possible or not?
$.ajaxPrefilter((options) => {
$.ajax('/retrieve-token').done((result) => {
options.headers = {
Authorization: `Bearer ${result}`
};
});
});
$.ajax('actual-url')
.done(whatever);

How can I prevent getting a dialog popup window to login with basic authentication?

Currently we are trying to access the reed.co.uk api and get the json results of jobs from an account. I have managed to access the API in chrome and get the results but in Safari (Version 10.0.1 (12602.2.14.0.7)) and Firefox(v 50.1.0) I get the dialog pop up that asks me to log in.
I have tried multiple versions of Ajax to get this working but nothing seems to fix the issue at all. Here is what I have got:
var clientId = "c*****-***-****-****-*********0";
var clientSecret = "";
var authorizationBasic = $.base64.btoa(clientId + ':' + clientSecret);
$.ajax({
type: 'GET',
url: 'http://www.reed.co.uk/api/1.0/search?employerId=488552',
dataType: "jsonp",
xhrFields: {
withCredentials: true
},
crossDomain: true,
headers: {
'Authorization': 'Basic ' + authorizationBasic
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
},
statusCode: {
401: function () {
result = false;
},
200: function (response) {
result = response;
}
},
async: false,
success: function (result) {
var token = result;
console.log(token);
},
//complete: function (jqXHR, textStatus) {
//},
error: function (req, status, error) {
alert(error);
}
});
Request headers Chrome:
Request headers firefox
This is the information reed.co.uk returns to you when accessing the results from their API:
You will need to include your api key for all requests in a basic
authentication http header as the username, leaving the password
empty.
Can anyone see why this would happen?

Categories

Resources