Postcodes.io bulk lookup - ajax

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

Related

ajax returns error but the process was successful

My ajax always returns error each time I run it but when I refresh the page the data was updated upon each trigger
My ajax
$.ajax({
url:"exe/deduct.php",`enter code here`
method:"POST",
data: {deductQty: deductQty, itemID: itemID, oldQty: oldQty},
success: function(data){
alert(data);
window.location.href="deduct.php";
},
error: function(jqXHR, exception){
alert(data);
}
});
My PHP Code
<?php
include('database.php');
if($_POST){
$itemID = $_POST['itemID'];
$deductQty = $_POST['deductQty'];
$oldQty = $_POST['oldQty'];
$answer = $oldQty - $deductQty;
$query = "UPDATE `item` SET `qty` = '$answer' WHERE `id` = '$itemID'";
if(mysqli_query($con,$query)){
echo "Restock Success";
}else{
echo "Restock Failed";
}
}
?>
make sure the url location is accurate.
the response can be print inside a div $('#divid').html(response);
$.ajax({
url:"exe/deduct.php",
method:"POST",
data: {deductQty: deductQty, itemID: itemID, oldQty: oldQty},
success: function(response){
alert(response);
//$('#divid').html(response);
//window.location.href="deduct.php";
},
error: function(jqXHR, exception){
var message = '';
if (jqXHR.status === 0)
message = 'Not connect.\n Verify Network.';
else if (jqXHR.status == 404)
message = 'Requested page not found. [404]';
else if (jqXHR.status == 500)
message = 'Internal Server Error [500].';
else if (exception === 'parsererror')
message = 'Requested JSON parse failed.';
else if (exception === 'timeout')
message = 'Time out error.';
else if (exception === 'abort')
message = 'Ajax request aborted.';
else
message = 'Uncaught Error.\n' + jqXHR.responseText;
alert(message);
}
});

How to return error message from ajax post in Node.js

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

Retrieving of Restful web service values in android for Titanium

We are using the same restful web service code from serviceutility.js for both android and ios. But the service is getting hit and values are retrieved only in ios. The same code is not working in android and we are getting the following error:
[ERROR] : TiExceptionHandler: (main) [2,821093] - In alloy/controllers/home.js:25,32
[ERROR] : TiExceptionHandler: (main) [0,821093] - Message: Uncaught TypeError: Cannot read property 'status' of null
[ERROR] : TiExceptionHandler: (main) [0,821093] - Source: if ("1" == response.status) alert(response.message); else if ("0"
[ERROR] : V8Exception: Exception occurred at alloy/controllers/home.js:25: Uncaught TypeError: Cannot read property 'status' of null.
Titanium SDK is 5.1.2 GA
exports.login = function(user, cb) {
var response = null;
if (Ti.Network.online) {
var xhr = Ti.Network.createHTTPClient({
timeout : 10000,
validatesSecureCertificate : false
});
xhr.onload = function() {// Onload
var responseTxt = this.responseText == '' ? '{}' : this.responseText;
try {
response = JSON.parse(responseTxt);
cb(response, 'SUCCESS');
} catch(e) {
cb(response, 'ERROR');
}
};
xhr.onerror = function(e) {
if (xhr.status === 0) {
cb(response, 'TIMEDOUT');
} else {
cb(response, 'ERROR');
}
};
url = "https://";
var postData = {
employeeId : user.employeeId,
password : user.password
};
xhr.open('POST', url);
xhr.setTimeout(10000);
xhr.setRequestHeader('employeeId', user.employeeId);
xhr.setRequestHeader('password', user.password);
xhr.send();} else {
cb(response, 'NO_NETWORK');
}};
The below code is for index.js file where the actual retrieval of values happen.
if (Ti.Network.online) {
loginUtil.login(user, function(response, status) {
Ti.API.info("status----" + status);
if (response.status == "0") {
Ti.API.info("status== " + response.status);
Ti.App.role = response.role;
Alloy.createController('home', {employeeId:$.userTextField.value,password:$.passwordTextField.value,from:"index"}).getView().open();
} else if (response.status == '1') {
alert(response.message);
} else {
alert("Please enter the correct credentials");
}
});
}
Please help us on this.
Looks like you are ONLY returning a string value instead of the entire response object. Then in your controller you attempt to access the .status property of the response object.
//this line returns the string responseTxt
response = JSON.parse(responseTxt);
Try returning the entire response object instead.
response = JSON.parse(this);
Then in your index.js controller use/ display the status property
alert(response.status);
Your index.js expected response to be an object, but that is only the case where you call callback like this:
response = JSON.parse(responseTxt);
cb(response, 'SUCCESS');
All other places where you call callback the response variable is null, since that is what you initialise it with on the second line.
Your callback returns two parameters, response & status, the second param is never used.
From reading the login function code, you only get to access the response object if status == "SUCCESS"
if(status === "SUCCESS"){
if (response.status == "0") {
Ti.API.info("status== " + response.status);
Ti.App.role = response.role;
Alloy.createController('home', {employeeId:$.userTextField.value,password:$.passwordTextField.value,from:"index"}).getView().open();
} else if (response.status == '1') {
alert(response.message);
} else {
alert("Please enter the correct credentials");
}
}
else {
alert("whoops, please try again !"); // a more generic message.
}

How do I access Laravel API via Ajax

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.

How to create multiple objects with django tastypie via Ajax using the PATCH method?

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.

Resources