Can't select data attr when added with jquery - javascript

I am adding some data to data attr with jquery when click button
$(document).on('click','.musicButton',function(){
var genre = $('.musicPlay').last().data('genre');
var musicBox = $($('#musicBoxTemplate').html());
$(musicBox).appendTo('.allMusics');
$('.getData').last().data('music',genre);
}
Then I need when that data
$(document).on('click','.musicPlay',function(){
var data = $(this).data('genre');
var music = $('.getData[data-music=' + data + ']');
if( music.find(':first-child').attr('tagName').toLowerCase() == 'em'{
//Do some stuff
}
}
that alert me undefined. why it don't see that data when I need?

Related

How to make API request from HTML select tags?

I need help with this scenario, getting all data from multiple select tag
and use those data to send an API request.
I have these three select tags, and one button to send a request to a news API.
The user needs to select a value from those select tags to set data like "source" and "category".
Example: "https://xxxxxxxxxxxx.org/v2/top-headlines?source='+ source +' + '&category='+ cat +'&apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Not sure if this the efficient way.
Below is my js code.
//global variables
var apiUrl = 'https://xxxxxxxxxxxxxxxxxx',
apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxx',
displayRequest = document.querySelector('.displayRequestData'),
requestBtn = document.querySelector('#runApi'), //Btn to display data
newsOpt = document.querySelector('#news-selection'), //news select tag
catOpt = document.querySelector('#news-category'); //category select tag
requestBtn.addEventListener('click', newsRequest); //onclick
function sourceSelected() { //news option
var source = newsOpt !== null ? newsOpt.options[newsOpt.selectedIndex].value : 'the-next-web';
var cat = catOpt !== null ? catOpt.options[catOpt.selectedIndex].value : 'general';
return newsRequest(source, cat);
}
function newsRequest(source, cat) {
axios.get(apiUrl + 'top-headlines?sources=' + source + '&language=' + cat + '&apiKey=' + apiKey)
.then(function (response) {
var reStringify = JSON.stringify(response);
var rejson = JSON.parse(reStringify);
if (rejson.data.status == 'ok'){
console.log(rejson.data.articles[1].source.name);
//console.log(requestBtn);
}
})
.catch(function (error) {
console.log(error);
});
}
By the way, i got this error
VM7472:1 GET https://xxxxxxxxxxxxxxxxxxxxxxxx/v2/top-headlines?sources=[object%20MouseEvent]&language=undefined&apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxx 400 (Bad Request)
When you add the event listener to call newsRequest via onClick, the first and only parameter that will be sent to that function is the event object. Therefore, the parameters of source and cat are not passed to newsRequest when they click on the button. (This is why your resulting URL has the [object MouseEvent] in it)
Instead, you might want to call your sourceSelected function in the onClick event which is fetching the current field values and then calling the newsRequest function.
I play around with my code, it's working now.
Note: The news API I'm using not allowing me to mix some data like country, source and langauge. So I try things that only allowed for free account and it works.
requestBtn.addEventListener('click', sourceSelected); //onchange
function sourceSelected() { //news option
var source = newsOpt !== null ? newsOpt.options[newsOpt.selectedIndex].value : 'en';
var cat = catOpt !== null ? catOpt.options[catOpt.selectedIndex].value : 'general';
return newsRequest(source, cat);
} //end of sourceSelected
function newsRequest(source, cat) {
axios.get(apiUrl + 'top-headlines?country=' + source + '&category=' + cat + '&apiKey=' + apiKey)
.then(function (response) {
var reStringify = JSON.stringify(response);
var rejson = JSON.parse(reStringify);
if (rejson.data.status == 'ok') {
console.log(rejson.data.articles[1].source.name);
//console.log(requestBtn);
}
})
.catch(function (error) {
console.log(error);
});
}//newsRequest

New ajax calls not resetting the existing data in the JSP table

Below is my ajax function which retrieves the data from servelt and shows it fine in the jps and the problem is every time a new ajax calls is submit the form just appends the data into the results received from previous calls, I need reset the current values stored in the table OrderResultContainer and then display it with new data.
I tried
document.getElementById("OrderResultContainer").reset = ();
but it's just reset the entire form data and not showing any data in the page.
function addData() {
if(window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest();
var loading = document.getElementById("loading");
document.getElementById("loading").style.display = "";
document.getElementById("OrderResultContainer").style.display = "none";
xhttp.open("POST","Order",true);
var formData = new FormData(document.getElementById('orderform'));
xhttp.send(formData);
xhttp.onreadystatechange=function() {
if ((xhttp.readyState == 4) && (xhttp.status == 200)) {
var jsonorderdata = JSON.parse(xhttp.responseText);
txt = "";
for (x in jsonorderdata) {
txt += "<tr><td>" + jsonorderdata[x].ordernumber+"</td>""</tr>";
}
document.getElementById("loading").style.display = "none";
document.getElementById("ViewOrderResultContainer").innerHTML = document.getElementById("ViewOrderResultContainer").innerHTML + txt;
document.getElementById("divOrderResultContainer").style.display = "";
}
};
}else
console.log('Ajax call is failed');
}
Can anyone help me on how to reset the data in the table OrderResultContainer alone after a new ajax response received from servlet.
You append the received data to the previous with following code:
document.getElementById("ViewOrderResultContainer").innerHTML = document.getElementById("ViewOrderResultContainer").innerHTML + txt;
So if you change it like following you would have only new data:
document.getElementById("ViewOrderResultContainer").innerHTML = txt;
It is kind of hard to see without the corresponding html but this looks like the problem:
document.getElementById("ViewOrderResultContainer").innerHTML =
document.getElementById("ViewOrderResultContainer").innerHTML + txt;
Your taking the innerHtml from the ViewOrderResultContainer and append the value from txt. If you do that more than once than it will keep growing. If you want to replace the text than replace it with
document.getElementById("ViewOrderResultContainer").innerHTML = txt;
p.s. the given javascript is not valid
txt += "<tr><td>" + jsonorderdata[x].ordernumber+"</td>""</tr>";

How to get more data from json array when a value in option tag is selected jquery

I'm trying to display more info of the museum when a museum name is clicked fro the option dropdown box. I am getting my data from a json array. I was able to populate the option box with the name of the museum but could not display more details. Could anyone please help me with this. I'm using jquery for this code.
function getMuseums() {
var museumSelect = $("<select id=\"museumlist\" name=\"museumlist\" onChange=\"getMuseumInfo()\" />");
var info = $("<span>Select Museum: </span>")
$.get("museums.php",function(data,status) {
var response = '';
var json = $.parseJSON(data);
museums = json.museums;
$.each(museums, function (index, item) {
$('<option />').attr({"value" : index}).text(item.museum_name).appendTo(museumSelect);
/*response += "<option value='"+index+"'>" + item.museum_name + "</option>";
$("#museumlist").html(response);*/
});
$('#content').empty().append(info, museumSelect);
$("<div id=\"museumDetails\" />").appendTo("#MuseumDiv");
getMuseumInfo()
});
}
function getMuseumInfo() {
var museum_id = $("#museumlist").val();
selectedMuseumid = museum_id;
$("#MuseumDiv").empty().append("<div id=\"museumDetails\"/>");
var url = "museums.php?museum_id=" +escape(museum_id);
$.get(url,function(data,status) {
var json = $.parseJSON(data);
museums = json.museums;
var museum_name = museums.museum_name;
var museum_description = museums.museum_description;
var museumInfo = "<h3>" + museum_name + "</h3><p>" + museum_description + "</p>";
$("#museumDetails").empty().append(museumInfo);
});
}
You can pass option value to your function as a parameter getMuseumInfo(this.value):
var museumSelect = $("<select id=\"museumlist\" name=\"museumlist\" onChange=\"getMuseumInfo(this.value)\" />");
And than you can use iterate through museums and check if index is the same as option value, and then print only properties for that item.
$.each(museums, function(index, item) {
if (index == id) {
var museumInfo = "<h3>" + item.museum_name + "</h3><p>" + item.museum_description + "</p>";
$("#MuseumDiv").empty().append(museumInfo);
}
});
But better check working code (also turn on console in app):
codePen
NOTE:
I make example of request to create JSON data. I make get request to url:
https://api.myjson.com/bins/58j10

Spotify Api Results Ajax

In the image I have the code to display only the first element ( song, image , artist, etc ... ) .
I would like to know how to make it show me :
When a user clicks on that button, show a new modal with all the
results of the tracks search you performed previously.
When a user clicks on one of the track names, update the player with
that track's information, including its audio.
The button is already created.
$('#song_btn').on('click', function Search_Song (event) {
event.preventDefault();
var song = $('#song_input').val();
var request = $.get('https://api.spotify.com/v1/search?q=' + song +'&type=track');
function Data_Songs (song) {
var track = song.tracks.items[0];
$('.song_title').text(track.name);
$('.artist_name').text(track.artists[0].name);
var cover = '<img src="' + track.album.images[0].url + '">';
$('.cover_image').html(cover);
var audio = '<audio class="js-player" src="' + track.preview_url + '">';
$('.audio').html(audio);
var more_results = '<br/><button type="submit" class="btn btn-primary" id="more_btn">Ver más Resultados</button>';
$('.more_result').html(more_results);
};
function handle_Error () {
console.error('¡¡ Ha Fallado !!');
}
request.done(Data_Songs);
request.fail(handle_Error);
});
So it seems like you have button to trigger the event...Here are your next steps:
Take an input (through a text field for example) and search for it through the API.
Next, obtain the parsed JSON from the API.
Then you'll be able to do what you are doing in your Data_Songs function...
Here's my implementation:
$('#song_btn').on('click', function(){
var BASE_URL = 'https://api.spotify.com/v1/'
var QUERY = $('#search_field').val(); // This is the value of your text field
var spotify_json = $.get(BASE_URL + 'search?type=track&query=' + QUERY, function(data){
console.log(data.tracks); // Do whatever you want with them after here!
// Ex. alert(data.tracks[0].href);
})
})
Note that I used a success handler on the $.get() method, which is a little different from your code.
To use your Data_Songs function in the $.get() function,
var spotify_json = $.get(BASE_URL + 'search?type=track&query=' + QUERY, Data_Songs(data));

Know which Form is submitted

I have eight Forms in a page (Form0, Form1, Form2 and so on). When a form is submitted, data is handed by JS and send to ReassignPreg.php, which search data in DB and send it back with json. Then the proper divs on the page are updated.
The code below is doing its job. But I have eigh copies of almost the same code, one for each Form (I only copy two of them for brevity). Newbie and amateur as I am, I wander which would be the way for synthesize this code (get Form name, and then pass that to only one function).
<script type="text/javascript">
$(document).ready(function(){
$("#Form0").submit(function(){
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox00").html(imagen)
$("#PregBox01").html(obj.Clase)
$("#PregBox02").html(obj.Dificultad)
$("#PregBox03").html(obj.Tipo)
});
return false;
});
});
$(document).ready(function(){
$("#Form1").submit(function(){
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox10").html(imagen)
$("#PregBox11").html(obj.Clase)
$("#PregBox12").html(obj.Dificultad)
$("#PregBox13").html(obj.Tipo)
});
return false;
});
});
</script>
A little more modularity helps a lot
$(document).ready(function () {
$("[id^=Form]").on('submit', function (e) {
e.preventDefault();
var _form = this.id.slice(-1); // 0, 1, etc
var cadena = $(this).serialize() + '&form=' + _form;
$.get('ReassignPreg.php?cadena=' + cadena, function (row) {
var image = $('<img />', {
src : "../ImageFolder/" + row.File + ".png",
width : 530
});
$("#PregBox"+_form+"0").html(image);
$("#PregBox"+_form+"1").html(row.Clase);
$("#PregBox"+_form+"2").html(row.Dificultad);
$("#PregBox"+_form+"3").html(row.Tipo);
}, 'json');
});
});
now you'll have a form key on the server containing the number of the form, for instance in PHP you'd get that with $_GET['form'] etc.
you could add an hidden field to each form with an ID/name and use that to identify the form submitting
You may need to assing classes to your PregBox elements and then target them accordingly to the form's ID.
$('form').submit(function(){ // listen to all form submissions.
var formID = $(this).prop('id'); // get the form ID here and do what you like with it.
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox00").html(imagen)
$("#PregBox01").html(obj.Clase)
$("#PregBox02").html(obj.Dificultad)
$("#PregBox03").html(obj.Tipo)
});
return false;
});

Categories

Resources