I am trying to access an custom API built with Laravel using a Mobile Apps but getting a 404 Error. I have tried some of the solutions listed on this website but to no avail.
I am using an Ajax request to fetch data like this
$.ajax({
type:'POST',
url: 'http://192.1**.**.**/mysite/api/v1/details',
data: {id:id},
dataType:"json",
success: function(data)
{
alert(data);
var comment='';
for(var i = 0; i < data.length; i++) {
comment = data[i];
}
if (comment.userid){
Notification('Login Successful');// display success
setTimeout(function(){ window.location.assign('main.html'); },2000);
}
else if (comment.error){
Notification(comment.error);// display error
}
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert("Not connected. Verify Network.");//show error
} else if (jqXHR.status == 404) {
alert("Requested page not found. [404]");//show error
} else if (jqXHR.status == 500) {
alert("Internal Server Error [500].");//show error
} else if (exception === 'parsererror') {
alert("Requested JSON parse failed.");//show error
} else if (exception === 'timeout') {
alert("Time out error.");//show error
} else if (exception === 'abort') {
alert( "Ajax request aborted.");//show error
} else {
alert("Uncaught Error.\n" + jqXHR.responseText);//show error
}
}
});
I also tried changing the URL to something like this as suggested by somebody but still don't work.
url: 'http://192.1**.**.**/mysite/public/index.php/api/v1/details'
ROUTE
Route::group(array('prefix' => 'api/v1', 'before' => 'auth.basic'), function()
{
Route::resource('users', 'UsersController');
Route::resource('details', 'DetailsController');
});
Please I am stuck badly, I need detail help.
Related
When a user clicks the edit icon the contents of a selectpicker are updated then refreshed. Then the selectpicker's value is updated, then refreshed again, but for some reason it is not updating with the selected value.
Everything works fine when I manually enter in the the same code in the console.
$('#IncWidgetId').val(864)// the value used when breaking in console
$('#IncWidgetId').selectpicker('refresh')
I have ensured that the selectpicker is updated with the new option values along with confirming the deferred is firing in the proper order.
As a double check, I also have separated the .selectpicker('refresh') to make sure it didn't try to fire before the option was selected due to async, but it is still not updating the selectpicker with the selected value.
$(document).on('click', '[id^=EditWidgetId-]', function () {
var id = $(this).attr('id').split('-')[1];
var mfg = $(this).data('mfg');
var widgetid = $(this).data('widgetid ');
var mfgSelect = $('input[name=mfg][value="' + mfg + '"]');
mfgSelect.prop('checked', true);
$.when(LoadWidgets(mfg)).then(function () {
console.log('then function');
$('#IncWidgetId').val(widgetid );
}).done(function () {
console.log('done function');
$('#IncWidgetId').selectpicker('refresh');
});
$('#modalWidgetNew').modal('show');
});
function LoadWidgets(mfg) {
var r = $.Deferred();
console.log('before ajax');
r.resolve($.ajax({
url: '/Widgets/FilterWidgetsDropdown',
type: 'GET',
cache: false,
data: { mfg: mfg },
success: function (partial) {
$('#IncWidgetDDArea').html(partial);
$('#IncWidgetId').selectpicker('refresh')
},
error: function (x, e) {
if (x.status == 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internel Server Error.');
} else if (e == 'parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
})).done(function () {
console.log('after ajax');
return r.promise();
});
}
What am I missing?
There was such an issue in old versions of this plugin.
Try to destroy it and initialize again. Something like this:
$('#IncWidgetId').selectpicker('destroy');
$('#IncWidgetId').selectpicker();
I am trying to use the following API https://postcodes.io/ and perform a bulk lookup using AJAX.
I can use the syntax provided in the documents to do a single postcode lookup like so:
$.ajax({
type: "POST",
url: 'https://api.postcodes.io/postcodes/BS16AA',
success: function (response) {
console.log(response);
},
error: function (xhr, ajaxOptions, thrownError) {
var msg = '';
if (xhr.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (xhr.status == 404) {
msg = 'Requested page not found. [404]';
} else if (xhr.status == 500) {
msg = 'Internal Server Error [500].';
} else if (thrownError === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (thrownError === 'timeout') {
msg = 'Time out error.';
} else if (thrownError === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + xhr.responseText;
}
}
});
However the example for "bulk lookups" is much less helpful (it looks like it wants an object with an array under a property called "postcodes: [myArrayHere]") I haven't managed to find a working example or create one myself. Using the example code above and the syntax for the bulk lookup i'd like to perform only a few ajax calls to lookup around 200 postcodes (the site says the limit is 100 at a time so I can break them in to several arrays). The time it takes to do a lookup for 200 postcodes in a loop is not really feasible for my project.
You need to use it like below
$.ajax({
type: "POST",
url: 'https://api.postcodes.io/postcodes/',
data: { postcodes: ["code1", "code2"] }
success: function (response) {
console.log(response);
},
error: function (xhr, ajaxOptions, thrownError) {
var msg = '';
if (xhr.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (xhr.status == 404) {
msg = 'Requested page not found. [404]';
} else if (xhr.status == 500) {
msg = 'Internal Server Error [500].';
} else if (thrownError === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (thrownError === 'timeout') {
msg = 'Time out error.';
} else if (thrownError === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + xhr.responseText;
}
}
});
See the test case they have which show the expected data
https://github.com/ideal-postcodes/postcodes.io/blob/373fda002692542f21330088154d3d4965a1cd65/tests/filter.integration.js#L33
I am submitting a form to node js server via ajax and expect an error if any, but instead of showing me the error , i am redirected to a whole new page with the error. I have used res.send , res.json, res.writheHead()... But i am always redirect to a new page
$.ajax({
url: $this.attr('/api/adduser'),
type: $this.attr('POST'),
data: $this.serialize(),
dataType: 'json', // JSON
success: function(json) {
alert('Erreur : '+ json.reponse);
}
})
event.preventDefault()
and on the server side i have:
sql.query("INSERT into internes(email,nom,prenom,password,privilege,datenaissance,gender,details,user_Add_Mail)"+
" VALUES(lower($1),lower($2),lower($3),lower($4),lower($5),$6,$7,lower($8),lower($9))",
req.body.email,req.body.nom,req.body.prenom,req.body.pass1,priv,req.body.datenaissance,parseInt('0'),req.body.details,req.body.passAdmin)
.then(function(result){
res.redirect('/api/users');
})
.catch(function(erreur){
res.json(400, {'success': erreur})
})
It seems that the error you're getting is being identified as a successful response from your sql promise. To fix that do something like
sql.query("INSERT into internes(email,nom,prenom,password,privilege,datenaissance,gender,details,user_Add_Mail)"+
" VALUES(lower($1),lower($2),lower($3),lower($4),lower($5),$6,$7,lower($8),lower($9))",
req.body.email,req.body.nom,req.body.prenom,req.body.pass1,priv,req.body.datenaissance,parseInt('0'),req.body.details,req.body.passAdmin)
.then(function(result){
// look into your result to see if you have what you asked for
if(result.error) {
res.status(500).send({error: 'you have an error'});
}
res.redirect('/api/users');
})
.catch(function(erreur){
res.json(400, {'success': erreur})
})
One option is to use ajax error:
success: function (json) {
alert(json);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
}
Doc
Trying to create multiple objects with django tastypie using Jquery and its failing alerts Not connect as specified in the code below. But performing a request with curl using the same data(sent_data) am passing to ajax, works perfectly.
sent_data = {"objects":[{"shopping_id":"#3Q^9%LF728N!9*840H(NEAH2L%J8$3H2J35(ZI#32MSA!S#RD%D3#PQG9^2#*J69S4&7IJX)POV$PYQ70817P2C!6OEPA%*$WR7","quantity":"3","option":"/api/v1/option/2/","item":"/api/v1/item/1/","created_by":"/api/v1/user/-1/","modified_by":"/api/v1/user/-1/","toppings_and_extras":["/api/v1/topping/1/","/api/v1/topping/2/"]},{"shopping_id":"#3Q^9%LF728N!9*840H(NEAH2L%J8$3H2J35(ZI#32MSA!S#RD%D3#PQG9^2#*J69S4&7IJX)POV$PYQ70817P2C!6OEPA%*$WR7","quantity":"3","option":"/api/v1/option/2/","item":"/api/v1/item/1/","created_by":"/api/v1/user/-1/","modified_by":"/api/v1/user/-1/","toppings_and_extras":["/api/v1/topping/1/","/api/v1/topping/2/"]}]};
$.ajax({
type:'POST',
url:'http://localhost:8000/api/v1/order/',
contentType: 'application/json',
data:sent_data,
headers:{'X-HTTP-Method-Override':'PATCH'},
dataType:'json',
processData:false,
success: function(data){
alert("POST request made");
},
error: function(jqXHR,exception){
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
Looking at django-tastypie PATCH gives me a "400 (Bad Request)" and Ajax Post Request to TastyPie Doesn't Do Anything figured since i am trying to make a bulk operation as mentioned in the docs, i had to use 'PATCH' method, which i did by providing a X-HTTP-Method-Override header but all on vain. What Could i have missed?
After doing more research, i figured problem was that i was not setting a header for the 'CSRFToken' in the form, this gist here helped me figure it out. So the working request looks this,
sent_data = JSON.stringify({"objects":[{"shopping_id":"#3Q^9%LF728N!9*840H(NEAH2L%J8$3H2J35(ZI#32MSA!S#RD%D3#PQG9^2#*J69S4&7IJX)POV$PYQ70817P2C!6OEPA%*$WR7","quantity":"3","option":"/api/v1/option/2/","item":"/api/v1/item/1/","created_by":"/api/v1/user/-1/","modified_by":"/api/v1/user/-1/","toppings_and_extras":["/api/v1/topping/1/","/api/v1/topping/2/"]},{"shopping_id":"#3Q^9%LF728N!9*840H(NEAH2L%J8$3H2J35(ZI#32MSA!S#RD%D3#PQG9^2#*J69S4&7IJX)POV$PYQ70817P2C!6OEPA%*$WR7","quantity":"3","option":"/api/v1/option/2/","item":"/api/v1/item/1/","created_by":"/api/v1/user/-1/","modified_by":"/api/v1/user/-1/","toppings_and_extras":["/api/v1/topping/1/","/api/v1/topping/2/"]}]});
$.ajax({
url:'/api/v1/order/?format=json',
accepts:'application/json',
contentType: 'application/json',
headers:{
'X-HTTP-Method-Override':'PATCH'
},
method:'POST',
data:sent_data,
beforeSend:function(jqXHR,settings){
jqXHR.setRequestHeader('X-CSRFToken',$("input[name=csrfmiddlewaretoken]").val())
},
dataType:'json',
processData:false,
success: function(data){
alert("damn posted");
},
error: function(jqXHR,exception){
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
Also notice i passed to a JSON.stringify() method.
I have following controller method:
[HttpPost]
[Authorize(Roles="some_role_actual_user_is_NOT_in")
public ActionResult AJAXMethod()
{
return Json(new { message = "server message");
}
and page with script:
function sendReq()
{
$.ajax({
type: "POST",
data: { somedata: "somedata" },
url: "/Path/To/AJAXMethod",
success: onAJAXSuccess,
error: onAJAXError
});
}
function onAJAXSuccess(response, status, xhr)
{
alert("success: " + response.message);
alert(status);
}
function onAJAXError(xhr,status,error)
{
alert("error: " + status);
alert(error);
}
When I call sendReq with user not in the authorized role the AJAX call still suceed - callback onAJAXSuccess is called, but response.message is undefined.
This is correct behaviour. The success of an AJAX call is only determined by the fact the the server responded with a 200 OK. You will need to interrogate the returned response yourself to ensure it is in the format you expect.
For example:
if (typeof response.message != "undefined" && response.message != "") {
// it worked
}
else {
// didn't work || user did not have access.
}