I am not able to view the JSON response from the server on my HTML page. Request is sent to server once the user clicks on the button. By making an API call from AJAX in javascript, I am trying to display the response.
Here is my html page:
This is the response which I get using POSTMAN:
{
"status": 1,
"success_Result": {
"names": [
{
"id": 1,
"name": "text1"
},
{
"id": 4,
"name": "text2"
},
{
"id": 5,
"name": "text3"
}
]
}
}
This is my javascript:
$("#search").click(function()
{
$.ajax(
{
type: "GET",
url: "http://localhost:8080/********/1/1/1?start_date=2017-02-10",
async:true,
dataType : 'jsonp',
crossDomain:true,
contentType: "application/json; charset=utf-8",
headers:
{
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'x-requested-with'
},
success: function(result)
{
try
{
console.log(JSON.stringify(result));
alert(result);
//$("#display").html(result);
}
catch (error)
{
alert("error found");
}
},
error: function(xhr, status, err)
{
console.log(err.message);
}
});
});
Firebug: console
I can view the response here by clicking on the arrow.
I tried using datatype: "json" in javascript. and I got this in the console. And nothing i could see in the HTML page.
$("#search").click(function()
{
$.ajax(
{
type: "GET",
url: "http://localhost:8080/*******/1/1/1?start_date=2017-02-10",
async:true,
dataType : 'json',
crossDomain:true,
contentType: "application/json; charset=utf-8",
success: function(result)
{
try
{
console.log(JSON.stringify(result));
alert(result);
//$("#display").html(result);
}
catch (error)
{
alert("error found");
}
},
error: function(xhr, status, err)
{
console.log(err.message);
}
});
});
console:
I tried other possible ways too....
// using XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8080/*******/1/1/1?start_date=2017-02-10", true);
xhr.onload = function ()
{
try
{
$("#display").html("hello");
console.log(xhr.responseText);
}
catch (ex)
{
alert('Error parsing response.');
}
};
try
{
xhr.send();
}
catch (ex)
{
alert(ex.message);
}
console:
Cross-origin resource sharing, Same origin policy error.
I don't know where i am going wrong. If anyone could help me out, it will be great. Please.
###########UPDATE###########
I tried this code now as per suggestions,
$.ajax(
{
type: "GET",
url: "http://localhost:8080/*******/1/1/1?start_date=2017-02-10",
dataType : 'json',
contentType: "application/json; charset=utf-8",
success: function(result)
{
try
{
console.log(JSON.stringify(result));
alert(JSON.stringify(result));
}
catch (error)
{
alert("error found");
}
},
error: function(xhr, status, err)
{
console.log(err.message);
}
});
I got this is my console:
Headers in above image has something to say about CORS ?? Is it enabled or disabled ?? How to check ??
Related
I am posting some JSON info using the code below. Currently, if it is successful (200 response) the alert pops up, but if it is unsuccessful nothing happens.
What I would like to do is basically say if successful do X, else do Y.
I have try using an if / else statement within the function, but it doesn't seem to work.
Apologies if this is a silly question, I am new to working with JSON, XHR etc. Any assistance would be greatly appreciated.
jQuery["postJSON"] = function(url, data, callback) {
if (jQuery.isFunction(data)) {
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: "POST",
crossDomain: true,
contentType: "application/json",
data: JSON.stringify(data),
success: callback
});
};
$.postJSON(
"https://test.com",
data,
function(data, status, xhr) {
alert("Success");
}
);
EDIT: Working Code:
jQuery["postJSON"] = function(url, data, callback) {
if (jQuery.isFunction(data)) {
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: "POST",
crossDomain: true,
contentType: "application/json",
data: JSON.stringify(data),
success: callback,
error: function(xhr, ajaxOptions, thrownError){
alert(thrownError);
});
};
$.postJSON(
"https://test.com",
data,
function(data, status, xhr) {
alert("Success");
}
);
add this line to your return jQuery.ajax({}) function:
error: function(xhr, ajaxOptions, thrownError){
window.alert(thrownError);
}
hope this helps~
var object={
"longDynamicLink": "https://[APP_NAME].page.link/?link=[LINK_HERE]",
"suffix":{
"option":"SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
dataType: "json",
data: object,
success: function(response, textStatus, jqXHR) {
alert(response.shortLink);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
The above code works if the "suffix" is deleted from the request. That makes an "UNGUESSABLE" url, but I want a short URL. As stated in the documentation at https://firebase.google.com/docs/dynamic-links/rest?authuser=0 I added the suffix option parameter, but it results with a 400 response. Any ideas why?
I haven't ever tried this but, ...
POST https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=api_key
var params = {
"longDynamicLink": "https://example.page.link/?link=http://www.example.com/&apn=com.example.android&ibi=com.example.ios",
"suffix": {
"option": "SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
data: jQuery.param(params) ,
contentType: "application/json",
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
I have the following javascript:
function foo()
{
var someObject = $("#someTextbox").val();
var contentType = 'application/x-www-form-urlencoded; charset=UTF-8;';
AjaxRequest(someObject, 'html', 'post', '/ErrorCheck/SaveToFile', contentType, function(response)
{
//stuff
}, function(error)
{ });
}
function AjaxRequest(data, dataType, type, url, contentType, success, error, args)
{
try
{
var useFD = false;
var form = new FormData();
if (type.toUpperCase() == 'POST')
{
if (contentType && contentType.indexOf('application/x-www-form-urlencoded; charset=UTF-8;') === 0)
{
form.append("MyData", JSON.stringify(data));
url = antiForgeryToken.add(url);
useFD = true;
}
}
$.ajax(
{
processData: useFD ? false : true,
mimeType: useFD ? "multipart/form-data" : "",
async: args.async,
cache: args.cache ? true : false,
data: useFD ? form : data,
dataType: dataType,
type: type,
url: url,
contentType: contentType,
traditional: true,
headers:
{
'__RequestVerificationToken': antiForgeryToken.token() != false ? antiForgeryToken.token().val() : '',
'__loginUserId': $('#hidLOGINUSERID').val()
},
beforeSend: function(request)
{ },
success: function(data, textStatus, XMLHttpRequest)
{
try
{
success(data, textStatus, XMLHttpRequest);
}
catch (e)
{}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {},
complete: function(XMLHttpRequest) {}
});
}
catch (err)
{}
}
In the above scenario, useFD is true.
Then in my ErrorCheck controller's SaveToFile method, I have the following:
public void SaveToFile()
{
try
{
if (Request.Form.Count > 0)
{
//do stuff
}
}
catch (Exception ex)
{
ElmahLogUtility.ErrorException(ex);
}
}
However, Request.Form.Count is always zero. I got this solution from a question I asked a few months ago here. I accepted the solution there back in October and I know this code was working, however it didn't get to a testing environment until just recently and it is no longer working, not even in my local environment.
What am I doing incorrectly?
I have a result from Fiddler (please see the attached image), how can I get the results where the arrow is pointing to?
This is what I have done so far and thank you:
function GetRefiners() {
$.ajax({
url: "myUrl",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function(data){
$.each(data.d.query, function(list){
});
},
error: function(error){
alert("Error message\n" + JSON.stringify(error));
}
}
);
}
Simply go to the results objects and iterates over it
function GetRefiners() {
$.ajax({
url: "myUrl",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function(data){
$.each(data.d.query.PrimaryQueryResult.RefinementResults.Refiners.results.Entries.results, function(list){
callWhatYouNeed();
}
};
},
error: function(error){
alert("Error message\n" + JSON.stringify(error));
}
}
);
}
Google Analytics v4 API was just released and GET requests were changed to POST requests. And there are no good examples out there yet...
So I've successfully received accessToken, but when I try the following POST request - I'm always getting empty object Object { }, but I'm sure that data is there and ViewID is correct!
Any advice helps! Thank you!
requestAnalyticsData1 = function (accessToken) {
var url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet?";
url += "access_token="+accessToken;
var params = {
"reportRequests":[{
"viewId":"121238102",
"dateRanges":[{
"startDate":"yesterday",
"endDate":"today"
}],
"metrics":[{
"expression":"ga:users"
}],
"dimensions": [{
"name":"ga:pagePath"
}]
}]
}
$.ajax({
url: url,
type: "POST",
data: params,
dataType: "json",
success: function(results) {
console.log(results)
parseAnalyticsReportsData(results);
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed');
alert(xhr.status);
alert(thrownError);
}
});
};
Solution was to replace this part:
data: params,
dataType: "json",
With this:
data: JSON.stringify(params),
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-Type", "application/json");
},