I am currently learning the Laravel API, and have been developed a very simple API that retrieves data from the database by simply entering 127.0.0.1:8000/api/XXX to the browser, however, when I tried to use ajax call to get data from the exact same url, the ajax always showed that the HTTP request was failed, the ajax codes I used are following:
$.ajax({
url: "127.0.0.1:8000/api/XXX",
success: function(data) {
let response = JSON.parse(data);
displayResult(response, 1);
}
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
And this code always resulted in alert("error");, therefore I am wondering that maybe there are some Routes needed to be written in order to let the API properly processes HTTP request? I have already defined a route in routes\api.php:
Route::apiResource('XXX', 'XXXController');
PS: when entering the API URL to the browser, it worked fine, it went wrong when doing an ajax call with the API URL.
Edit
These are the errors I got from the browser console after I used function(jqXHR, textStatus, errorThrown) to catch the errors
DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL
at Object.send (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:79420)
at Function.ajax (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:77118)
at retrieveAllBooks (http://127.0.0.1:8000/js/api-query.js:25:5)
at HTMLInputElement.<anonymous> (http://127.0.0.1:8000/js/api-query.js:10:7)
at HTMLInputElement.dispatch (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:41772)
at HTMLInputElement.y.handle (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:39791)
I am not exactly sure why it is an invalid URL, since if I copy and paste this link to browser, nothing goes wrong...
(Posted on behalf of the question author).
Actually the solution is simple, just add http:// to the url.
Related
I have a small application and it has one route that returns JSON. If I use Postman or my browser, I get the correct result. Similarly, if I am running a server on my computer, I get the correct result.
On a live server, however, jQuery is encoding the api token before submitting it, and I'm not getting the result, just a 401 error.
let product_id = $(this).val()
let token = $('input[name=token]').val()
$.ajax({
url: 'api/campaign/',
data: {
'product_id': product_id,
'api_token': token,
},
success: function (data) {
// Do Stuff
}
})
I have seen a lot of questions here with the exact same problem, but none of them have a solution that works for me.
I have a NodeJS server setup and in an Angular controller I'm trying to get a contact form working. On form submission I call this function (this is only one of the many variations on a POST request I've tried):
$scope.submit_contact_form = function(){
$http({
method: "post",
url: 'http://' + window.location.host + "/form-u10657.php",
data: $scope.form_data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(data) {
$scope.status_message_toggle("Success");
}).error(function(){
$scope.status_message_toggle("Problem sending mail", 'warning');
});
};
But it always returns a 404 not found error. The php file is definitely in the right directory. Going to the url with a GET request works.
What is different in my setup, that I haven't seen in other questions, is that I am using a NodeJS server and ngRouteProvider.
Other answers have said to allow NodeJS to accept POST requests, but it hasn't been necessary to configure NodeJS before, and I would like to avoid it now.
Is there a way to fix it just in Angular? And if not what should I do with NodeJS to get it working?
Here is an excerpt from w3.org on http responses:
10.2 Successful 2xx
This class of status code indicates that the client's request was
successfully received, understood, and accepted.
10.2.1 200 OK
The request has succeeded. The information returned with the response is dependent on the method used in the request, for example:
GET an entity corresponding to the requested resource is sent in the response;
POST an entity describing or containing the result of the action;
Is it considered "received, understood, and accepted" when the $_POST[] variables are stored in some other variable?
EDIT: here is the ajax call which calls an empty php file.
$.ajax({
url: 'process.php',
data: 'type=new&title='+title+'&startdate='+start+'&zone='+zone,
type: 'POST',
dataType: 'json',
success: function(response){
event.id = response.eventid;
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
and it calls the error part of the ajax call. But the console shows no errors. Now why it chooses only error and not success ??
You don't need to store anything... it's only about the response code.
For example I can make a POST to a "script" that doesn't process anything, just a dummy empty file...
I don't really understand what's your "dilemma".
I am not any kind of RESTful API expert, but I have a simple PUT/DELETE function in an AngularJS app that has been functioning as expected until now. I am trying to work out whether this problem is likely to lie in my app, or in the (php) back-end that is running the endpoint. Other REST services are functioning normally & the server appears to be running fine.
This function only ever calls PUT or DELETE, assigned as var method:
if (food.favourite === true) {
method = "PUT";
console.log("method is " + method)
} else if (food.favourite === false) {
method = "DELETE";
console.log("method is " + method)
}
$http({
method: method,
url: $scope.URL
}).success(function (data, status, headers, config) {
console.log(method + " successful")
}).error(function (data, status, headers, config) {
console.log(method + " not successful")
});
I have one $http GET in my app that uses a different endpoint. There is no $http GET pointing to this endpoint anywhere in my app- I have searched extensively.
When I trigger the function containing the $http above, the console shows:
method is PUT
GET http://localhost:8888/api/ext/51/ 500 (Internal Server Error)
PUT not successful
Why would I be receiving a GET error on an unsuccessful PUT request? Does this point to a problem in my function, or a problem with the endpoint?
Thank you for any help in understanding this problem.
Update 1
Info from the Network panel: calling the $http function above triggers two simultaneous requests, one 'PUT' and one 'GET'. The 'PUT' returns a 301 code, and the 'GET' returns a 500 server error (which I think is to be expected, as this endpoint is not set up to respond to 'GET', only to 'PUT' and 'DELETE').
So: why would my code be generating two simultaneous requests with different methods?
For future seekers of answers to similar questions: it is a standard behaviour (of REST in general or this implentation? Not sure) to try to return a GET for every action that is called. Evidence for this is that if I check the Network panel for all the other (successful) $http functions, they also have two actions visible: the original PUT/GET/DELETE etc, + a GET.
We are seeing a 500 Error on the GET for these particular requests because the configuration of this particular endpoint does not allow for a GET. This should not have any effect on the PUT/DELETE actions on this endpoint- the 500 Error is not related to the reason why the PUT/DELETE actions weren't working. In terms of trying to solve this specific problem, it's a red herring.
The reason the PUT/DELETE was not working was because the service was broken on the server-side.
I ran into this and the issue was in how I was outputting the errors in the first argument for header. They need to be in this format:
header('400: Error', true, 400);
or in your case, of course:
header('301: Moved Permanently', true, 301);
header('Location: ' . $url);
Note that this WILL NOT work:
header('Some Random Text', true, 400); // $http.error shows status of 500
The following code works perfectly in Chrome and Safari, but bonks in Firefox.
First the javascript:
$.ajax('/sn.php',{
type: 'POST',
dataType: 'json',
data: {...stuff},
complete: function(response){
console.log(response);
// do stuff with response...
}
});
and the php relay (on MY server) that uses cURL() to POST or GET from another domain:
// setup cURL...
$token = curl_exec($handle);
echo $token;
error_log('token='.$token);
$token shows up perfectly in the error_log, and everything works perfect in Chrome and Safari, but in Firefox the ajax status is "error" and the responseText is blank. Been banging my head against the wall for a couple days on this one.
Firefox doesn't have a native console.log like Webkit browsers do. Comment that out or replace it with alert() and I bet it works.
I might be barking up the wrong tree here, but I suspect it's the call to error_log in your php code. If you remove that, does it help?
Also, it might help to set an error handler on your .ajax request too, something like
$.ajax('/sn.php',{
type: 'POST',
dataType: 'json',
data: {...stuff},
complete: function(response){
console.log(response);
// do stuff with response...
},
error: function (jqXHR, textStatus, errorThrown){
console.dir(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
It won't fix the problem, but it'll at least give you some more debug output to look at
edit Couple more ideas from 249692. Is your webserver returning the correct mime type for the request? Can you try doing a beforeSend and setting overrideMimeType
Firefox was returning Status: 0 for the ajax request. Based on a heads up from this blog post I updated my form to onSubmit='return false;' and now it works perfect.