React - WP_Mail works with jQuery but not axios - javascript

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

Related

How to call API Ninjas API with Javascript?

I am trying to use an API from https://api-ninjas.com/api/geocoding/. Their site provides the following starter code for how to call an API, but when I try it, the browser console just tells me that $ is not defined.
Is $.ajax a stand-in for something I need to create?
Here is the starter code they provide:
var city = 'london'
$.ajax({
method: 'GET',
url: 'https://api.api-ninjas.com/v1/geocoding?city=' + city,
headers: { 'X-Api-Key': 'YOUR_API_KEY'},
contentType: 'application/json',
success: function(result) {
console.log(result);
},
error: function ajaxError(jqXHR) {
console.error('Error: ', jqXHR.responseText);
}
});
I have tried writing document.ajax, but that returned the error that it was not a function. I have also tried deleting $.ajax and putting fetch in its place
I was able to solve with the following code:
let options = {
method: 'GET',
headers: { 'x-api-key': 'myKey' }
}
let url = 'https://api.api-ninjas.com/v1/geocoding?city=denver'
fetch(url,options)
.then(res => res.json()) // parse response as JSON
.then(data => {
console.log(data)
})
.catch(err => {
console.log(`error ${err}`)
});

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

Sending data to Firebase Cloud Function via Ajax

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

Implement clientside token-based authentication using plain Javascript/AJAX

Can anyone point me to an article that explains clientside token auth implementation using Javascript?
I found many articles on Angular but that is not what I'm looking for. That brings me to the question if it is possible to be done with Javascript.
Also how to handle scenarios when the auth server throws a 401. Is there a built in exception to detect that response? Or is a custom exception required to be implemented?
I have personally used JSON web tokens in one of my projects.
http://blog.slatepeak.com/creating-a-simple-node-express-api-authentication-system-with-passport-and-jwt is a tutorial on how to set up JSON web tokens on the server side.
Once you get the token as a response to the client side, you can store the token on window.localStorage.
var credentials = {
username : document.getElementById("username").value,
password : document.getElementById("password").value
};
var url = window.localStorage.getItem('appUrl');
$.ajax({
url: url + '/register',
type: 'POST',
data: { username: credentials.username, password: credentials.password },
success: function(Data) {
window.localStorage.setItem('token', Data.token);
},
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', window.localStorage.getItem('token'));},
error: function() {
alert('Error occured');
}
});
});
Then you can attach it in an AJAX call as a header while navigating to other pages.
$.ajax
({
type: "GET",
url: "index1.php",
data: '{}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization',window.localStorage.getItem('token'));
},
success: function (){
alert('Thanks for your comment!');
}
});
This worked for me..
var token = gettoken();
function getDatatypes() {
if (isEmpty(token)) {
token = gettoken();
}
var request = getDatatypesFromApi();
request.success(function (data) {
alert('success!');
});
request.error(function (httpObj, textStatus) {
if (httpObj.status == 401)
gettoken();
});
}
function getDatatypesFromApi() {
var request = $.ajax
({
type: "GET",
url: "http://yoururl.com/",
data: '',
headers:{
'Authorization': 'Basic ' + token
},
dataType: "json",
timeout: 5000,
});
return request;
}
function gettoken() {
var credentials = {
username: "userid",
password: "PASS",
domain: "",
extensionsAppId:"{extAppId}"
};
var url = "http://thelinktoresource/"
$.ajax({
url: url,
type: 'GET',
data: { userId: credentials.username, password: credentials.password, domain: credentials.domain, extensionsAppId: credentials.extensionsAppId },
dataType: "json",
contentType: 'application/json; charset=UTF-8',
success: function (Data) {
console.log(Data);
token = Data.replace(/"/ig, '');
return token;
},
error: function () {
alert('Error occured');
return "undefined";
}
});
}
function isEmpty(strIn) {
if (strIn === undefined) {
return true;
}
else if (strIn == null) {
return true;
}
else if (strIn == "") {
return true;
}
else {
return false;
}
}

I can't do a request that needs to set a header with axios

I'm trying to get some datas from an external API (from Mashape) that requires a specific header to set the API key.
Everything is ok using jQuery :
$.ajax({
url: 'https://omgvamp-hearthstone-v1.p.mashape.com/cardbacks',
type: 'GET',
data: {},
dataType: 'json',
success: function(data) { console.dir((data.source)); },
error: function(err) { alert(err); },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "MY_API_KEY");
}
});
However, when I'm trying to do the same request with axios for a react application, I have a 404 error:
axios.get({
url: 'https://omgvamp-hearthstone-v1.p.mashape.com/cardbacks',
headers: {
"X-Mashape-Authorization": "MY_API_KEY"
}
})
Is there something I'm missing ? Thanks.
I finally understood.
We need to set the header BEFORE the request using axios.defaults.headers.common['header_name'] = "API_KEY"; :
axios.defaults.baseURL = 'https://omgvamp-hearthstone-v1.p.mashape.com';
axios.defaults.headers.common['X-Mashape-Key'] = "API_KEY";
axios.get('/cardbacks')
.then((resp) => {
console.dir(resp);
});
Try also to do it like this without setting defaults:
axios.get('https://omgvamp-hearthstone-v1.p.mashape.com/cardbacks', {
headers: { "X-Mashape-Key": "MY_API_KEY" }
})
.then((resp) => {
console.dir(resp);
})
.catch(err => {
console.log(err);
});
}
It should work.
PS I also observed that you use different header keys in question(X-Mashape-Authorization) and answer(X-Mashape-Key). Maybe that is also somehow related to 404 error?
I got better way to solve this .
You just need add parameters format from axios like this below:
axios({
method: <method>,
url: <url>,
data: <params>,
headers: { common: <headers> },
})
.then(response => {
if (!cb) return { error: 'No callback' };
return cb(response);
})
.catch((err) => cb(err.response));

Categories

Resources