How can I parse JSON using the data parameter in JQuery? - javascript

I am making a web application using Jersey and JQuery for client-side.
I have the following URL that returns a JSON string:
http://localhost:8080/messenger/webapi/messages/1
returns:
{"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"}
when typed into the browser.
Now I am attempting to get this data client-side using the following JQuery functions:
var rootURL = "http://localhost:8080/messenger/webapi/messages";
$(function() {
$('#btnRegister').click(function() {
var username = $('#username').val();
addMessage();
});
function addMessage() {
var url = rootURL;
$.ajax({
type: 'GET',
url: rootURL +"/1",
dataType: "json", // data type of response
success: (function(data) {
var obj = jQuery.parseJSON(data);
alert('ID: ' + obj.id);
})
});
}
});
EDIT: When the "btnRegister" is pressed nothing is displayed at all
which just doesn't make sense to me.

There is some unwanted $ wrapping in success callback function, also there is no need to parse the response as you set dataType:'json'. For better understanding of $.ajax() read documentation here.
$(function() {
$('#btnRegister').click(function() {
var username = $('#username').val();
addMessage();
});
function addMessage() {
var url = rootURL;
$.ajax({
type: 'GET',
url: rootURL + "/1",
dataType: "json", // data type of response
success: function(data) {
//----^----------- remove the $ sign
alert('ID: ' + data);
}
});
}
});
You can access the value using obj.prop or obj['prop']
var obj= {"author":"Joe","created":"2015-07-28T22:33:34.667","id":1,"message":"Hello World"};
alert(obj.author);
alert(obj['author']);

Related

How to read data using JSONP, Ajax and jquery?

I am trying to read data from this API, but it is not working, I have an input box where I enter the isbn number and then get the data, using jsonp. Could you possibly help me in identifying where my error("Cannot read property 'title' of undefined") is?
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(isbn){
var infoUrl = isbn.info_url;
var thumbnailUrl = isbn.thumbnail_url;
var title = isbn.details.title;
var publishers = isbn.details.publishers;
var isbn13 = isbn.details.isbn_13;
console.log(isbn.info_url);
}
});
}
Open Library's API expects bibkeys to be prefixed with their type and a colon, rather than just the number alone:
function add(){
var isbn = 'ISBN:' + $("#isbn").val();
// ...
The colon also means the value should be URL-encoded, which jQuery can do for you:
$.ajax({
url: "https://openlibrary.org/api/books?jscmd=details&callback=?",
data: { bidkeys: isbn },
dataType: "jsonp",
Then, the data it returns reuses the bibkeys you provided as properties:
{ "ISBN:0123456789": { "info_url": ..., "details": { ... }, ... } }
To access the book's information, you'll have to first access this property:
success: function(data){
var bookInfo = data[isbn];
console.log(bookInfo.details.title);
// etc.
}
Example: https://jsfiddle.net/3p6s7051/
You can also retrieve the bibkey from the object itself using Object.keys():
success: function (data) {
var bibkey = Object.keys(data)[0];
var bookInfo = data[bibkey];
console.log(bookInfo.details.title);
// ...
}
Note: You can use this to validate, since the request can be technically successful and not include any book information (i.e. no matches found):
success: function (data) {
var bibkeys = Object.keys(data);
if (bibkeys.length === 0)
return showError('No books were found with the ISBN provided.');
// ...
Example: https://jsfiddle.net/q0aqys87/
I asked a professor, and this is how she told me to solve it:
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(data){
var thumb=data["ISBN:"+isbn+""].thumbnail_url;
....
}
});
}

Having trouble getting JSON data from database with AJAX

So as the title suggests, I am having difficulty retrieving data from my database with these technologies. This is my current situation:
var username = $('#username').val();
var password = $('#password').val();
// For the sake of example this is a dummy IP
var url = 'http://55.55.55.55/dbfuncts.php?action=getuser&user=' + username;
// For debugging purposes I compare this object with the one I get with the ajax function
var obj1 = {
"name" : "Dave"
};
var obj = $.ajax({
url: url,
type: 'POST',
dataType: 'json'
});
The format of my JSON is supposed to be like this:
{"UserID":"User","Password":"User","Email":"User#questionmark.com","Fname":"Web","Lname":"User","isManager":"0"}
When I go to the URL I am able to see this JSON string in my browser.
Currently when debugging, I find that I keep getting the jqXHR object instead of the json object that I want.
How do I retrieve the information as a JSON from the database?
I don't think jQuery ajax call will return the result directly as you did (but I'm not sure).
I used to get result from ajax call by using callback function as below.
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
success: function(data) {
// data argument is the result you want
console.log(data);
}
});
Try this:
Place the url which gives the json data in the url column.
var jsonData = $.ajax({
url: '*',
dataType:"json",
async: false
}).responseText;
var parsed = JSON.parse(jsonData);
If this does not then try this:
var jsonData1 = $.ajax({
xhrFields: { withCredentials: true },
type:'GET',
url: '*',
dataType:"json",
crossDomain: true,
async: false
}).responseText;
var parsed1 = JSON.parse(jsonData1);
TRY 2:
Ok so try it with Spring MVC. Get the data from the database, and keep it in a url. As given in this link. Ckick Here And then use the above ajax call to access the data from the url.

Ruby on Rails: Get json from controller in Javascript file

in my controller I've some json:
votes_controller.rb:
def create
...
vote_status = current_user.user_votes.pluck(:recipient_uid).include?(#user.uid)
render json: vote_status
end
I need to get vote_status in javascript file
votes.js:
jQuery(function($) {
$(".doWant").click( function () {
var status = vote_status.evalJSON();
var uid = $(this).parents("#dialog")[0];
var username = $(this).parents("#dialog")[0];
if(confirm("Are you sure?")) {
$.ajax({
url: '/votes' + "?uid=" + $(uid).attr("data-user-uid") + "&username=" + $(username).attr("data-user-username"),
type: 'POST',
success: function(data) {
console.log(data)
}
});
};
});
});
But there is an error Uncaught ReferenceError: vote_status is not defined. What am I doing wrong?
Thanks!
You're not defining this variable:
var status = vote_status.evalJSON();
You must define that variable.
It seems likely that you intended for that code to go into the success function, which returns the data from the ajax call as the first argument in that function:
success: function(data) {
console.log(data)
}
The vote_status is returned in success json callback, init the status there
$.ajax({
url: '/votes' + "?uid=" + $(uid).attr("data-user-uid") + "&username=" + $(username).attr("data-user-username"),
type: 'POST',
success: function(data) {
var status = JSON.parse(data);
}
});

Using $.ajax to return HTML & turn it into JavaScript array

var urlArray = window.location.pathname.split("/"),
idFromUrl = urlArray[2],
dataPath = "/bulletins/" + idFromUrl + "/data";
$.ajax({
url: dataPath,
type: "get",
dataType: "html",
success: function (data) {
var dataObj = data.replace(/"/g, '"');
console.log(dataObj);
}
});
I'm grabbing the contents of an HTML page, and the contents on that page is super simple. It's just an "array", although it's plain text so when it returns, JavaScript is treating it as a string instead of an array. This is all that's on that HTML page:
[{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]
Without replace the "'s, a console.log spits out [{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]
So my question is, how can I turn that HTML string (that's already in "array" form) into an actual array?
You can use JSON.parse
JSON.parse(dataObj);
You can parse the returned HTML fragment as JSON:
JSON.parse(dataObj);
Change "dataType" to "json" and it will convert it for you:
var urlArray = window.location.pathname.split("/"),
idFromUrl = urlArray[2],
dataPath = "/bulletins/" + idFromUrl + "/data";
$.ajax({
url: dataPath,
type: "get",
dataType: "json",
success: function (data) {
console.log(data);
}
});
If it is returning the " instead of ", then I would change the AJAX return page to make sure it is doing a proper JSON response.

Ajax post - POST array is returning empty on server side

I have an js function that is collecting data and sending it to a php file.
I am trying to submit an array as part of the post:
function send_registration_data(){
var string = "{username : " + $('#username').val() + ", password : " + $('#pass1').val() + ", level : " + $("#userrole").val() + ", 'property[]' : [";
var c = 0;
$('input[name=property]:checked').each(function(){
if( c == 0){
string +="\"" +this.value+"\"";
c=1;
} else {
string +=",\""+this.value+"\"";
}
});
string+="]}";
$('#input').html( JSON.stringify(eval("(" + string + ")")) );
$.ajax({ url: './php/submit_registration.php',
//data: { username : $('#username').val() , password : $('#pass1').val() , email : $('#email').val() , level : $("#userrole").val() },
data: JSON.stringify(eval("(" + string + ")")) ,
type: 'post',
success: function(output) {
$('#output').html( output );
}
});
};
On submit my php file returns an the POST array as NULL. I am not sure what I am doing wrong here.
EDIT: IT is the same weather I try to convert the string to json or not.
ALso, the inputs contain just text names.
string keyword
Do not use the "string" keyword.
eval
Eval is evil - use it with caution.
strict mode
Make sure always to work in the "strict mode" by placing this line at the beginning of your code:
'use strict'
Building your response object
You do not have to glue your post object manually. Just do it this way:
var post = {
'username': $('#username').val(),
'password': $('#password').val(),
'myArray[]': ['item1', 'item2', 'item3']
};
jQuery the right way
Avoid messing up with unnecessary syntax.
$.post(url, post)
.done(function(response){
// your callback
});
Conclusion
'use strict'
var url = './php/submit_registration.php'; // try to use an absolute url
var properties = {};
$('input[name="property"]:checked').each(function() {
properties.push(this.value);
});
var data = {
'username': $('#username').val(),
'password': $('#pass1').val(),
'level': $('#userrole').val(),
'property[]': properties
};
// submitting this way
$.post(url, data)
.done(function(response) {
// continue
})
.fail(function(response) {
// handle error
});
// or this way
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(data), // you'll have to change "property[]" to "property"
contentType: "application/json",
dataType: 'json',
success: function(response) {
// continue
}
});
You need to get from php://input if you are not using multipart/form-data, so, application/json
$myData = file_get_contents('php://input');
$decoded = json_decode($myData);
If you're sending this up as json, your $_POST variable will continue to be NULL unless you do this.

Categories

Resources