Reading data from JSON reply with JQuery - javascript

I've been having trouble accessing this piece of content in a json object. Here is my code for fetching data:
function getEntries(key){
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=ISBN:" + key + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
}
The reply I get looks like this:
How do I access the pointed object if the key is different for every search?

Try using
data["ISBN:"+key]
Where key is the key you are passing to the function

I think I found it after all...
function getEntries(key){
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=ISBN:" + key + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(data){
console.log(data["ISBN:"+key]);
}
});
}
did the trick.

Related

Ajax with JSON GET request undefined

I am trying to get the front end to display the contents of my dynamo db table although it displays the information as undefined.
$(document).ready(function(){
$.ajax({
type: 'GET',
url:someURL,
success: function(data){
$('#incidentid').html('');
data.forEach(function(IncidentNotesItem){
$('#incidentid').append ('<p>'+ IncidentNotesItem.incidentid + '</p>');
})
}
});
});
I solved it! The issue was that I wasn't calling the column name properly. I did console.log(IncidentNotesItem) to see what is stored inside the IncidentNotesItem Function and saw on the console that it is called id instead of incidentid.
$(document).ready(function(){
$.ajax({
type: 'GET',
url:someURL,
success: function(data){
$('#incidentid').html('');
data.forEach(function(IncidentNotesItem){
$('#incidentid').append ('<p>'+ IncidentNotesItem.id + '</p>');
})
}
});
});

Run if/else script with only part of a URL

I am trying to edit my Javascript to pull different data via an AJAX call based upon only part of a URL. Currently, my if/else script looks like this:
if (window.location.href=="london") {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data-london.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
} else {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
}
This doesn't work as currently written since if window.location.href=="london") is only part of the URL, not the full URL. Is there a way to edit this script to run only based off of the last bit of the page URL? For example: /london, /nw, etc.? Is there a better way to accomplish this task?
Instead of
if (window.location.href=="london") {
Use below code
var URL = window.location.href;
if(URL.indexOf("london") !== -1)
The .indexOf function will find out a substring is exist or not in a string. And in your case you wants "london" is exist or not in URL.
I assume you are asking, when the url something like 'https://example.com/london' , so you just want to include or get the value of london. below code will help to provide always last bit of value of the url.
window.location.pathname.splitOnLast('/')[1]
it will give you '/london'. or you can just check the existence of theondon in the url.
Firstly it is not necessary to use if else like above
You can use like below
var dataurl = document.URL
$.ajax({
url: 'somepage.php',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});
in somepage.php file you can process the data however you want based on the dataurl
And also in javascript you can do like below
var urlTopost="other.php";
if(document.url.indexOf("london")!==-1)
{
urlTopost="london.php";
}
$.ajax({
url: urlTopost,
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});

pass data($post) to php file using javascript without callback

I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);
as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.
var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});

append ajax result to div

I'm making an ajax call to the IMDb API to get the movie data for 'The Shawshank Redemption'. I want this data to be put in the div I created.
<div id="movie-data"></div>
My js code currently:
$(init);
function init() {
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").append(data);
}
});
It doesn't give any response. However, I can see the data in my console. When I append <p>Test</p> instead of data it does return 'Test' to the screen.
This is what I did. It seems to be working now. Thanks everyone.
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").append(JSON.stringify(data));
The following should work
$("#movie-data").html(data.Title);
because data will be in json format, like this:
{"Title":"Titanic","Year":"1997","Rated":"PG-13","Released":"19 Dec 1997","Runtime":"3 h 14 min","Genre":"Drama, Romance","Director":"James Cameron","Writer":"James Cameron","Actors":"Leonardo DiCaprio, Kate Winslet, Billy Zane, Kathy Bates","Plot":"A seventeen-year-old aristocrat, expecting to be married to a rich claimant by her mother, falls in love with a kind but poor artist aboard the luxurious, ill-fated R.M.S. Titanic.","Poster":"http://ia.media-imdb.com/images/M/MV5BMjExNzM0NDM0N15BMl5BanBnXkFtZTcwMzkxOTUwNw##._V1_SX300.jpg","imdbRating":"7.6","imdbVotes":"449,162","imdbID":"tt0120338","Type":"movie","Response":"True"}
Check these resources:
Using AJAX to Extract Data from IMDB API
http://99webtools.com/blog/php-get-movie-information-from-imdb/
Try like this. API is returning JSON values you need to get the values like mentioned below. Hope this helps you.
var content = 'Title : '+data.Title ;
content += ' Year : '+data.Year ;
content += ' Rated : '+data.Rated ;
content += ' Released : '+data.Released ;
$("#movie-data").append(content);
<div id="movie-data"></div>
function init() {
var html='';
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
for(var key in data) {
var value = data[key];
html+='<div>'+key+':'+value+'</div>'
}
$("#movie-data").append(html);
}
});
}
init();
working demo
the answer is:
function init() {
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").html($(data).append(data));
}
});
You could try to delete dataType: "json" from your ajax call
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").append(data);
}
});
You can try with JSON.stringify(data)
The code would be the following:
$(document).ready(function(){
$.ajax({
method:"get",
url:'{{ route('getnotificationcount') }}',
success:function(data){
console.log(data);
for(var key in data) {
var value = data[key];
html+='<div>'+key+':'+value+'</div>'
}
$("#notifyy").append(html);
}
});
});

How to make jQuery JSON request and use response data to change html element values?

I'm not good at JQuery at all, in fact this is my first encounter due to Shopify. In other words I'm completely lost.
This is what I was able to do so far.
function FindPlayer()
{
var playerid = $('input[id=playerId]').val();
var clubname = $('input[id=teamname]').val();
$("#searchBar").attr('data-user-input', value);
$.ajax({
url: "http://website.com/index.php?player=" + playerid + "&club=" + clubname,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response(data);
}
});
}
The json response is going to look like this:
[{"playerFound":"true","tradeid":"123456"}]
I want to then check if playerFound is true or false before setting this element:
<input id="tradeId" type="hidden" name="attributes[tradeid]" />
This is probably pretty basic for JQuery users but not for me any help would be appericiated.
Try This:-
$.ajax({
url: "http://website.com/index.php?player=" + playerid + "&club=" + clubname,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if(data[0].playerFound == "true")
{
$('#tradeId').val(data[0].tradeid);
}
}
});
Since content type is JSON you can simply use like this
success: function (data) {
if(data.playerFound == "true"){
$('#tradeId').attr('name',data.tradeid) // if you want to change name
$('#tradeId').val(data.tradeid)// if you want to change value
}
}

Categories

Resources