jQuery Post Callback from REST API - javascript

I am working on an app that will submit data to a REST API and have some questions.
How does jQuery know if my post request was successful or not? Is it only looking at the HTTP status?
Is there a convention on what to return from a POST request to a REST API?
JavaScript
$.post( '/API/removeUser', { Eid: id }, function(data) { row.remove(); } );
PHP SLIM Framework
$app->POST('/API/removeUser', function () use ($app) {
// Get the ID from the jQuery post
$Eid = trim(stripslashes(htmlspecialchars($_POST['Eid'])));
echo json_encode(removeFunction($Eid));
});

Your backend should always return the appropriate HTTP status code along with the actual data. 404 for resources that were not found, 403 for unauthorized requests, 200 for successful requests etc. Most AJAX libraries (including jQuery) will rely on those for determining the result of the operation.
If you need more fine-grained error reporting, you could always include a field like "errorCode" in your response that contains an application-level error code that you define yourself and react to accordingly in your frontend code.

Related

Process multiple unique Express JS requests

I've got a small Express JS api that I'm building to handle and process multiple incoming requests from the browser and am having some trouble figuring out the best approach to handle them.
The use case is that there's a form, with potentially up-to 30 or so people submitting form data to the Express JS api at any given time, the API then POSTS this data of to some place using axios, and each one needs to return a response back to the browser of the person that submitted the data, my endpoint so far is:
app.post('/api/process', (req, res) => {
if (!req.body) {
res.status(400).send({ code: 400, success: false, message: "No data was submitted" })
return
}
const application = req.body.Application
axios.post('https://example.com/api/endpoint', application)
.then(response => {
res.status(200).send({ code: 200, success: true, message: response })
})
.catch(error => {
res.status(200).send({ code: 200, success: false, message: error })
});
})
If John and James submit form data from different browsers to my Express JS api, which is forwarded to another api, I need the respective responses to go back to the respective browsers...
Let's make clear for you, A response of a request will only send to the requester, But if you need to send a process request and send a response like, hey i received your request and you can use another get route to get the result sometimes later, then you need to determine which job you mean. So You can generate a UUID when server receives a process request and send it back to the sender as response, Hey i received your process request, you can check the result of process sometimes later and this UUID is your reference code. Then you need to pass the UUID code as GETparam or query param and server send you the correct result.
This is the usual way when you are usinf WebSockettoo. send a process req to server and server sends back a reference UUID code, sometime later server sends the process result to websocket of requester and says Hey this is the result of that process with that UUID reference code.
I hope i said clear enough.

CakePHP 3 Json response instead of redirect ( if ext = json )

Is there any easy way to configure CakePHP auth component to send out a json response instead of normal redirect to login url.
Im using many ajax requests, and when the session expires, the ajax request will get a response of my home page's html instead of json encoded status.
I would like CakePHP to send out the following json response, if user is not logged in, and the query was made using json extension.
{status: false, message: "Please log in"}
Non-ajax page loads would still need to redirect as usual.
You should look upon where is the system checking whether you are logged in and see the case where it is not logged in. Wrap the following if around it:
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
//put here the html for the log in screen
} else {
$response = '{status: false, message: "Please log in"}';
echo json_encode($response);
}
Since it is hard to determine if you are making an ajax request, Cake 3 uses X-Requested-With = XMLHttpRequest. It seems this is a default for jquery (but who uses that anymore? seriously.).
You will need to set that header manually to allow cakephp to detect that your request is indeed ajax.
Your ajax requests may work on other pages because you are probably setting the _serialize var and setting the Accept Header or using the .json extensions to force json. However, the auth function does not check the Accept Header it only checks the X-Requested-With header.
So verify in your xhr request that X-Requested-With is XMLHttpRequest and you should receive a 403.
If you want to further customize the element or data that is returned, checkout the AuthComponent ajaxLogin param.
Handle Ajax Unauthorized
Basically, you will need to set the value to an element you want rendered.
Cake will look in your Element Template path and load that element.
// In your AppController
$this->loadComponent('Auth', [
'ajaxLogin' => 'yourAjaxElement', // This is what is important
// Optional stuff....
'authenticate' => [
'Form' => [
'finder' => 'AuthUser'
]
],
'authorize' => ['Controller'],
// More settings...
Then create this element
Template/Element/yourAjaxElement.ctp
Happy coding.

Retrieve data from restful api with angularjs service $resource

I try to use the $resource service with surveygizmo api.
My code :
html :
<div ng-app="Survey">
<body>
<div ng-controller="SurveyCtrl">
{{survey.data.title}}
</div>
</body>
</div>
my script :
angular.module('Survey', ['ngResource']);
function SurveyCtrl($scope, $resource) {
$scope.surveygizmo = $resource('https://restapi.surveygizmo.com/v3/survey/:id',
{id: '#id'},
{get:{method:'JSONP', params: {'user:pass':'xxx#xxxx:xxxx', q:'angularjs', callback:'JSON_CALLBACK'}, isArray:true}});
$scope.survey = $scope.surveygizmo.get({id:xxxx}, function(survey) {
alert('this is ok');
}, function(err){
alert('request failed');
});
}
When i try it, the alert 'request failed' appear in my page. No json result in the page but i can see it in the firebug network menu.
May i miss something?
kalaoke
I know this question is old, but I thought I might be able to help. I actually work at SurveyGimzo. We actually do support JSONP, JSON and XML. However; in order to request JSONP you need to specify this in the url. Using your example URL, it would look like this.
https://restapi.surveygizmo.com/v3/survey/:id.jsonp
Now when you request JSON_CALLBACK as part of the your ngResource parameters for your get action, you will get a properly wrapped object back.
I have been tinkering around with a minnie AngularJS app using SG REST api. You are welcome to take a look at my github https://github.com/sfisherGizmo/ang-app
I hope this helps anyone else who may happen across this as well.
Survey Gizmo does not support JSONP.
HTTP Methods which are supported by Survey Gizmo are
PUT, POST, DELETE
see
http://developer.surveygizmo.com/rest-api-documentation/methods/
Or if they support they did not specify that in the API doc.
this is what i see when u change .get to .query
Request URL:https://restapi.surveygizmo.com/v3/survey/xxxx
Request Method:OPTIONS
Status Code:200 OK
and if you go ahead with .get the response is
Request URL:https://restapi.surveygizmo.com/v3/survey/xxxx
Request Method:GET
Status Code:200 OK
But the response is not wrapped in JSONP callback. Though you are able to see a response in firebug network console but angular is not able to unwrap it since its not a JSONP response.
Check http://jsfiddle.net/jhsousa/aQ4XX/ for angularjs examples using ngResource

Prevent JavaScript from breaking with a 403 HTTP response

I'm grabbing user information from the Last.fm website with a JQuery $.get request.
Since some users' accounts are private, I sometimes receive a 403 error stating that authentication is required. This breaks the JS code. The last.fm API doesn't let you see if a user is private or not.
Is there a way to catch this error and continue through the code?
Thanks!
Not sure if it works with cross-domain requests, but you could do something like this:
$.ajax({
type: 'GET',
statusCode: {
403: function() {
alert('a 403 was received');
}
},
success: function() {
alert('everything OK');
}
});
Or possibly set it up in $.ajaxSetup() if it works ?
You would be better using a proxy to get the data from API since $.ajax() error handler won;t return errors for cross domain requests per jQery API docs:
http://api.jquery.com/jQuery.ajax/
EDIT Note in docs for error option:
"Note: This handler is not called for cross-domain script and JSONP requests."

I need to know about the response type of $.ajax() method in jquery

I am working on an e-commerce site and I need google sign-on it, so when a user creates his/her shopping list and click on the add to list button. I am able to send my data through the $.ajax() method, so what I exactly want is when the response from ajax method come it should redirect me to Login page if the user is not logged in, else it should save my object.
In the target endpoint of that .ajax() call, check your authentication, and if the user is not logged in, set the response header to - 401 Unauthorized.
Then in the .ajax() do this:
$.ajax(function() {
//.. your other ajax stuff..//
error: function(jqXHR, textStatus, errorThrown) {
// only redirect if user unauthorized - 'errorThrown' has text part of HTTP status header
if(errorThrown == "Unauthorized") {
window.location.href = "myloginpage.html";
}
}
});
The response header being set to 401 will trigger .ajax()'s error function, instead of the success function.
Edit:
Changed the error function to only redirect on Unauthorized
Also note, that if this is a cross-domain jsonp call, it won't work, as jsonp requests fail silently and don't trigger the error function
check in your response callback function and write your programming logic that you want
$.ajax({
'url':location,
'type':type,
'success':function(response){
/*write here your logic*/
},
'error':function(){
/*you code for error handling*/
}
});
to redirect window by javascript use
window.location.href = 'your location';
You can redirect to login page using window.location = 'yourlocation' in either success or error function of the response (depending upon what response you are gettig from server. If you are bringing the response code in header 401 error function will be executed other wise success).
but i think what you would like to have is take user back to the same page after login from which he started.
If you are interrested in this, you can use spring security for this. Its very easy to integrate if you are using spring already.
If you are not using spring you might look for some alternative for the same. Following links may help you
Spring Security Ajax login
http://java.dzone.com/articles/implementing-ajax
In jquery there is .post() method found to do this. In action page you can do whatever you want.

Categories