I'm using this exact same function for a different xml and it works perfectly. This function was actually working perfectly yesterday now I wake up today and its giving me a 422 error.
useEffect(()=>{
$.ajax({
url: 'https://api.rss2json.com/v1/api.json',
method: 'GET',
dataType: 'json',
data: {
rss_url: 'https://basketball.realgm.com/rss/wiretap/0/0.xml',
}
}).done(function (response) {
if(response.status !== 'ok'){ throw response.message; }
let a = response.items
let b = a.filter((el, i) => {
return !el.title.toLowerCase().includes('realgm')
})
setNewNews(b)
});
},[])
Related
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);
});
I have used JQuery since a long time and i am familar with the AJAX-Calls in it. I often had the situation where i had to wait until multiple requests have been finished and continue after that with the results.
The JQuery syntax was the following:
$.when(
$.ajax({
type: "POST",
url: '/Services/Service.asmx/GetResults1',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
...
},
error: function (e) {
console.log('ERROR! ' + e.responseText);
}
}),
$.ajax({
type: "POST",
url: '/Services/Service.asmx/GetResults2',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
...
});
},
error: function (e) {
console.log('ERROR! ' + e.responseText);
}
})
).done(function (result1, result2) {
// Do s.th. with result1 and result2 what is already
// available here
updateUI();
...
});
How can you do this in VanillaJS?
Here is an example using the new vanilla JS fetch API
fetch('URL', {
method: "POST/PUT/GET/DELETE",
body: JSON.stringify({
name: Name,
otherData : otherData
}),`enter code here`
headers: {"content-type": "application/json"}
})
.then(res => res.json())
.then(response => {
//do what you want with the response here
})
For a GET request you can opt-out the body in fetch like
fetch('URL', {
method: "GET",
headers: {"content-type": "application/json"}
})
.then(res => res.json())
.then(response => {
//do what you want with the response here
})
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
document.getElementById("userID").innerHTML = json.userId;
document.getElementById("title").innerHTML = json.title;
document.getElementById("completed").innerHTML= json.completed;
})
<div>The User ID is : </div>
<div id="userID">
</div>
<div>The Title is : </div>
<div id="title">
</div>
<div>Completed : </div>
<div id="completed">
</div>
Compare this one with your AJAX request:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
receivedJSON = JSON.parse(xhttp.responseText);
//Your success: function here...
}else{
//Your error: function here...
}
};
xhttp.open("POST","/Services/Service.asmx/GetResults1",true);
xhttp.send(/**Your JSON Data**/);
I am trying to pass json string from angularjs to my websrvice and used below code.Can someone please let me where i went wrong with the below code?
Controller method:
[httpget]
public string BulkData(JObject jObjectData)
{
var x = jObjectData;
return (jObjectData != null ) ? “SUCCESS”: “FAIL”;
}
Javasctiprt method :
function Get(url, data) {
var getReq = {
method: "GET",
url: url,
dataType: 'json',
data: JSON.stringify(data),
headers: { "Content-Type": "application/json;charset=UTF-8" }
};
return $http(getReq).then(function (response) {
$log.debug('**response from EXECUTE:', response);
return response;
}, function (error) {
$log.error('**error from EXECUTE', error);
return error;
});
}
You need [HttpPost] method, and make post request
Controller method:
[HttpPost]
public string BulkData(JObject jObjectData)
{
var x = jObjectData;
return (jObjectData != null ) ? “SUCCESS”: “FAIL”;
}
Javasctiprt method :
function Get(url, data) {
var getReq = {
method: "POST",
url: url,
dataType: 'json',
data: JSON.stringify(data),
headers: { "Content-Type": "application/json;charset=UTF-8" }
};
return $http(getReq).then(function (response) {
$log.debug('**response from EXECUTE:', response);
return response;
}, function (error) {
$log.error('**error from EXECUTE', error);
return error;
});
}
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;
}
}
Apologies if worded awkwardly, but I have to make an rest API call using jQuery. I've already made the call using angularJS before, but for this case I can't use that. I tried translating it to jQuery but I'm not getting the same results. Is there anything I'm doing wrong or am I missing information? I'm fairly new to jQuery so I feel as if I'm missing something crucial or misunderstood something.
Working code with angularJS:
var req = {
method: 'POST',
url: 'https://fakeurl.com/rest/v1/portal/user/' + $scope.email.value,
headers:{
'Content-Type': 'application/json',
'Header_1': 'Yes',
'x-access-token': 'glsFromWebsite' //$scope.authInfo.token
}
};
restCall($http, req).then(function (res) {
// check for error even though 200 response
if (res.error) {
console.error("Error reported...");
} else {
` //enter success code here
}
});
var restCall = function(http, req) {
var _url = getBaseUrl() + req.url;
req.url = _url;
return new Promise(function(fulfill, reject) {
try {
http(req).then(function (res) {
// check for error even though 200 response
if (res.data.error) {
if (res.data.error === '601') {
console.error('Token is invalid or has expired');
} else {
console.error("Error from end point: " + res.data.error);
}
}
fulfill(res.data);
}, function(err) {
console.error('Error calling rest endpoint',err);
reject();
});
} catch (ex) {
console.error('Exception calling rest endpoint',ex);
reject(ex);
}
});
};
My failing jQuery code:
var processCreate = function (email) {
$.ajax({
url: 'https://fakeurl.com/rest/v1/portal/user/' + email.value,
type: 'POST',
headers: {
'Content-Type': 'application/json',
'Header_1': 'Yes',
'x-access-token': 'glsFromWebsite' //$scope.authInfo.token
},
success: function (res, a, b) {
if (res === 'NOT FOUND') {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function () {
console.error("Error...");
}
});
}
Try making an ajax call like this
var processCreate = function (email) {
var authHeaders = {};
authHeaders.Authorization = 'Bearer ' + 'glsFromWebsite';
$.ajax({
url: 'https://fakeurl.com/rest/v1/portal/user/' + email.value,
type: "POST",
cache: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
headers: authHeaders,
success: function (data) {
//console.log(data);
if (data === 'NOT FOUND') {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function (xhr) {
console.log(xhr);
}
});
}