I want to get the data response from my login webservice. Here is my web service
http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a
(for testing). Here is my code:
$("#login").click(function () {
var url = "http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a";
$.ajax({
url: url,
type: 'Get',
success: function (data) {
alert(data.Medical_id);
},
});
});
The alert() shows me undefined. Please advise on what the problem could be.
The result is an array, so in order to get that field you have to iterate the result or get the first item:
for (var i in data) {
console.log(d[i].Medical_id);
}
Or you can simply get the first result:
$.ajax({
url: 'http://41.128.183.109:9090/api/Data/getloginer?medid=a&pass=a',
type: 'Get',
success: function (data) {
alert(data[0].Medical_id);
}
});
The JSON result you are getting is :
[{"$id":"1","id":8,"Medical_id":"a","Password":"a","Name":null,"Email":null,"gender":null,"Type":null}]
use for each to iterate through the results or
instead of this you can check the result like this :
var data = [{ "$id": "1", "id": 8, "Medical_id": "a", "Password": "a", "Name": null, "Email": null, "gender": null, "Type": null }]
alert(data[0].Medical_id);
If you develop application in localhost then refer this questions also.
"No 'Access-Control-Allow-Origin' header is present on the requested resource"
If you are using chrome, then use this link to use CORS enable plugin.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US
hope this will help
Related
I'm doing an AJAX GET request to an API that returns all stores in my area that offer express delivery. I need to check over the data to see if any store in the area offer express delivery but can't access the data properly to perform any check's and don't understand why.
A stripped back version of the data returned from the API is here:
{
"data": {
"service_eligibility": [
{
"accesspoint_list": [
{
"current_time": null,
"currency": null,
"accesspoint_id": "3242342-6dc1-43d8-b3d0-234234234234",
"service_info": {
"fulfillment_type": "DELIVERY",
"reservation_type": "SLOTS",
"dispense_type": "DELIVERY",
"priority": 0,
"carrier": "Owned",
"fulfillment_option": "DELIVERY",
"location_type": "Home",
"service_time": 0,
"is_recurring_slot": false,
"enable_express": false,
"is_unattended_slot": true,
"is_flex_slot": false
},
{
"current_time": null,
"currency": null,
"accesspoint_id": "234234242-3387-4e1d-9eaa-234234242",
"service_info": {
"fulfillment_type": "INSTORE_PICKUP",
"reservation_type": "SLOTS",
"dispense_type": "PICKUP_INSTORE",
"priority": 0,
"carrier": "NA",
"fulfillment_option": "PICKUP",
"location_type": "Store",
"service_time": 0,
"is_recurring_slot": false,
"enable_express": true,
"is_unattended_slot": false,
"is_flex_slot": false
},
"current_time": "2021-06-07T11:24:39Z",
"currency": "GBP"
},
"status_code": 200,
"status_message": "Requested input executed successfully."
}
The call I use to get my data:
$.ajax({
type: 'GET',
dataType: "json",
url: query,
data: "",
success: function(data)
{
//Check for express delivery
if(data.status_code == 200) {
console.log(data);
}
},
error: function(data)
{
//Check for API error
if(data.status == 400){
console.log(data.responseJSON.errors[0].message);
}
}
})
So far the data is being logged to the console. But when I try to access it or parts I want to use I get console errors.
I have tried copying the property path from the console and using it in the console.log:
console.log(data.service_eligibility[0].accesspoint_list)
but get the error message:
Cannot read property '0' of undefined
I have tried just data.service_eligibility but this just give me the error of undefined
In fact even if I just try to access data.currency I get undefined
Why can I not access the data being returned from the API?
type: 'GET',
dataType: "json",
url: query,
data: "",
success: function(data)
{
//Check for express delivery
if(data.status_code == 200) {
console.log(response.data.ervice_eligibility[0].accesspoint_list);
}
}
Looking at the above piece of code you have provided, it looks like, the data object that you are receiving in the success handler does not directly refer to the data object inside your received response. Given the names are same, it can be confusing.
I think if you try accessing the property inside the data object using data.data.service_eligibility, you will be able to access it. For some more clarity, see the code below:
type: 'GET',
dataType: "json",
url: query,
data: "",
success: function(response)
{
//Check for express delivery
if(response.status_code == 200) {
console.log(response.data.service_eligibility[0].accesspoint_list);
}
}
Just think about it, if your data is available inside the success handler, it means that the asynchronous action of fetching the data from the api has successfully completed. You can just debug the structure of your data object and find out what's missing or what's wrong in the way you are accessing a value. People can behave differently, code can never! :)
I'm trying to retrieve some data from the MediaWiki Api; especifically the registration date of a certain user. Taking Wikipedia as a live example, according to their Api sandbox, the request URL to get the information of Jimmy Wales would be:
/w/api.php?action=query&list=users&format=json&usprop=registration&ususers=Jimbo_Wales
So I make an Ajax call:
$.ajax({
dataType: "jsonp",
url: "/w/api.php?action=query&list=users&format=json&usprop=registration&ususers=Jimbo_Wales",
success: function (data) {
var timestamp = data.query.registration;
console.log(timestamp);
}
});
But if I run that script on Firebug, I simply get "undefined". What am I missing?
The resulting JSON data is something like:
{
"batchcomplete": "",
"query": {
"users": [
{
"userid": 24,
"name": "Jimbo Wales",
"registration": "2001-03-27T20:47:31Z"
}
]
}
}
Of course, data.query.registration is undefined. it is not available. Your have to "address" the user itself. Like data.query.users[0].registration.
How to get display return values from the JSON values.I need to get value the user id
$('User_id').observe('blur', function(e) {
var txt = $('User_id').value;
jQuery.ajax({
type: 'get',
url: BASE_URL + 'admin/index/user_id',
data: {
user_id: txt
},
dataType: 'json',
success: function(data) {
console.log('success' + data.success);
if (data.success) {
var Value = data.location.user_id;
alert(Value);
}
}
});
});
These values are getting in html form. In that I need to store user id in Value varable. But I receive successundefined as a output..
[{
"user_id": "139",
"mobile": "9042843911",
"gender": "male",
"hashcode": "DfAbMqLApAV6nVa1z940",
"username": "anandhsp21",
"password": "74bcff7d1199012e154f364e3f65e31d:8I",
"authorized_person": "Anandh",
"created": "2015-06-08 13:46:55",
"modified": "2015-06-08 06:43:35",
"logdate": "2015-06-08 08:16:55",
"lognum": "12",
"reload_acl_flag": "0",
"is_active": "1",
"extra": "N;",
"rp_token": null,
"rp_token_created_at": null,
"app_name": "",
"api_key": ""
}]
Please some one help. Thanks in Advance
Your get the data in array so use loop in success data
for (var i=0; i<data.length; i++) {
console.log('success' + data[i].user_id );
}
If you know the record length is 1 then use directly
console.log('success' + data[0].user_id );
Your data is an array that contains one object. So you can access this object using :
success: function(data){
console.log('success' + data[0].user_id );
Trying to log success is pointless, because there is no success key whatsoever in the received data.
Make sure that you get the response in proper json format,and as harshad pointed String male should be wrapped in double quotes.
After you get that fixed,you can access the user_id as:
data[0].user_id
data.success is undefined, because the received data is stored directly in data. That's the first argument of the success block. You can access the received data directly by data[0] to get the object inside of the array, or if you have a larger array you can do a for each loop over it, etc..
Try this, simply use json.parse()
$(document).ready(function() {
var v = ['{"user_id":"139","mobile":"9042843911"}'];
var obj = JSON.parse(v);
alert(obj.user_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
To get userid please follow below code I edited,
$('User_id').observe('blur', function(e) {
var txt = $('User_id').value;
jQuery.ajax({
type: 'get',
url: BASE_URL + 'admin/index/user_id',
data: {
user_id: txt
},
dataType: 'json',
success: function(data) {
// this below userid is the value user_id you want.
var userid = data[0].user_id;
}
});
});
There is a json error
"gender":male
Strings male should be wrapped in double quotes.
you need to make sure that your response is formatted appropriately and according JSON.org standards.
This question already has answers here:
How do I send a cross-domain POST request via JavaScript?
(17 answers)
Closed 8 years ago.
I've wrote a snippet for axis room API. While passing the json for testing, I have got Cross-Origin Request Blocked error.
At the same time console shows: {"message":"Could not parse the message.","status":"Error"}. (see the below image)
I hasn't solution for Cross-Origin Request Blocked error. But now I want to show the Could not parse the message error. How to do that?. Is a good way to solve Cross-Origin Request Blocked error. suggest me please.
My JavaScript code
<script type="text/javascript">
$(function () {
$('#Button1').click(function () {
alert('Alter with jQuery Button Clicked');
alert('Clicked');
$.ajax({
type: 'POST',
url: 'http://test.axisrooms.com/api/daywiseInventory',
data: '{"accessKey": "7eb228097576abf56968e9845ab51b90","channelId": "103","hotels": [{"hotelId": "2","rooms": [ {"roomId": "1", "availability": [ { "date": "2014-05-30","free": 1},{"date": "2014-05-31","free": 1}]}]}]}',
//data: "{accessKey':'cilentAPIKey'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
callback(data);
alert('sus'+data.toString());
},
error: function (response) {
//alert(response);
//alert('error' + response.valueOf(message));
alert('An error has occured');
}
});
});
});
</script>
You cannot get the response status, code nor headers of the XHR object via javascript for a cross origin request... you just got a success status but empty response.
First of all your json is not correct formated.
Go to jsonlint and paste your json in there. I guess you have to use double cotes like this.
test it, and come back if it does not work.
{
"accessKey": "7eb228097576abf56968e9845ab51b90",
"channelId": "103",
"hotels": [
{
"hotelId": "2",
"rooms": [
{
"roomId": "1",
"availability": [
{
"date": "2014-05-30",
"free": 1
},
{
"date": "2014-05-31",
"free": 1
}
]
}
]
}
]
}
I have a PHP function that echoes out JSON data and pagination links. The data looks exactly like this.
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
Previous
Next
To get these data, I would use jQuery.ajax() function. My code are as follow:-
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: "page="+page,
success: function(msg)
{
$("#area").ajaxComplete(function(event, request, settings)
{
$("#area").html(msg);
});
}
});
}
Using jQuery, is there anyway I can scrape the data returned from the AJAX request and use the JSON data? Or is there a better way of doing this? I'm just experimenting and would like to paginate JSON data.
It's better to not invent your own formats (like adding HTML links after JSON) for such things. JSON is already capable of holding any structure you need. For example you may use the following form:
{
"data": [
{"name": "John Doe", "favourite": "cupcakes"},
{"name": "Jane Citizen", "favourite": "Baked beans"}
],
"pagination": {
"prev": "previous page URL",
"next": "next page URL"
}
}
On client-side it can be parsed very easily:
$.ajax({
url: "URL",
dataType:'json',
success: function(resp) {
// use resp.data and resp.pagination here
}
});
Instead of scraping the JSON data i'd suggest you to return pure JSON data. As per your use case I don't think its necessary to write the Previous and Next. I am guessing that the first object in your return url is for Previous and the next one is for Next. Simply return the below string...
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
and read it as under.
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
dataType:'json',
success: function(msg)
{
var previous = msg[0]; //This will give u your previous object and
var next = msg[1]; //this will give you your next object
//You can use prev and next here.
//$("#area").ajaxComplete(function(event, request, settings)
//{
// $("#area").html(msg);
//});
}
});
}
This way return only that data that's going to change not the entire html.
put a dataType to your ajax request to receive a json object or you will receive a string.
if you put "previous" and "next" in your json..that will be invalid.
function loadData(page){
$.ajax({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: {'page':page},
dataType:'json',
success: function(msg){
if(typeof (msg) == 'object'){
// do something...
}else{
alert('invalid json');
}
},
complete:function(){
//do something
}
});
}
and .. in your php file, put a header
header("Content-type:application/json");
// print your json..
To see your json object... use console.log , like this:
// your ajax....
success:(msg){
if( window.console ) console.dir( typeof(msg), msg);
}
Change your json to something like this: (Use jsonlint to validate it - http://jsonlint.com/)
{
"paginate": {
"previous": "http...previsouslink",
"next": "http...nextlink"
},
"data": [
{
"name": "JohnDoe",
"favourite": "cupcakes"
},
{
"name": "JaneCitizen",
"favourite": "Bakedbeans"
}
]
}
You can try this :-
var jsObject = JSON.parse(your_data);
data = JSON.parse(gvalues);
var result = data.key;
var result1 = data.values[0];