Undefined is not a function (AJAX, PHP, jQuery) - javascript

I am very new to jQuery and AJAX so I apologise if I am being stupid.
I am receiving an error in my AJAX jQuery script.
I am retrieving data via AJAX get to display dynamically on my page.
The JSON file returns an array which must be iterated and displayed in a DIV for each item.
The JSON is:
[{"id":1,
"user_id":14,
"title":"The Title",
"thumbnail":"image.jpg",
"summary":"summary of post",
"content":"content info here",
"category":"Graphic Design",
"sub_category":"Adobe Photoshop",
"views":0,
"published":0,
"created_at":"2015-04-16 00:09:57",
"updated_at":"2015-04-16 00:09:57"}, {and so on...}]
The jQuery is:
function retrieveTutorials()
{
$.ajax({
type: "GET",
url: "/tutorials/retrieve",
dataType: "json",
success: function(data){
var tutorial = ('')
$.each(data, function(){
tutorial.append($( '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))
});
$("#generated-content").empty().append(tutorial);
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
The error I am currently receiving is "Uncaught TypeError: undefined is not a function" which refers to the following section
tutorial.append($( '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))
Any ideas as to where I am going wrong?
I have used very similar code before which worked fine

try this
var tutorial = $('<div></div>');

You should select any DOM Element and assign it to tutorial variable, something like this:
var tutorial = $('someCSSselector');

There is an error because you are calling .append() on (''). .append() is a jQuery function, but ('') is an empty string, not a jQuery object.
You can do this:
var tutorial = $('<div>');
...
$("#generated-content").empty().append(tutorial.html());

You should define your div object first, and you can keep generatedbox class when defining it. Then, you can omit the div that you had in the appended content.
var tutorial = $('<div class="generatedbox">')
$.each(data, function(){
tutorial.append($('<img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p>'))
});

Related

Getting attribute from XML with my script

I try to read a specific value of a XML feed. Evertyhing is working but I want to read the "StartTime=" value too.
This is the XML:
<Program StartTime="17:00:00" EndTime="17:30:00">
<Name>name</Name>
</Program>
And this is the code:
$.ajax({
type: "GET",
url: "./data.xml",
dataType: "xml",
error: function (e) {
alert("An error occurred while processing XML file");
console.log("XML reading Failed: ", e);
},
success: function (response) {
$("ul").children().remove();
$(response).find("Program").each(function () {
var _name = 'Program: ' + $(this).find('Name').text();
console.log(_name);
var _time = 'Time: ' + $(this).find('StartDateTime').text();
// add content to the HTML
$("ul").append('<li>' + _name + '</li>');
$("ul").append('<li>' + _time + '</li>');
});
}
});
}
I found some interesting information, but I can't actually use it...
The StartTime is an attribute of <Program>, not an element/node inside it. find() is for elements that are descendants.
Use attr() instead
Try:
var _time = 'Time: ' + $(this).attr('StartDate')

AJAX jQuery Iterate through response on Button Click

I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}

How to get json data from url with Cordova?

I started to develop an app with Cordova for android and I'm now searching around google for a solution(Whitelist) to get the JSON data from the URL.But I cannot find a simple tutorial. Most of the tutorials I found are not so beginner friendly. I'm thinking about trying to get the JSON data with pure javascript, but I think it's not a good idea. Are there some simple tips or tutorial that can solve this problem? I love to hear from you!
Like this? Assuming that hello.php returns your JSON data.
$.ajax({
url: "yourwebsite.com/hello.php",
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getdata(arr);
},
error: function () {
validationMsg();
}
});
function _getdata(arr){
//your JSON resuls are now in arr. Do what you need with the array.
}
This example could be very helpful.
You should try ajax calls in order to fetch data from the server, jQuery makes it very easy. Here is the function used in the example that loads the data from the server :
function getEmployeeList() {
$('#busy').show();
$.getJSON(serviceURL + 'getemployees.php', function(data) {
$('#busy').hide();
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
I hope it help.
fetch('/echo/json', {
method: 'get'
}).then((JSONresponse) => {
// do whatever you want with your
// JSONresponse here
})

Passing variable to javascript function with symbols like colon, semicolon, etc

Currently I am stock on this scenario on my current function.
Basically, this ajax call will generate list of emoticons, however I want that when a user clicks on a smiley image, the smiley code will be added to message textbox.
Like for example, when user clicks on smiling image, the :-) code will be added to the message box.
My question is, Is it possible to pass the code :-) to a function?
On my current codes, addText(' + key + ') is not working. The value of key is :-). Error says Uncaught SyntaxError: Unexpected token : And when the value is ;) the error is Uncaught SyntaxError: Unexpected token ;
I also have :lol: etc. codes similar to that. Any help will be much appreciated.
$.ajax({
type: "POST",
async: true,
cache: false,
dataType: "json",
url: "./assets/php/scripts.php",
data: {command: 'get-smileys'},
success: function (data) {
$("#smileys").empty();
$("#smileys").append("<br>");
var div_obj = document.createElement("ul");
$(div_obj).addClass('list-inline');
$.each(data, function(key, value) {
$(div_obj).append('<li><div class="col-xs-1 col-sm-1 col-lg-1" style="width:110px; height:80px" align="center"><img src="assets/img/smileys/' + value[0] + '" title="' + value[1] + '" onclick="addText(' + key + ');"><br>' + key + '</div></li>')
$("#smileys").append($(div_obj));
});
$("#smileys-flag").text('1');
$("#loader-chat").hide();
}
});
And here's the function in adding text part:
function addText(text){
var fullMessage = $("#message").val();
$("#message").val(fullMessage + text);
}
The problem is you need to pass them as string literals as given below.
'" onclick="addText(\'' + key + '\');"><br>'
But a better solution will be to use a jQuery event handler instead of a inline one like
$(div_obj).append('<li><div class="col-xs-1 col-sm-1 col-lg-1" style="width:110px; height:80px" align="center"><img class="smileys" src="assets/img/smileys/' + value[0] + '" title="' + value[1] + '" data-smiley="' + key + '"><br>' + key + '</div></li>')
then
jQuery(function ($) {
$("#smileys").on('click', '.smileys', function () {
addText($(this).data('smiley'))
});
})
You need to pass your args as string literals. Then when you are decoding it you can just get the substring you want.
For example:
function takeSmiley(smiley) {
return smiley.substr(1, smiley.length - 2) // Return lol for :lol:
}
takeSmiley(":lol:");

String Not Appended to Dynamically Created Div

I've researched this in depth on stackexchange and I don't think I am making a 'common' mistake, and the other answers have not solved this.
The problem is I am trying to append data to a DEFINITELY existing div of a certain ID. What I DO know is that the div is dynamically generated, and that is probably why it is hidden.
Despite using jquery on I cannot seem to get jquery to find the particular div.
Here is the code:
$(document).ready(function() {
function example_append_terms(data) {
var sender_id = data['sender_id'];
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = '<span data-lemma="' + v['key'] + '" class="lemma">' + v['name'] + '</span>';
$('#' + sender_id + ' .lemmas').append(html);
}
});
}
function example_get_options(data) {
$.ajax({
url: '/example/',
type: 'post',
data: data,
success: function(data) {
//alert(JSON.stringify(data))
example_append_terms(data)
},
failure: function(data) {
alert('Got an error dude');
}
});
return false;
}
$(document).on('click', ".example-synset-option", function() {
var synset = $(this).data('name');
var sender_id = $(this).attr('id')
example_get_options({
'synset': synset,
'sender_id': sender_id,
});
});
});
On clicking a certain div, an action is fired to "get options" which in turn runs an ajax function. The ajax function runs the "replacer" function example_append_terms.
Having tested up to example_append_terms the .each iteration is definitely working. But when I did tested $('#' + sender_id + ' .lemmas').length I continue to get 0.
Where is this jquery newb going wrong?
I fixed it by changing stuff...
For some inexplicable reason fetching the data attribute worked better than the id..
function intellitag_append_terms(data) {
var sender_id = $('*[data-location="'+data['sender_id']+'"] .lemmas');
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = $('<span data-lemma="' + v['key'] + '" class="label label-primary lemma">' + v['name'] + '</span>');
html.appendTo(sender_id)
//$('#' + sender_id).append(html);
}
});
}

Categories