I'm trying to pass my own array of objects: results[num_row] = {'title:\'' + title + '\', ' + 'url:\'' + url + '\''};
but this returns the error in firebug
when I try: results[num_row] = {title:'Link A', url:'/page1'}
it works.
Thanks,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="styles.css" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script type="text/javascript">
var test = ["a","b","ab"];
var results = new Array();
function prep(){
$("#searchbox").autocomplete(results,{
formatItem: function(item) {
return item.title;
}
}).result(function(event, item) {
location.href = item.url;
});
}
$(document).ready(function(){
$.ajax({
type: "GET",
url: "links2.xml",
dataType: "xml",
success: function(xml) {
// Count elements
var count = $(xml).find('ROW').length;
// Create Array of correct length
//window.results = new Array(count);
// Set array variable
var num_row = 0;
//data string
var datastring = "";
//start of find block
$(xml).find('ROW').each(function() {
var title = $(this).find('SC_DF_FIELD_1').text();
var url = $(this).find('SC_DF_FIELD_2').text();
var support_url = $(this).find('SC_DF_FIELD_3').text();
var description = $(this).find('SC_DF_FIELD_4').text();
var contacts = $(this).find('SC_DF_FIELD_5').text();
//clean up xml variables
url = url.substring(url.indexOf('>') + 1, url.indexOf('/a') - 1);
support_url = support_url.substring(support_url.indexOf('>') + 1, support_url.indexOf('/a') - 1); /*need to clean up contacts search later */
//alert(title + '\t' + url + '\t' + support_url + '\t' + description + '\t' + contacts);
results[num_row] = {'title:\'' + title + '\', ' + 'url:\'' + url + '\''};
//results[num_row] = title;
//results[num_row] = {text:'Link A', url:'/page1'}
num_row++
// $('<div class="items"></div>').html('' + title + '').appendTo('#page-wrap');
});
//end of find block
prep();
}
});
});
</script>
</head>
<body>
<div id="page-wrap">
<FORM autocomplete="off"><INPUT id="searchbox" type="text"/>
</FORM></DIV>
</body>
</html>
That gives you a SyntaxError, the Object initializer syntax doesn't work like that.
If you want to use the title and url variables in a new object, you can easily:
//...
results[num_row] = {'title': title , 'url': url};
//...
Essentially when you write
{'title:\'' + title + '\', ' + 'url:\'' + url + '\''}
You are trying to set the value of
results[num_row]
equal to an incomplete object
{ PropertyName }
when you need
{ PropertyName : PropertyValue }
Try
results= [];
num_row = 0;
title = "myTitle";
url = "myURL";
results[num_row] = {'title': title, 'url': url}
Related
i'm still learning ajax,jquery and js here.. So in this problem i want to get the json data and display each of it into div id="card-body" dynamically one by one per ID, but it seems my code doesn't work because the result only show one div that have all the data inside of it. Are there any suggestion that can be added or changed within the code here?
<div class="container">
<div class="card">
<div class="card-header">
</div>
<div class="addDiv">
<div id="card-body">
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function (result) {
$.each(result, function (index, item) {
var userId = item.userId;
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $info = $("<p/>").html("user id: " + userId + "<br>"
+ "id: " + typeId + "<br>"
+ "title: " + titleId + "<br>"
+ "body: " + bodyId);
var html = '<div id="card-body>';
for (let i = 0; i < $(result).length; i++) {
const element = $(result)[i];
}
html += '</div>';
$(".addDiv").append(html);
$("div#card-body").append($info);
});
// console.log('success', result);
// console.log(result[0].body);
// console.log($(result).length);
}
});
});
</script>
for (let i = 0; i < $(result).length; i++) {
const element = $(result)[i];
}
what is here going to do?
or you mean this? --- Updated
$(function() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function(result) {
var container = $("div#list");
$.each(result, function (index, item) {
var userId = item.userId;
var id = "card-body-" + userId;
var el = $('div#' + id)
console.log(el)
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $info = $('<div>').html(
"user id: " + userId + "<br>" +
"id: " + typeId + "<br>" +
"title: " + titleId + "<br>" +
"body: " + bodyId
);
if (!el.length) {
// not found, create new one
el = $('<div id="' + id + '">')
container.append(el)
}
el.append($info)
});
}
});
});
I have the following JavaScript function that is called onload of an HTML page, but my data isn't parsing nor anything can be written in html through this function:
function displaySearchResults(){
//link base para a realização de requests para a API
var requestBaseURL = "https://api.predicthq.com/v1/events?";
var startDate = "start.gte=" + sessionStorage.getItem("startDate") + "&";
var endDate = "start.lte=" + sessionStorage.getItem("endDate") + "&";
var eventType = "category=" + sessionStorage.getItem("eventType") + "&";
var countrySearch = "country=" + sessionStorage.getItem("countrySearch");
var requestURL = requestBaseURL + startDate + endDate + eventType + countrySearch;
var searchRequest = new XMLHttpRequest();
searchRequest.withCredentials = false;
searchRequest.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
var data = JSON.parse(this.responseText);
console.log(data);
//TODO parse data into lists with associated buttons
var result = data.results
var msg = ""
for (var i=0;i < result.length;i++) {
msg += ("<li>" + result[i].title + "</li>\n");
}
msg = "<li>END</li>"
document.getElementsById("searchResults").innerHTML=msg;
}
});
}
Nor any data from the request nor de END msg is passing to the this HTML page:
(...)
<script type="text/javascript" src="js/script.js"></script>
</head>
<body onload="displaySearchResults()">
<header id="header">
</header>
<div class="container">
<div class="row">
<h5>Resultados:</h5>
<ul id="searchResults">
</ul>
</div>
</div>
</body>
Ive tried calling it at the end and after the body tag, same result. If its on load why doesn't appear anything, also console shows no errors.
Try this. It has a button which on click render the List in dom.
var data = {
results: [{
title: "title1"
}, {
title: "title2"
}, {
title: "title3"
}]
}
function LoadResult() {
var result = data.results
var msg = "<ul>"
result.forEach(s => {
msg = msg + "<li>" + s.title + "</li>"
})
msg = msg + "<li>END</li></ul>"
document.getElementById("result").innerHTML = msg;
}
<html>
<body>
<button onClick="LoadResult()">Load</button>
<div id="result">
</div>
</body>
</html>
I use RSS to get posts from my WordPress website and in its name have date in title and I want to remove the date from its title and use date from rss instead
The Result I want (image) I want to remove date on title (red cross) and use rss date(green underline) instead
The problem is date format in title is not international format
Any idea to make jQuery to detect this date formula and replace(remove) it?
HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="http://momentjs.com/downloads/moment-with-langs.min.js"></script>
<script type="text/javascript" src="http://www.sd.ac.th/main/wp-content/rss_fetch/FeedEk.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#divRss').FeedEk({
FeedUrl: 'http://www.sd.ac.th/main/?feed=rss2&cat=121',
//FeedUrl: 'http://www.sd.ac.th/main/?feed=rss2&cat=234',
MaxCount: 10,
ShowPubDate: true,
ShowDesc: false
});
/*setInterval(function(){
$('.itemTitle a').each(function() {
var text = $(this).text();
$(this).text(text
.replace('[', '')
.replace(']', '')
.replace('59', '')
.replace('60', '')
);
});}
, 1);*/
});
function reloadFunction() {
location.reload();
}
</script>
<button onclick="reloadFunction()">R</button>
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="http://www.sd.ac.th/main/wp-content/rss_fetch/rss_style.css">
<div id="divRss"></div>
FeedEk.js (Plugin that I use for fetching my feed)
/*
* FeedEk jQuery RSS/ATOM Feed Plugin v3.0 with YQL API
* http://jquery-plugins.net/FeedEk/FeedEk.html https://github.com/enginkizil/FeedEk
* Author : Engin KIZIL http://www.enginkizil.com
*/
(function ($) {
$.fn.FeedEk = function (opt) {
var def = $.extend({
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
DescCharacterLimit: 0,
TitleLinkTarget: "_blank",
DateFormat: "",
DateFormatLang:"en"
}, opt);
var id = $(this).attr("id"), i, s = "", dt;
$("#" + id).empty();
if (def.FeedUrl == undefined) return;
$("#" + id).append('<img src="loader.gif" />');
var YQLstr = 'SELECT channel.item FROM feednormalizer WHERE output="rss_2.0" AND url ="' + def.FeedUrl + '" LIMIT ' + def.MaxCount;
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(YQLstr) + "&format=json&diagnostics=false&callback=?",
dataType: "json",
success: function (data) {
$("#" + id).empty();
if (!(data.query.results.rss instanceof Array)) {
data.query.results.rss = [data.query.results.rss];
}
$.each(data.query.results.rss, function (e, itm) {
s += '<li><div class="itemTitle"><a href="' + itm.channel.item.link + '" target="' + def.TitleLinkTarget + '" >' + itm.channel.item.title + '</a></div>';
if (def.ShowPubDate){
dt = new Date(itm.channel.item.pubDate);
s += '<div class="itemDate">';
if ($.trim(def.DateFormat).length > 0) {
try {
moment.lang(def.DateFormatLang);
s += moment(dt).format(def.DateFormat);
}
catch (e){s += dt.toLocaleDateString();}
}
else {
s += dt.toLocaleDateString();
}
s += '</div>';
}
if (def.ShowDesc) {
s += '<div class="itemContent">';
if (def.DescCharacterLimit > 0 && itm.channel.item.description.length > def.DescCharacterLimit) {
s += itm.channel.item.description.substring(0, def.DescCharacterLimit) + '...';
}
else {
s += itm.channel.item.description;
}
s += '</div>';
}
});
$("#" + id).append('<ul class="feedEkList">' + s + '</ul>');
}
});
};
})(jQuery);
If it is always and the only thing between brackets ([ and ]) and it's always at the end of the string then use this:
text = text.replace(/(\[.*\])$/, replacementDateString);
Read about Regular Expression.
The object array is built here in the first script..."order_items". I want to pass it into the second script so I can loop through values and build a pixel to render to my screen. I'm stuck trying to pass the array.
#for (int i = 0; i < OrderItemsReceived.Count; i++)
{
<script type="text/javascript" id="pepper" data-search="order_items">
var order_items = [{
'name':ProductName',
'sku': SKU',
'price': UnitPrice.ToString().Replace(",", "")',
'quantity': Quantity.ToString()'
}]
</script>
}
<script type="text/javascript">
var script_tag = document.getElementById('pepper');
var order_items = script_tag.getAttribute("data-search");
var order_id = #Model.OrderId;
var pixel_html = '';
var integration = 'DYNAMIC';
var program_id = 7302;
if (order_id && order_items) {
jQuery.each( order_items, function (i, order_item) {
pixel_html += '&' + 'ITEM_ID' + i + '=' + order_item.sku +
'&' + 'ITEM_PRICE' + i + '=' + order_item.price +
'&' + 'QUANTITY' + i + '=' + order_item.quantity;
});
if (pixel_html) {
pixel_html = '<iframe src="https://t.pikespeak.com/track?' +
'INT=' + integration +
'&' + 'PROGRAM_ID' + '=' + program_id +
'&' + 'ORDER_ID' + '=' + order_id +
pixel_html +
'" width="1" height="1" frameborder="0"></iframe>';
}
}
$('body').append(pixel_html);
</script>
this is how I solved the problem.
<script type="text/javascript" id="pepper" data-search="order_items">
alert("hello");
var order_items = #Html.Raw(Json.Encode(Model.OrderItemsReceived.OrderItemsReceived));
var order = [];
var order_listItems = [];
for (var i = 0; i < order_items.length; i++){
var orderList = order_items[i];
order = [{
'sku': orderList.SKU,
'price': orderList.UnitPrice,
'quantity': orderList.Quantity
}]
order_listItems.push(order);
}
I chose to go ahead with a json object because my array would be constructed of key, value pairs. Once I realized this, the scope of the variable was no longer the issue.
I was wondering how I could embed pictures from FLICKR onto the website, right now, I can only get the URL's of the image, but I wanted to get the whole image with it. Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
API_KEY = 'YOURAPIKEY'; //INSERT API KEY
USER_ID = '28858578#N06'; //ENTER USER ID
var photolist = [];
$.getJSON('https://www.flickr.com/services/rest/?method=flickr.people.getPhotos&api_key=' + API_KEY + '&user_id=' + USER_ID + '&format=json&jsoncallback=?', function(rest) {
var numPhotos = rest.photos.pages;
for (var u =1; u < numPhotos + 1; u++) {
$.getJSON('https://www.flickr.com/services/rest/?method=flickr.people.getPhotos&api_key=' + API_KEY + '&user_id=' + USER_ID + '&format=json&page=' + u + '&jsoncallback=?', function(results) { var targetDiv = $('#fotolist')
for (var m =0; m < results.photos.total; m++) {
targetDiv.append("https://www.flickr.com/" +
results.photos.photo[m].owner + "/" + results.photos.photo[m].id + "<br />");
photolist.push("https://www.flickr.com/" + results.photos.photo[m].owner + "/" + results.photos.photo[m].id);
}
});
}
});
});
</script>
</head>
<body>
<div id="fotolist">
</div>
</body>
</html>
if photolist contains array of links of images
var fotolist = $('#fotolist');
jQuery.each(photolist , function(index, value){
fotolist.append('<img src="'+value+'">');
});