I am trying to make an application that allows the user to search through the College Scorecard API. I am very new to ajax so I am not sure what I have done incorrectly here. I have the textAjax() function hooked to a button on my HTML form, but when I run my code, the request fails. Here is my code.
function testAjax(){
$.ajax({
type : 'POST',
url : 'https://api.data.gov/ed/collegescorecard/v1/schools?school.name=University%20of%20Cincinnati&api_key=<API-KEY>',
dataType : 'json',
success : function(data) {
//if the request is successful do something with the data
alert(data);
},
error : function(request){
//if the request fails, log what happened
alert(JSON.stringify("Error: " + request));
}
});
}
function buttonClick() {
var url = testAjax();
}
There is a data attribute for queries to be added to your url so you don't have to do it yourself. Check this out:
function testAjax(){
$.ajax({
type : 'POST',
url : 'https://api.data.gov/ed/collegescorecard/v1/schools',
data: {
'name': 'University of Cincinnati',
'api_key': 'whatever'
},
dataType : 'json',
success : function(data) {
//if the request is successful do something with the data
alert(data);
},
error : function(request){
//if the request fails, log what happened
alert(JSON.stringify("Error: " + request));
}
});
I'm not sure if this is your only problem, but it might help.
Related
I am getting bad request 400 error while sending request with parameters to controler I have checked whole sysntax but I did not wind any mistake, please look at my code whats wrong there?
var url = contextPath+"/billingControler/getOrdersByResWiseTables";
$.ajax({
url : url,
data : "&resID="+$("#rsId").text()+"&tblid="+tableId,
type : "get",
dataType : "json" ,
contentType : 'application/json; charset=utf-8',
success : function(response) {
console.log(response);
}
});
error :
jquery-3.3.1.min.js?_=1520931033076:2 GET http://localhost:8088/smartpos/billingControler/getOrdersByResWiseTables?&resID=11&tblid=3 400 (Bad Request)
please check my java code
#RequestMapping(value="/getOrdersByResWiseTables", method=RequestMethod.GET, produces="application/json")
public List<OrderBans> getOrdersByResWiseTables(#RequestParam("resId") String resId,#RequestParam("tblid") String tableid) {
String result="";
logger.debug("Started adding order");
RestypeIDao pdo = new RestypeIDaoImp();
List<OrderBans> orderList = pdo.getOrdersResWIseTbles(resId, tableid);
System.out.println(orderList);
logger.debug("end adding order");
return orderList;
}
You have extra & in your URL.
Also, you're using data attribute wrong, it should be an object.
Try this:
var url = contextPath+"/billingControler/getOrdersByResWiseTables";
$.ajax({
url : url,
data: {
"resID": $("#rsId").text(),
"tblid": tableId
},
dataType:"json",
contentType:'application/json; charset=utf-8',
success:function(response) {
console.log(response);
}
});
I am currently using the dark sky forecast api https://developer.forecast.io/ to retrieve json object via jquery get request.the required url parameters format is (api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE") while the valid format with the parameters is:
https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115
inputting this url in your browser will show you a json object.
First thing i tried was a jquery get request :
$.ajax({
type: 'GET'
, data: ''
, url: "https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115"
, success: function (data) {
alert("works");
}
, datatype: 'json'
, error: function (err) {
alert("Could not get forecast");
}
});
this is not succesful- it triggers the error function. i try again using a post request it doesnt work either.please help
This is a simple CORS issue which can be easily resolved by using jsonp datatype:
$.ajax({
url: "https://api.forecast.io/forecast/02a90a53f4705dc5e5b54f8cda15d805/9.055169,7.49115",
dataType: "jsonp",
success: function(data) {
console.log(data.latitude, data.longitude);
console.log(data.timezone);
console.log(data.daily.summary);
},
error: function(err) {
console.log("Could not get forecast");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<em>Loading . . .<em>
I have the following code:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify($(this).serializeArray()),
dataType:'json'
});
});
And after I submit the form, I get a JavaScript alert with the json string, so that is made correct (on my server I only log it so it does not matter what it is in it). If I try to send a request to the same link from postman it works, it logs it.
I think I'm doing something wrong in the ajax call, but I am not able to figure out.
Try below piece of code. Add success and error handler for more details
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($(this).serializeArray()),
dataType:'json',
success : function(response) {
alert("success");
},
error: function (xhr, status, error) {
alert(error);
}
});
});
data:{ list : JSON.stringify($(this).serializeArray())}
From the Jquery docs:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url.
$.ajax({
url:'http://127.0.0.1:1337/receive',
data:{ apikey: 'secret-key-or-any-other-parameter-in-json-format' },
dataType:'jsonp',
crossDomain: 'true',
success:function (data) {alert(data.first_name);}
});
hi i am calling a php file using ajax after an interval of time. In my php file i simply echo a text line. But it didnt show me any output after time interval..
here is my ajax code form where i am calling my php file..
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"}, });
}, 5000);
});
</script>
code inside the process.php file
<?php
echo "hello testing";
?>
You aren't handling the response from php script. You need to get it by success parameter in ajax. Try this:
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: 'x=1&y=2', // data here! use query strings like this or;
// data: { x: '1', y: '2' }
success: function(response) { alert(response); } // alert the response text
// returns 'hello testing'
error: function(){ alert('error while posting data'); }
});
}, 5000);
});
User the success and error function of ajax. for eg
$.ajax ({
url: 'process.php',
type:'post'
data:data1,
success: function (response) {
//alert response here you will get the value hello testing
alert (response);
},
error {
alert ('error');
}
});
You should modify your code to use the response.
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"},
success:function(str){
$("#YOUR_ELEMENT").html(str);
}
});
}, 5000);
});
Just change your JQuery script to show the response after successful request it can be done with done() or success functions.
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: { token: "your_token"}}).done(function(msg){
$("#response").append(msg);
};
}, 5000);
});
This will append reponses to #response every 5s when ajax request is successful.
the success block, which handles the data returned from remote script is present in your code. you may need to add something like this .
JS CODE:
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"},
}).done(function( data) {
//data received from remote script
});
}, 5000);
});
Happy Coding :)
Timeout is not the culprit here.
We need to make sure that you have a server where process.php resides and its running fine.
Make sure the path for the file process.php is right. You can use browser's developer tools. When the request is made you will see a new entry under "Network" tab of the developer tools. Exploring it you can get the url at which it the file should be available.
I would suggest using Google Chrome's "postman" extension to test the ajax call before implementing it in your code.
Also you need to have a callback that will run in case of request success or failure. Once you get the string in success response, you can do whatever you intend to do with it.
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"} //removed the comma from last argument
}).done(function(serverResponse) {
alert( "Success: " + serverResponse ); //Will show success alert with concatenated text string if the request is successful
}).fail(function(serverResponse) {
alert( "Error: " + serverResponse.message); //Will show error alert with concatenated error message
});
}, 5000);
});
</script>
the php page sends the string "hello testing", and you have to manage it.
take a look here for an example: click me
I am working now in a phonegap android application, I need the user's current address, so that i have used this
JSON api.
This is my code to get data for location updates from JSON api
$.ajax('http://maps.googleapis.com/maps/api/geocode/json?latlng=26.9008773,75.7403539&sensor=true', {
dataType: 'jsonp',
timeout: 3000,
data: {
_method: 'GET'
},
success: function (data,status) {
if (data._status != 200) {
console.log('received error', data._status);
// handle error
}else{
console.log('received data', data);
// do something useful with the data
}
},
error: function(data,status) {
var myObject = JSON.stringify(data);
console.log("Data Returned is " + myObject);
console.log("Status is " + status);
alert('error');
},
complete: function(data, status) {
alert('complete');
}
});
Every time it goes on error section , then the complete section, never goes into the success part.
the console output is :
12-10 11:11:34.393: I/Web Console(10620): Data Returned is {"readyState":4,"status":404,"statusText":"error"} at file:///android_asset/www/index.html:263
12-10 11:11:34.393: I/Web Console(10620): Status is error at file:///android_asset/www/index.html:264
Can anyone tell me, where exactly the problem is ?
If I remember correctly the default security policy in PhoneGap is to block all network access. You need to whitelist http://maps.googleapis.com.
The api you request does not support jsonp, the final request will like this:
http://maps.googleapis.com/maps/api/geocode/json?callback=jQuery18309743240959942341_1386656119920&latlng=26.9008773,75.7403539&sensor=true&_method=GET&_=1386656120107
with the callback param, but the output is still json, not javsscript file like
jQuery18309743240959942341_1386656119920(jsonDataHere...)
Take a look at this: https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse, it request url like this
https://maps.googleapis.com/maps/api/js/GeocodeService.Search?5m2&1d40.714224&2d-73.96145200000001&7sUS&9sen&callback=_xdc_._4cni6z&token=46423
And the output is:
_xdc_._4cni6z && _xdc_._4cni6z( { ....
That's jsonp.
ajax_call ='http://maps.googleapis.com/maps/api/geocode/json?latlng=26.9008773,75.7403539&sensor=true';
$.ajax({
type: "GET",
url: ajax_call,
cache:false,
dataType: "json",
success: function(response){
$.each(response.results, function(key, value) {
//alert(value.formatted_address);
console.log(value.formatted_address);
});
}
}).done(function() {
})