Issuing http get request and accessing the data I'm getting - javascript

In my app, I'm issuing get request to retrieve JSON from my server.
$http.get('http://localhost:3000/documents/2.json')
.success(
function(success){
console.log("Success");
})
.error(
function(error){
console.log("error has occurred")
});
Right now, I do successfully get 200 response, but I'm not sure how to access the json file I'm getting from the URL in my web app. I assume there's gotta be something like function(JSONData) but not sure how to implement it in my function above.
I'm issuing this in client side(Written in Angular) and getting the data from the server(written in Rails). My front end (in Angular) is part of Rails app now.

MAJOR EDIT:
This is the version (1.4.9) that the OP is using.
In the AngularJS $http Documentation v1.4.9 you get a sample script of what you are trying to do.
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

inside succes call back write
console.log(success)
so your code must look like this
$http.get('http://localhost:3000/documents/2.json')
.success(
function(success){
console.log("Success");
console.log(success);
})
.error(
function(error){
console.log("error has occurred")
});
parameter(success) in function is data, that you receive from server,
instear of success you can write anything you want .. usually i write data .. so in my case it will be function (data)

Related

Ajax request works on local server but not online

I have built my first website and it works on local server but not online. The problem is loading a json file with Ajax. In the published version I get the error message that my object is undefined.
This is a (simplified) version of my code that shows the problem:
$.ajax({
url: "json/torp.json",
contentType: "application/json",
success: function (data) {
torp = data;
console.log('great success!');
console.log(torp.items[3]);
},
error: function (/* request, error */) {
console.log('Network error has occurred please try again!');
}
This is the message in the console when running on local server:
great success! main.js:37:13
Object { id: "brunskar", title: "<h2>Brunskär</h2>", image: "img/countryside.jpg" }
But when I publish online this is what I get:
great success! main.js:37:13
TypeError: torp.items is undefined
In the Utilities Net section I get status code 200 and the whole content of the JSON file is readable under the "reply" tab, so it seems like the file is loaded. But I don't understand why my object is undefined.
Sounds like an asynchronous issue (your page is loading before your ajax call can return the data, therefor it is returned as undefined) one way to solve this is to put a function inside your ajax call that fires your page functions that use the data being returned by the call.
$.ajax({
url: "json/torp.json",
contentType: "application/json",
success: function (data) {
torp = data;
console.log('great success!');
console.log(torp.items[3]);
function usePageData (); <----calls webpage function utilizing
data
},
error: function (/* request, error */) {
console.log('Network error has occurred please try again!');
}
Hope that helps!
Problem solved by changing
contentType: "application/json"
to
dataType: "json"!
I used the tip from Patrick Evans in one of the comments. Thank you for the help!

Getting "parsererror" in jquery ajax

Below is my AJAX code. Here I'm hitting a service with one value. The service is getting called successfully, but it is not going into the success method. It is going into the error method only. In the error method it is giving parsererror and message: Unexpected token S
$.ajax({
type: 'GET',
url: 'http://domin.com:9000/ramsweb/rest/DetailRest/addOrderContacts/123456/' + customerId,
success: function (data, status, xhr) {
console.log(data);
$("#loadingSpinner").hide();
},
error: function (jqXhr, textStatus, errorMessage) {
$('.ErrorMsg').html('<h5>An error has occurred</h5>');
},
fail: function (data) {
$('.ErrorMsg').html('<h5>data loading failed</h5>');
}
});
jQuery AJAX functions by default will try to detect the type of response depending on other pieces of data in your request and response (headers etc.)
Most likely, your endpoint serves it as JSON thus telling jQuery to internally do a JSON.parse. However, your endpoint may be serving an error page instead of JSON which can cause parse errors like this.

Sending a json object using ajax to a servlet and receiving a response json object

I'm trying to send a json object using ajax to a servlet. The object is to be changed and sent back to the client. This is the code I used to send the json object from client to server.
function sendJson(jsonObj)
{
var parsed = JSON.parse(jsonObj);
$.ajax({
type: 'get',
url: 'GameLogic',
dataType: 'JSON',
data: {
loadProds: 1,
parsed: JSON.stringify(parsed)
},
success: function(data) {
},
error: function(data) {
alert('fail');
}
});
}
I only have a basic knowledge of javascript. As I understand this piece of code just sends a json object to a servlet. When receiving the response from the servlet, how do I get it? I searched for this and found functions similar to above function to receive response. I don't understand what this success: function(data) part does.
Can someone explain me the way to send a json object and receive the response to and from a servlet.
When I send a json object to the servlet, is there any way I can know whether it is received by the servlet, other than sending the object back as the response.
Ver simply, the answer is already in your code.
The ajax method of jquery has to callback methos for success and error.
Both are already impl. in your example but doing nothing!!
Here your code with comments pointing to the callback impl.
{
var parsed = JSON.parse(jsonObj);
$.ajax({
type: 'get',
url: 'GameLogic',
dataType: 'JSON',
data: {
loadProds: 1,
parsed: JSON.stringify(parsed)
},
success: function(data) {
// PROCESS your RESPONSE here!!! It is in "data"!!!!
},
error: function(data) {
// This is called when the request failed, what happend is in the "data"!!!
alert('fail');
}
});
}
Impl. something in the success callback and debug it with your browser dev tools to see what's inside of "data".
As you changed your question more about how to handle the communication in general and how to know if your request was received. Here my normal approach.
First I define an envenlope for every request and response which is always the same. It can look like this:
{
status: OK | ERROR,
message: "possible error message etc."
data: JSON Object representing the payload.
}
After doing this I can impl. a generic logic to send and receive message between server and client and every side nows how to handle the envelope. To make sure a message is received, could be processed etc.
Then you have this:
Make an ajax call to your server.
2a. If there is topoligical problem your error callback on client side is called. Request failed, server not reachable!
2b. The message was received by the server. The server can now process the payload regarding the URL used to call the server. The server method succeed it will write an OK in the envelop and his possible result in "data" as payload. If the method fails, it sets "status" to "ERROR" and provides an proper message, data is empty.
The client receives data on the success callback and it can inteprete the "status" field if it's a usefull response or if it's an error.
Hope that helps
The success:function() part goes like this
A function to be called if the request succeeds. The function gets passed three arguments:
The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified
a string describing the status
the jqXHR (jQuery-XHR) object
What this means is - if your ajax request was successful, the server will return you some response, ie, the data. This "data" can be used in the function.
$.ajax({
...
success: function(data) {
// process the "data" variable
console.log("SERVER RESPONSE");
console.log(data);
}
});

how to get json string from angular $http post request

I am sending this POST, I want to see the string that get's sent in the request before I send it.
Here's Plunker
$http.post('/someUrl', {msg:'hello word!'}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I guess what I am trying to do is see the JSON string being sent to the server.
if you are hitting the url with config option like this
var config = {
headers: { 'Content-type': 'application/json' },
'dataType': 'json'
};
var data = {
name: 'intekhab',
age:26,
};
$http.post('/admin/header', data, config).then(function(response){
console.log(response);
});
Then you can see the data what are send. Open your browser console and click network then under network click your url what you have hit
And now see the look at Request Payload under header tab
There your data will be revealing what you have send to server.
And if you are not using config option like this
var data = {
name: 'intekhab',
age:26,
};
$http.post('/admin/header', data).then(function(response){
console.log(response);
});
Then do the same as above only difference is where you have seen the data under Request Payload, now you will see the same data under Form Data
From what I understand, I think you want different handlers if the request succeeds or fails. You can do it in this way:
$http.post('/someUrl', {msg:'hello word!'}).
success(function(response) {
// this callback will be called asynchronously
// when it succeeds
}).error(function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

AJAX request in React JS js doesn't work

I'm trying to get info from my database via an AJAX request, but the success event isn't triggered.
The AJAX request is however received by the server, as it trigger the correct console log in the terminal.
I'm building it in Node, using the Express framework.
Here is the code for triggering the AJAX call. The 'componentDidMount triggered' is logged to the console. But then it stops. Neither the console.log in 'success' or 'error' is triggered, even though I know that the server has receenter code hereived an AJAX request.
app.get('/api/:name', function (req,res){
name = req.params.name;
Member.findOne({username: name}, function(err,member){
res.setHeader('Content-Type', 'application/json');
res.write(member.toString());
console.log('member fetched from DB: ', member);
res.end();
});
});
I'm not getting any other errors either, so I have no idea why this isn't working.
Can anybody please help?
UPDATE: Thanks for the help. I'm one step closer now. I did not realise I needed 'res.end' when serving the AJAX request. When I changed this, I've managed to get a response, though it's an error.
Her is the server side code:
app.get('/api/:name', function (req,res){
name = req.params.name;
Member.findOne({username: name}, function(err,member){
res.setHeader('Content-Type', 'application/json');
res.write(member.toString());
console.log('member fetched from DB: ', member);
res.end();
});
});
Tangential to your question, but equally important as figuring out why .success isn't being called: your code is not calling Main's setState in the success handler, because the success function isn't called "in your component" but "by jQuery, somewhere".
If you want to call setState on your component as part of the success handling, either cache the component and then call component functions on that:
var self = this;
$.ajax({
...
success: function() {
self.setState({ ... });
}
...
or use the JavaScript bind function (unrelated to jQuery.bind) to explicitly set the execution context for the success function to be your component:
...
success: function(data) {
console.log('success')
this.setState({data: data});
}.bind(this),
...
My mistake was in the res.write(member.toString()). I had to change it to res.write(JSON.stringify(member)), as the client was asking for a JSON file.

Categories

Resources