I've looked up a lot of examples and none really answered my question. I'm trying to iterate through a JSON file and add certain items to divs on my page.
Here's the code I've written so far. This code returns all the item values of all objects into the different divs instead of appending each item to its div. You can ignore the first for loop, it's just for adding id's to each div. I've also created an example fiddle.
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/kraken/streams',
dataType: 'json',
success: function(data) {
console.log(data);
var name = document.getElementsByClassName("player-name");
var gamename = document.getElementsByClassName("gamename");
var viewcount = document.getElementsByClassName("viewcount");
var date = document.getElementsByClassName("date");
var numItems = $('.stream').length;
var i = 1;
$('.stream').each(function(i) {
$(this).attr('id', (i + 1));
i++;
});
$('.stream').each(function(i, obj) {
$.each(data.streams,function(index,item) {
$(name).append(item.channel.name);
$(gamename).append(item.channel.game);
$(viewcount).append(item.viewers);
$(date).append(item.created_at);
});
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
var name = $(".player-name"); // jQuery's $ cares about your fingers
var gamename = $(".gamename");
var viewcount = $(".viewcount");
var date = $(".date");
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/kraken/streams',
dataType: 'json',
success: function(data) {
console.log(data);
$.each(data.streams,function(index,item) {
// now use .eq(index) over your elements collections
name.eq(index).append(item.channel.name);
gamename.eq(index).append(item.channel.game);
viewcount.eq(index).append(item.viewers);
date.eq(index).append(item.created_at);
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
Related
I am attempting use a variable that I create through data being sent from php in one ajax function in a another ajax function. I'm not sure what I am doing wrong. I tried creating making this a global variable by doing var nameOutput and also tried var nameOutput = 0. You will see alert code in the second ajax function. This is outputting nothing. If I remove the .val(), I receive object Object.
The code in question is in the second Ajax function: data: {
'nameOutput': nameOutput.val()
}
Does anyone have any idea what I have to do?
var nameOutput;
$('#shuffle').on('click', function() {
$.ajax({
url: 'php/name-selection.php',
type: 'POST',
success: function(data) {
nameOutput = $('#name-output').html(data);
$(nameOutput).html();
},
complete:function(){
$('#send-info').slideDown(1500);
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
});
//var datastring1 = $('#name-output').serialize();
$('.check').click(function() {
alert(nameOutput.val());
$.ajax({
url: 'php/name-selection-send.php',
type: 'POST',
data: {
'nameOutput': nameOutput.val()
}
,
success: function(data) {
if (data == 'Error!') {
alert('Unable to submit inquiry!');
alert(data);
} else {
$('#success-sent').html(data);
}
},
complete:function(){
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
if you can set inner html of nameOutput using .html('blah') , so you can extract the html again using nameOutput.html() not nameOutput.val();
however I think you have to define the element like this to be a HTML element:
var nameOutput=$('<div></div>');
also in first ajax function,set the html using this:
nameOutput.html(data);
and if there is a real element with ID name-output , and you want the result to be visible, do both of these:
nameOutput.html(data);
$('#name-output').html(data);
I have the following js/jquery code:
var trigger = $('#loadTableData');
var wrapperClass = 'tableAccordionWrapper';
var url = 'data/tableData.json';
var template = 'includes/tableInput.html';
var parentWrapper = $('#selectedTables .sub-content .input-controls');
var href;
var intID;
var items;
var i;
// retrieve node data send from exteral source
addExternalTableInput = function(){
$('.tableAccordionWrapper').remove();
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success:function(data){
items = data.items
for(i in items){ // this loops 3 times
addExternalTemplate();
}
},
error:function(status){
console.log(status, "Something went wrong");
},
complete:function(){
}
});
}
// append table input to document
addExternalTemplate = function(){
var wrapper;
$.ajax({
type: 'GET',
url: template,
dataType: 'html',
success:function(data){
intID = i;
wrapper = $('<li/>');
wrapper.addClass(wrapperClass);
wrapper.attr('data-id','table-' +intID);
href = $('<a href="#"/>');
wrapper.append(href);
wrapper.append(data).insertBefore(parentWrapper);
var anchor = wrapper.find('> a');
anchor.html(items[intID].tableName); // this returns 'DB_SOURCE_3' for all 3 templates added to the DOM
},
error:function(status){
console.log(status, "Something went wrong");
},
complete:function(){
}
});
}
The concept is that I am using a small json file to run another ajax request. The length of the data in the json file determines how many times the consecutive function should be fired.
The json contains very basic data, but as I loop through it I want the second ajax function to append a template of html to the document (at which point I want to be able to run other functions). One part of data from the json file needs to be injected into the template as it is iterating through the loop.
It appears that the loop works in that in this example the html template gets appended to the dom 3 times, but it passes the last table name in the json to each template that is added to the dom. The second function appears to run after the loop has finished.
Example JSON:
{
"items":[
{
"tableName": "DB_SOURCE_1",
"tableID" : "14739",
"tableDescription" : "Main customer table"
},
{
"tableName": "DB_SOURCE_2",
"tableID" : "184889",
"tableDescription" : "Partitions table"
},
{
"tableName": "DB_SOURCE_3",
"tableID" : "9441093",
"tableDescription" : "Loans Table"
}
]
}
I have tried passing the function in the ajax complete function.
I have also tried to trigger the second ajax function inside the first ajax success function like so:
addExternalTableInput = function(){
$('.tableAccordionWrapper').remove();
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success:function(data){
items = data.items
for(i in items){
$.ajax({
type: 'GET',
url: template,
dataType: 'html',
success:function(data){
intID = i;
wrapper = $('<li/>');
wrapper.addClass(wrapperClass);
wrapper.attr('data-id','table-' +intID);
href = $('<a href="#"/>');
wrapper.append(href);
wrapper.append(data).insertBefore(parentWrapper);
var anchor = wrapper.find('> a');
anchor.html(items[intID].tableName);
},
error:function(status){
console.log(status, "Something went wrong");
},
complete:function(){
}
});
}
},
But everything I have tried seems to return the same results.
The code has been rewritten somewhat, but here is what I am doing.
var templateData;
addExternalTableInput = function(){
$('.tableAccordionWrapper').remove();
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success:function(data){
var items = data.items;
for(var i in items){
addExternalTemplate(items[i], i); // pass parameters to this function
}
},
error:function(status){
// etc.
}
});
}
addExternalTemplate = function(item, intID){ // add parameters to our function so we can access the same data
var wrapper;
// load template data once
if(!templateData){ // only run this function if !templateData (should only run once).
$.ajax({
type: 'GET',
url: template,
dataType: 'html',
async: false, // wait until we have a response before progressing
success:function(data){
templateData = data;
},
error:function(status){
console.log(status, "Something went wrong");
}
});
}
// append templateData to the dom
if(templateData){
var href = $('<a href="#"/>');
var tableNameInput = wrapper.find('[name="tables"]');
tableNameInput.val(item.tableName);
// etc
}
// update for, id and name attributes etc.
updateInputAttributes = function(){
// do other stuff to each instance of the template
}();
}
I have moved alot of the global variables out and instead I am using function parameters.
I am only calling the html template once, but for each iteration of the loop I can run functions to update certain atrributes in that instance of the template as well as match items in the json to items in the template.
I have a problem with jQuery calling an AJAX function, basically everytime a user changes a select box, I want it to call the getSubCategories function, but for some reason, nothing is happening. Any ideas?
If I load the page and add console.log inside the getSubCategories function it logs it, should that even be happening?
function getSubCategories() {
var id = $("#category").prop('selectedIndex');
var selectedCategory = $("#category").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfCategory = convertToSlug(selectedCategory);
id++;
console.log('here');
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_subcategories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#sub_category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#sub_category").append('<option value="' + this.body + '">' + this.body + '</option>'); //add the sub categories to the options
});
$("#category_slug").attr('value', slugOfCategory);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function getCategories() {
var id = $("#type").prop('selectedIndex');
var selectedType = $("#type").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfType = convertToSlug(selectedType);
console.log(slugOfType);
//add one to the ID because indexes dont start at 0 as the id on the model
id++;
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_categories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#category").append('<option value="' + this.name + '">' + this.name + '</option>'); //add the sub categories to the options
});
$("#type_slug").attr('value', slugOfType);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
}
$(document).ready(function() {
var firstCatgegory = $("#category").val();
var slugOfFirstCategory = convertToSlug(firstCatgegory);
$("#category_slug").attr('value', slugOfFirstCategory);
var firstType = $("#type").val();
var slugOfFirstType = convertToSlug(firstType);
$("#type_slug").attr('value', slugOfFirstType);
$("#type").change(getCategories());
$("#category").change(getSubCategories());
});
Thanks for any help. (Sorry the code is a little messy, i've just been trying to get it to work so far)
This is due to the fact that the ajax call you are trying to make is asynchronous. When you call getSubCategories() it returns undefined which is why your code is not working.
To make this work you need to put your code within the success callback function instead.
<script>
function getSubCategories()
{
var id= $("#category").prop('selectedIndex');
$.ajax({
method: 'GET',
url: '/product/get_subcategories',
data: {'id' : id},
success: function(response){
// DO SOMETHING HERE
},
error: function(jqXHR, textStatus, errorThrown) { }
});
}
$( document ).ready(function() {
// This is also wrong. Currently you're passing
// whatever is returned from getSubCategories
// (which is undefined) as the callback function
// that the "change" event will call. This instead
// should be the reference to the function. Which
// in this case is getSubCategories
$("#category").change(getSubCategories);
});
Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting.
<script>
$(document).ready(function(){
$("#category").change(function(){
getSubCategories();
});
$("#type").change(function(){
getCategories();
});
});
</script>
I am using jquery function to get the selected checkbox row from the table and it worked fine after i get that data i need to pass it in ajax where i get an error myData is undefined and my code is
$("#user-table-form").on('submit', function(e){
var url = $(this).attr('action');
var method = $(this).attr('method');
usertable.$('input[type="checkbox"]:checked').each(function(){
var myData = $(this).parent().siblings().eq(2).text();
alert(myData);
});
$.ajax({
type: method,
url: url,
dataType: 'JSON',
data: myData,
success: function(data) {
alert("Promocode added successfully");
//window.location.href = "{{ route('admin.promocode')}}";
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
//console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
when i run my browser console show this error
user?userTable_length=10:347 Uncaught ReferenceError: myData is not defined
at HTMLFormElement.<anonymous> (user?userTable_length=10:347)
at HTMLFormElement.dispatch (jquery.min.js:3)
at HTMLFormElement.r.handle (jquery.min.js:3)
Where i need to define that variable please any one help me
The issue is here:
usertable.$('input[type="checkbox"]:checked').each(function(){
var myData = $(this).parent().siblings().eq(2).text();
alert(myData);
});
move var myData outside of loop like:
var myData = [];
usertable.$('input[type="checkbox"]:checked').each(function(){
myData.push($(this).parent().siblings().eq(2).text());
});
alert(myData);
I have a dropdownlist in table and button that should show if there is a value form the database. In my dropdown I send to a function
onchange = "getInfoid(this)"
The function:
function getInfoid(myvalue) {
var typeid = $(myvalue).val();
$.ajax({
url: '/mycontroller/GetInfoUrl',
contentType: 'application/html; charset=utf-8',
type: 'Get',
data: {
id: typeid
},
dataType: 'html'
})
.success(function (result) {
var tr = $($(myvalue).parents("tr")[0]);
var button = tr.find("button#Details0");
$(button).attr("onclick", "viewOhaInfo('" + result + "')");
$(button).show();
})
.error(function (result) {
var tr = $($(myvalue).parents("tr")[0]);
tr.find("button#Details0").hide();
});
};
The script does not show or hide the button. To test it; I tried the Ajax script to show and hide a div, and tried hiding and showing the button in the table using the same without Ajax, both worked. Do I lose the value of myvalue variable or what else could be the reason.
EDIT
The problem was in my understanding of success and error, I changed my script to:
.success(function (data) {
if (data == null) {
var tr = $($(myvalue).parents("tr")[0]);
tr.find("button#Details0").hide();
} else {
var tr = $($(myvalue).parents("tr")[0]);
var button = tr.find("button#Details0");
$(button).attr("onclick", "viewOhaInfo('" + data + "')");
$(button).show();
}
This solved it. Thank you all for your assistance.
jqXHR.success() and jqXHR.error() are deprecated. Read api docs.
jqXHR.done(function( data, textStatus, jqXHR ) {}); An alternative
construct to the success callback option, the .done() method replaces
the deprecated jqXHR.success() method. Refer to deferred.done() for
implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {}); An
alternative construct to the error callback option, the .fail() method
replaces the deprecated .error() method. Refer to deferred.fail() for
implementation details.
so modify your script to this:
$.ajax({
url: '/mycontroller/GetInfoUrl',
contentType: 'application/html; charset=utf-8',
type: 'Get',
data: {
id: typeid
},
dataType: 'html'
})
.done(function (result) {
var tr = $($(myvalue).parents("tr")[0]);
var button = tr.find("button#Details0");
$(button).attr("onclick", "viewOhaInfo('" + result + "')");
$(button).show();
})
.fail(function (jqXHR, textStatus) {
var tr = $($(myvalue).parents("tr")[0]);
tr.find("button#Details0").hide();
});
Here is how to do it alternatively.