Get response parameter value in ajax [duplicate] - javascript

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
}
]
}
]
}
]
}

Related

How to access data returned from an API using jQuery

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! :)

Build cusom json for ajax rest request

Im trying to send a request to a rest API and granted my knowledge using jquery is not advance however through numerous tutorials I'm struggling a bit to build a request based on this swagger documentation.
{
"fields": {
"": [
{
"NAME": "NAME"
},
{
"ADDRESS": "ADDRESS"
},
{
"EMAIL": "EMAIL"
}
]
}
}
This is the model of how i need to send the Rest request, im able to do this using postman however i struggle to do this in javascript.
var data = {};
var json = [{ "NAME": "name", "ADDRESS": "address", "EMAIL": "email" }];
data.fields ={json};
My problem is that in the model there is an empty quotation which im unable to replicate. I suspect that either the rest API is not the best or im missing something quite vital in building a request. See below for the actual ajax jquery request.
var request = $.ajax({
type: "POST",
url: urlBase,
contentType: 'application/json',
data: JSON.stringify({json}),
});
request.done(function (msg) {
alert(msg);
$("#log").html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
Error message based on the above request
Invalid field groups: [json] used in the search fields not found in duplicate store schema
You can create a json like this:
var obj = {
"": [{
"NAME": "NAME"
},
{
"ADDRESS": "ADDRESS"
},
{
"EMAIL": "EMAIL"
}
]
}
console.log(obj)
Hope it helps. Revert for any doubts.

JSONP callback is returning error

I'm trying to learn JSONP. From my research online, I understood that it's invoke function with callback.Apart from that everything else (the way data is handled/data format) similar to JSON?
I'm just playing with JSONP as below. But It's returning error, please explain in detail about it, please..
Script.js
function test(){
jQuery.ajax({
url: "/plugins/system/chat/jsonstr.php",
dataType: "jsonp",
jsonpCallback: "logResults"
});
jsonstr.php
logResults(){
$arr = '[{
"title": "keren",
"picture": "http://something.png",
"id":1
}, {
"title": "diana",
"picture": "/plugins/system/conversekit/conversekit/images/avatar.png",
"id": 2
}]';
echo $arr;
}
I expect this call to return json object so that I can manipulate it in success function of test. But error as below is thrown:
<br />
<b>Parse error</b>: syntax error, unexpected '{' in <b>C:\projects\easysocial.com\plugins\system\conversekit
\jsonstr.php</b> on line <b>14</b><br />
The url in console is as this:
GET http://mysite.localhost.com/plugins/system/chat/jsonstr.php?callback=logResults
logResults() is JavaScript callback, not PHP function. jsonstr.php should only return valid JSON.
So jsonstr.php should look like this
<?php
$arr = [
[
'title' => "keren",
'picture' => "http://something.png",
'id' => 1,
],
[
'title' => "diana",
'picture' => "/plugins/system/conversekit/conversekit/images/avatar.png",
'id' => 2,
],
];
echo(json_encode($arr));
And Script.js
function logResults() {
console.log('ajax done');
}
function test(){
jQuery.ajax({
url: "/plugins/system/chat/jsonstr.php",
dataType: "jsonp",
jsonpCallback: logResults
});
}
Two issues:
Your server-side script doesn't return anything, as the Net pane in your browser developer tools should reveal.
JSONP is just a dirty trick to avoid cross-site permission issues in AJAX, not a way to make PHP code interact with JavaScript (something that is not possible). So when you say "I want a callback function called logResults" you mean a JavaScript function.
If you want to use JSONP you need:
Make your server actually return JSONP (not even JSON):
$callback = filter_INPUT(INPUT_GET, 'callback');
// ...
echo sprintf('%s(%s);', $callback, $json);
Define a JavaScript function to process the returned data:
function logResults (data) {
alert(data[0].title);
}
This way you basically get a dynamically generated good old <script> tag that loads a simple script:
logResults([{
"title": "keren",
"picture": "http://something.png",
"id":1
}, {
"title": "diana",
"picture": "/plugins/system/conversekit/conversekit/images/avatar.png",
"id": 2
}]);
But since you are making an AJAX call in your own domain:
url: "/plugins/system/chat/jsonstr.php",
^^
No "http://example.com/` prefix pointing to a third-party site
... you don't need JSONP at all: plain JSON will be enough.

How can I get response from webservice in jquery?

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

MediaWiki JSON Api always returning "undefined"

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.

Categories