So I have this jquery function that is pulling data from another domain and i want to display that data with ajax when the user enters a value into the search box. As of now the app continuously gives me the error message I wrote from the error state no matter if I search by .productName or .itemCode. Any ideas what I'm doing wrong?
function foodQuery() {
var key = "123456789";
$("#searchinput").keyup(function() {
var value = $(this).val();
foodQuery(value);
});
function foodQuery(key) { // key is passed as a parameter
var foodURL = "http://api.example.com/items?key=" + key;
$.ajax({
url: foodURL,
type: 'GET',
contentType: "text/plain",
dataType: 'json',
success: function(json) {
$.each(json.products, function(index, product) {
// build product block
var htmlString = '<div class="product large-3 columns">';
//open imgwrap
htmlString += '<div class="imgwrap">';
//get img src
htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '#2x.jpg" />';
// close imgwrap
htmlString += '</div>';
// open textwrap
htmlString += '<div class="textwrap">';
// get productName
htmlString += '<h1 class="product_headline">' + product.productName + '</h1>' ;
// get itemCode
htmlString += '<h4 class="item_id" >#' + product.itemCode + '</h4>';
// get description
htmlString += '<p class="product_desc">' + product.description + '</p>';
// open price
htmlString += '<div class="price">';
// get price & close div
htmlString += '<span class="dollar"><span class="usd">$</span>' + product.price + '</span> <span class="product_desc">per weight</span></div>'
// close divs
htmlString += '</div>';
//console.log(htmlString);
$('.listing').append( $(htmlString) );
}); //end each
}, // end success
error: function(e) {
console.log(e.message);
$('.listing').append( '<h1 class="errmsg" >Sorry, there was an unkown error.</h1>' );
} // end error
}); // end ajax request
$(".listing").html("");
}
}
Since its from a different domain, you can try using jsonp
Related
Trying to print my htmlString in the .listing div but I'm only getting the last item in the array, yet the console.log loops correctly. what gives?
$.each(json.products, function(index, product) {
// build product block
var htmlString = '<div class="product large-3 columns">';
//open imgwrap
htmlString += '<div class="imgwrap">';
//get img src
htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '#2x.jpg" />';
// close imgwrap
htmlString += '</div>';
// open textwrap
htmlString += '<div class="textwrap">';
// get productName
htmlString += '<h1 class="product_headline">' + product.productName + '</h1>' ;
// get itemCode
htmlString += '<h4 class="item_id" >' + product.itemCode + '</h4>';
// get description
// get price
// close divs
htmlString += '</div>';
console.log(htmlString);
$('.listing').html(htmlString);
}); //end each
You are overriding the contents of listing in each iteration, instead you need to append the contents.
When you use .html() it will remove the current contents of the element, then replace it with the passed content. To add the new content after the existing one you can use .append()
If you want to clear the listing element, you can do it before the beginning of the loop as shown below
$('.listing').html(''); //clear the listing element if needed
$.each(json.products, function(index, product) {
// build product block
var htmlString = '<div class="product large-3 columns">';
//open imgwrap
htmlString += '<div class="imgwrap">';
//get img src
htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '#2x.jpg" />';
// close imgwrap
htmlString += '</div>';
// open textwrap
htmlString += '<div class="textwrap">';
// get productName
htmlString += '<h1 class="product_headline">' + product.productName + '</h1>';
// get itemCode
htmlString += '<h4 class="item_id" >' + product.itemCode + '</h4>';
// get description
// get price
// close divs
htmlString += '</div>';
console.log(htmlString);
$('.listing').append(htmlString); //add the current content to existing one
}); //end each
With .html() you're replacing the contents after each loop. Instead, append:
$('.listing').html(htmlString);
becomes:
$('.listing').append( $(htmlString) );
Im making a site but i want to check the value of a session so i can show a button depending on what the users role is.
the problem im having is that i cant get the value of the session into SessionValue
i will also add that the file is a .js
what i have so far:
function getGroups() {
var SessionValue = <?php print($_SESSION['user_role']); ?>;
$.ajax({
url: 'services/functions.php',
data: {
action: 'getGroups'
},
type: 'post',
success: function (output) {
var result = JSON.parse(output);
result = result.results;
$(result).each(function (index, element) {
var out = "<div class='row'>";
out += "<div class='col-md-3'>";
out += "<img class='img-responsive image_" + index + "' src=" + element.group_image + ">";
out += "</div>";
out += "<div class='col-md-9'>";
out += "<h3>" + element.group_title + "</h3>";
if(SessionValue == "admin"){
out += "<button class='btn btn-primary pull-right' type='button' id='submitPost'>Delete</button>";
}
out += "<h4 class='hidden_" + index + "'>" + moment(element.group_playdate, 'HH:mm:ss').format('HH:mm') + "</h4>";
out += "<p class='hidden_" + index + "'>" + element.group_description + "</p>";
out += "</div>";
out += "</div>";
out += "<hr/>";
$(".groupContainer").append(out);
$(".hidden_" + index).hide();
$(".image_" + index).hover(
function () {
$('.hidden_' + index).fadeIn(200);
},
function () {
$('.hidden_' + index).fadeOut(100);
}
);
});
},
error: function (output) {
console.error("Something went wrong while loading the groups from the database.");
}
});
}
the session is started and the user_role is also defined #login.
I have a HTML code that extracts variables from JSON as :
<textarea id="{{textarea_id}}" class="comment-insert-text" style = "border: 1px solid #e1e1e1"></textarea>
</div>
<div id="{{btn_id}}" style = "margin: 2px 2px 0 0;width:26px;height: 25px;"class="comment-post-btn-wrapper">
C
</div>
The variables for id are also stored in a hidden temporary variable as:
I want to resolve these variables into a javascript file which executes an onclick function. The function takes in the id variable which is not always static. This dynamic variables are the one, passed to the temporary variable through JSON :
$(document).ready(function() {
$(document).on("click",<id-name to be resolved here> , function() {
alert("yes");
comment_post_btn_click();
});
$(document).on("click", "#comm_first_1", function() {
$('.comment-insert-text').css('border', '1px solid #e1e1e1 ');
});
});
function comment_post_btn_click()
{
var _tt = $('#textarea_id').val();
alert("in");
//Text within the textarea which the person has entered
var _comment = $('<id-name variable>').val();
var _Userid = 1;
// Hard coded the name, should be a session name like $('#Userid').val()
var _Username = "Username_sagar";
// Hard coded the name, should be a session name like $('#Username').val()
if (_comment.length > 0)
{
// proceed with ajax callback
$("#comm_first_1").css('border', '1px solid #e1e1e1');
$.post("comment_insert.php",
{
task: "comment_insert",
Userid: _Userid,
comment: _comment
}
)
.error(
function()
{
console.log("Error: ");
}
)
.success(
function(data)
{
//sucess
//insert html into the ul/li
comment_insert(jQuery.parseJSON(data)); // converts the text which we receive into a javascript object
console.log("ResponseText: " + data);
}
);
console.log(_comment + "Username: " + _Username + "Userid: " + _Userid);
}
else
{
// the textarea is empty, put a border on it
$('.comment-insert-text').css('border', '1px solid #ff0000');
console.log("The textarea is empty");
}
//remove the textarea and ready for another comment
$('#comm_first_1').val("");
}
function comment_insert(data) {
var t = '';
t += '<li class="comment-holder" id="_' + data.comment_id + '">';
t += '<div class="user-img">';
t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field" >' + data.Username + '</h3>';
t += '<div class="comment-text">' + data.comment + '</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">[x]</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
You can just add the click event to the class, not the id, then pass the this object to the function.
$(document).ready(function() {
$(".comment-insert-text").click(function() {
alert("yes");
comment_post_btn_click(this);
});
$(document).on("click", "#comm_first_1", function() {
$('.comment-insert-text').css('border', '1px solid #e1e1e1 ');
});
});
function comment_post_btn_click(textArea)
{
var _tt = $('#textarea_id').val();
alert("in");
//Text within the textarea which the person has entered
var _comment = $(textArea).val();
var _Userid = 1;
// Hard coded the name, should be a session name like $('#Userid').val()
var _Username = "Username_sagar";
// Hard coded the name, should be a session name like $('#Username').val()
if (_comment.length > 0)
{
// proceed with ajax callback
$("#comm_first_1").css('border', '1px solid #e1e1e1');
$.post("comment_insert.php",
{
task: "comment_insert",
Userid: _Userid,
comment: _comment
}
)
.error(
function()
{
console.log("Error: ");
}
)
.success(
function(data)
{
//sucess
//insert html into the ul/li
comment_insert(jQuery.parseJSON(data)); // converts the text which we receive into a javascript object
console.log("ResponseText: " + data);
}
);
console.log(_comment + "Username: " + _Username + "Userid: " + _Userid);
}
else
{
// the textarea is empty, put a border on it
$('.comment-insert-text').css('border', '1px solid #ff0000');
console.log("The textarea is empty");
}
//remove the textarea and ready for another comment
$('#comm_first_1').val("");
}
function comment_insert(data) {
var t = '';
t += '<li class="comment-holder" id="_' + data.comment_id + '">';
t += '<div class="user-img">';
t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field" >' + data.Username + '</h3>';
t += '<div class="comment-text">' + data.comment + '</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">[x]</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
I have the following code to load the first 10 blog posts and want to see how I can add a 'more...' text link at the end of the lists to load more posts:
$(document).ready(function(){
url = 'http://hopexxx.com/category/daily-devotion/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function(data){
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 10; i++) {
var entry = postlist[i];
html += '<li>';
html += '<a href="#">';
html += '<div class="entry">' + entry.title + '</div>';
html += '<div class="entry">' + entry.author + '</div>';
html += '<div class="entry">' + entry.publishedDate + '</div>';
html += '<div class="entry">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#postlist").append(html);
$("#postlist ul[data-role=listview]").listview();
}});
});
The google feed API doesn't have the option to skip elements, its just a feed, so it loads all elements (as you already have defined num=... you already know that you can load more than 4 elements (which is the default).
To do what you want you would have to call the same request on button click and then implement some logic to compare if the new result contains elements which are not displayed on your page. If so, simply append them...
I have the following .js code but when i test the site, it only displays the wordings as seen in each but no contents. What i want to achieve at the end is to be able to display 5 posts and also add a link at the bottom to display more mosts:
$(document).ready(function(){
url = 'http://hopexxx.com/category/daily-devotion/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function(data){
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 5; i++) {
html += '<li>';
html += '<a href="#">';
html += '<div class="entry">entry.title</div>';
html += '<div class="entry">author</div>';
html += '<div class="entry">publishedDate</div>';
html += '<div class="entry">contentSnippet</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#postlist").append(html);
$("#postlist ul[data-role=listview]").listview();
}});
});
If you know that your postlist is not null, and that each entry has properties 'title', 'author', 'publishedDate' and 'contentSnippet' try this:
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 5; i++) {
var entry = postlist[i];
html += '<li>';
html += '<a href="#">';
html += '<div class="entry">' + entry.title + '</div>';
html += '<div class="entry">' + entry.author + '</div>';
html += '<div class="entry">' + entry.publishedDate + '</div>';
html += '<div class="entry">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#postlist").append(html);
try a $.each loop on data.responseData.feed.entries, see here for details