Javascript match function not working in for loop - javascript

Javascript match function not working in my for loop properly. The match function works only once.
Not functioning code:
<script type = 'text/javascript' >
var numposts = 5;
function labelthumbs(json) {
for (var i = 0; i < numposts; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var postcontent = entry.content.$t;
url = postcontent.match(/pname='(.+?)'/);
if (url){
document.write('<td>'+url[1]+'</td>');
}else {
document.write('<td> bb</td>');
}
}
}
</script>
<script type="text/javascript" src="https://www.ibpsonline.in/feeds/posts/default/-/IBPS?published&alt=json-in-script&callback=labelthumbs"></script>

It does work on all the post, however only one of the post has pname defined with single quote. You can change your regex to the check for double quote too like postcontent.match(/pname=['"](.+?)['"]/i);
<script type = 'text/javascript' >
var numposts = 5;
function labelthumbs(json) {
for (var i = 0; i < numposts; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var postcontent = entry.content.$t;
url = postcontent.match(/pname=['"](.+?)['"]/i);
if (url){
document.write('<td>'+url[1]+'</td>');
}else {
document.write('<td> bb</td>');
}
}
}
</script>
<script type="text/javascript" src="https://www.ibpsonline.in/feeds/posts/default/-/IBPS?published&alt=json-in-script&callback=labelthumbs"></script>

Related

Use variables from a callback function into loop process of another callback function...Is it possible?

I have the "favouritePosts" json callback function working with blogger feed:
<script type='text/javascript'>
//<![CDATA[
function favouritePosts(json) {
for (var i = 0; i < numposts; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var posturl;
postdate = entry.published.$t;
var post_id = i;
var postThumb = entry.media$thumbnail.url;
var authorname = entry.author[0].name.$t;
var author_img = entry.author[0].gd$image.src;
var author_uri = entry.author[0].uri.$t;
var label_category = entry.category[i].term;
var item = '<a class="listing-geodir-category" href="">'+label_category+'</a><span class="avatar-tooltip">Added By <strong>'+authorname+'</strong></span></div><h3>'+posttitle+'</h3><div class="geodir-category-options fl-wrap"></div></div>';
document.write(item);
}
}
//]]>
</script>
that is called with the following script
<script src='/feeds/posts/summary/-/Νέα%20Καταχώρηση?alt=json-in-script&callback=favouritePosts'/>
Also there is "displayContent" json callback function that is working with sheets api:
<script>
//<![CDATA[
function displayContent(json) {
var string = "";
var len = json.feed.entry.length;
for (var i=0; i<len; i++) {
var user = json.feed.entry[i].gsx$user.$t;
var comment = json.feed.entry[i].gsx$comment.$t;
var rating = json.feed.entry[i].gsx$rating.$t;
var date = json.feed.entry[i].gsx$date.$t;
string += '<div class="reviews-comments-item"><div class="reviews-comments-item-text"><h4>' + user + '</h4><div class="listing-rating card-popup-rainingvis" data-starrating2="'+rating+'"></div><div class="clearfix"></div><p>"' + comment + '"</p><span class="reviews-comments-item-date"><i class="fas fa-calendar-check"></i>'+date+'</span></div></div>';
}
$(string).appendTo('div.reviews-comments-wrap');
}
//]]>
</script>
and is called with
<script src="https://spreadsheets.google.com/feeds/list/____/od6/public/values?alt=json-in-script&callback=displayContent">;</script>
Is it possible to get variables that used into "displayContent" sheets api json callback and use them into "favouriteposts" callback function?
Maybe with a promise function???

for loop is executed twice but data is saved only once php ajax

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body onload="searchVideo();">
<script>
var data_length = 2;
for(var i=0; i<data_length; i++){
console.log(i);
var pageToken = '';
var numOfResult = 0;
var maxResults = 200;
function searchVideo(){
var separator = ',';
$.getJSON('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&pageToken=' + pageToken + '&playlistId=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-&key=Apikey&callback=?',function(data){
var l = data.items.length;
pageToken = data.nextPageToken;
numOfResult += l;
var itemUrl = '';
var videoids = [];
for(var j = 0; j < l; j++) {
if( j == 0) {
separator = ',';
}
else {
separator = ',';
}
var videoid = data.items[j].snippet.resourceId.videoId;
var title = data.items[j].snippet.title;
$.ajax({
method: 'POST',
url: 'add.php',
data: { title: title, videoid: videoid }
})
.done(function(data) {
});
}
if( numOfResult < maxResults) {
searchVideo();
}
});
}
}
</script>
</body>
</html>
add.php
<?php
ini_set('max_execution_time', 300);
include 'config.php';
$title = mysqli_real_escape_string($mysql,$_POST['title']);
$videoid = mysqli_real_escape_string($mysql,$_POST['videoid']);
$thumbnail_url = 'http://img.youtube.com/vi/'.$videoid.'/hqdefault.jpg';
$sql = "INSERT INTO ytfb(name,video_name,thumbnail_url) VALUES('$title','$videoid','$thumbnail_url')";
$create_post_query=mysqli_query($mysql,$sql);
if(!$create_post_query)
{
die("Connection failed".mysqli_error($mysql));
}?>
From the above code data is saved only once. The data is not saved twice but am running the for loop twice to save the data twice. SO can anyone help me how to save the data twice using ajax. Only once data is saved the data is not saved twice as I have given length 2 means 2 for loops it should be saved twice
as per my comments your for loop execute one time not execute 2 times. if you want to execute 2 times then j<=1
problem in this line. i have fixed issue
for(var j = 0; j <= 1; j++) {
i solved issue on local.. your function searchVideo not execute two times. onload function call only first time. i have upload some code sample. you should fallow this sample
sample code. remove function and write code without function
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
var data_length = 2;
for(var i=0; i<2; i++){
alert(i);
console.log(i);
var pageToken = '';
var numOfResult = 0;
var maxResults = 200;
var videoid = "asdf";
var title = "erwe";
$.ajax({
method: 'POST',
url: 'test4.php',
data: { title: title, videoid: videoid }
})
.done(function(data) {
});
}
</script>
</body>
</html>
test4.php
<?php
echo "string";
?>
other way to implement the function
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
var data_length = 2;
for(var i=0; i<2; i++){
searchVideo();
alert(i)
console.log(i);
var pageToken = '';
var numOfResult = 0;
var maxResults = 200;
function searchVideo(){
var videoid = "asdf";
var title = "erwe";
$.ajax({
method: 'POST',
url: 'test4.php',
data: { title: title, videoid: videoid }
})
.done(function(data) {
});
}
}
</script>
</body>
</html>
Try this
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var paylistIdArray=['PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-','PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-'];
var pageToken ='';
var data_length = paylistIdArray.length;
var numOfResult = 0;
var maxResults = 200;
var i=0;
var paylistId=paylistIdArray[0];
function searchVideo() {
var separator = ',';
$.getJSON('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&pageToken='+pageToken+'&playlistId='+paylistId+'&key= xxxx',function(data){
console.log(data)
var l = data.items.length;
pageToken = data.nextPageToken;
numOfResult += l;
var itemUrl = '';
var videoids = [];
for(var j = 0; j < l; j++) {
if( j == 0) {
separator = ',';
} else {
separator = ',';
}
var videoid = data.items[j].snippet.resourceId.videoId;
var title = data.items[j].snippet.title;
console.log("called");
$.ajax({
method: 'POST',
url: 'add.php',
data: { title: title, videoid: videoid }
}).done(function(data) {
});
}
if( numOfResult < maxResults) {
searchVideo();
}
if( numOfResult == maxResults && i<data_length) {
i++;
pageToken = '';
numOfResult = 0;
maxResults = 200;
paylistId=paylistIdArray[i];
searchVideo();
}
});
}
searchVideo()
</script>
No we called search video function only once.(on page load)
Remove onload function from body tag
Please try this code
<script>
function searchVideo() {
var separator = ',';
$.getJSON('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&pageToken=' + pageToken + '&playlistId=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-&key=Apikey&callback=?',function(data){
var l = data.items.length;
pageToken = data.nextPageToken;
numOfResult += l;
var itemUrl = '';
var videoids = [];
for(var j = 0; j < l; j++) {
if( j == 0) {
separator = ',';
} else {
separator = ',';
}
var videoid = data.items[j].snippet.resourceId.videoId;
var title = data.items[j].snippet.title;
$.ajax({
method: 'POST',
url: 'add.php',
data: { title: title, videoid: videoid }
}).done(function(data) {
});
}
if( numOfResult < maxResults) {
searchVideo();
}
});
}
var data_length = 2;
var pageToken = '';
var numOfResult = 0;
var maxResults = 200;
for(var i=0; i<data_length; i++){
console.log(i);
searchVideo();
}
</script>
but i don't know the below condition inside searchVideo function
if( numOfResult < maxResults) {
searchVideo();
}
try this
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var pageToken ='';
var data_length = 2;
var numOfResult = 0;
var maxResults = 200;
var i=1;
function searchVideo() {
var separator = ',';
$.getJSON('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&pageToken='+pageToken+'&playlistId=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-&key= xxxx',function(data){
console.log(data)
var l = data.items.length;
pageToken = data.nextPageToken;
numOfResult += l;
var itemUrl = '';
var videoids = [];
for(var j = 0; j < l; j++) {
if( j == 0) {
separator = ',';
} else {
separator = ',';
}
var videoid = data.items[j].snippet.resourceId.videoId;
var title = data.items[j].snippet.title;
console.log("called");
$.ajax({
method: 'POST',
url: 'add.php',
data: { title: title, videoid: videoid }
}).done(function(data) {
});
}
if( numOfResult < maxResults) {
searchVideo();
}
if( numOfResult == maxResults && i<data_length) {
i++;
pageToken = '';
numOfResult = 0;
maxResults = 200;
searchVideo();
}
});
}
searchVideo()
</script>

Array of images from flickr not showing in the intended order

I'd like to preface I'm a total beginner with JS, only been working with it for a few days now.
Here's what I'm working with http://jsfiddle.net/joyroyxw/
What I want to do is get a person's name and display images of each letter in their name.
So far I'm able to split the name into the individual letters, and concatenate "letter," as search tags, so that flickr returns images of each letter.
My problem is these images are not being added in order, could this be because one query loads faster than another? How could I add a buffer or delay so that each letter is displayed in order? Why would it do that if my for loop is sending the tags to the function in order?
Javascript from jsfiddle:
function getQueryStringVar(name){
var qs = window.location.search.slice(1);
var props = qs.split("&");
for (var i=0 ; i < props.length;i++){
var pair = props[i].split("=");
if(pair[0] === name) {
return decodeURIComponent(pair[1]);
}
}
}
function getLetterImage(tag){
var flickerAPI = "https://www.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: tag,
tagmode: "all",
format: "json"
})
.done(function (flickrdata) {
//console.log(flickrdata);
var i = Math.floor(Math.random() * flickrdata.items.length);
var item = flickrdata.items[i];
var url = item.media.m;
console.log(url);
$("body").append("<img src="+ url + "></img>");
});
}
$(document).ready(function() {
var name = getQueryStringVar("name") || "Derek";
var str = "letter,";
var searchtags = new Array()
for (var i = 0; i < name.length; i++) {
//console.log(str.concat(searchtags.charAt(i)));
searchtags[i] = str.concat(name.charAt(i));
}
for (var j = 0; j < name.length; j++){
//getLetterImage(searchtags[j]);
getLetterImage(searchtags[j]);
}
});
Instead of using append, try having a place holder element already build to receive the data.
<div id="img1">Loading</div>
<div id="img2">Loading</div>
<div id="img3">Loading</div>
You can dynamically create the elements as needed with javascript. Then you populate them in the order. Simply increment i as you go.
$("#img"+i).html("<img src="+ url + "></img>");
UPDATE
Your jsfiddle was very close, but you have to remember that ajax is asynchronous.
html
<body>
<h1>Hi! What's your name?</h1>
<form action="trending.html">
<input class="textbox" type="text" name="name">
</form>
<div id="img0">Loading</div>
<div id="img1">Loading</div>
<div id="img2">Loading</div>
<div id="img3">Loading</div>
<div id="img4">Loading</div>
</body>
javascript
function getQueryStringVar(name){
var qs = window.location.search.slice(1);
var props = qs.split("&");
for (var i=0 ; i < props.length;i++){
var pair = props[i].split("=");
if(pair[0] === name) {
return decodeURIComponent(pair[1]);
}
}
}
function getLetterImage(tag, theNumber){
var flickerAPI = "https://www.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
return $.getJSON( flickerAPI, {
tags: tag,
tagmode: "all",
format: "json"
})
.then(function (flickrdata) {
//console.log(flickrdata);
var i = Math.floor(Math.random() * flickrdata.items.length);
var item = flickrdata.items[i];
var url = item.media.m;
$("#img"+theNumber).html("<img src="+ url + "></img>");
});
}
$(document).ready(function() {
var name = getQueryStringVar("name") || "Derek Martin";
var str = "letter,";
var searchtags = new Array()
for (var i = 0; i < name.length; i++) {
searchtags[i] = str.concat(name.charAt(i));
}
for (var j = 0; j < name.length; j++){
getLetterImage(searchtags[j], j);
}
});

Get anchor tag values in jQuery

I have a html tag like this.
<a class="employee_details" target="_blank" href="index1.php?name=user1&id=123">User</a>
I need to get the two parameter values in jquery
<script type="text/javascript">
$(function () {
$('.employee_details').click(function () {
var status_id = $(this).attr('href').split('name');
alert(status_id[0]);
});
});
</script>
Any help in getting both the parameter values in two variables in javascript.
I want to get user1 and 123 in two variables using jQuery
Thanks
Kimz
You can use URLSearchParams as a most up-to-date and modern solution:
let href = $(this).attr('href');
let pars = new URLSearchParams(href.split("?")[1]);
console.log(pars.get('name'));
Supported in all modern browsers and no jQuery needed!
Original answer:
Try this logic:
var href = $(this).attr('href');
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
console.log(result);
So you'll get the parameters as properties on result object, like:
var name = result.name;
var id = result.id;
Fiddle.
An implemented version:
var getParams = function(href)
{
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
return result;
};
$('.employee_details').on('click', function (e) {
var params = getParams($(this).attr("href"));
console.log(params);
e.preventDefault();
return false;
});
Fiddle.
$(function() {
$('.employee_details').on("click",function(e) {
e.preventDefault(); // prevents default action
var status_id = $(this).attr('href');
var reg = /name=(\w+).id=(\w+)/g;
console.log(reg.exec(status_id)); // returns ["name=user1&id=123", "user1", "123"]
});
});
// [0] returns `name=user1&id=123`
// [1] returns `user1`
// [2] returns `123`
JSFiddle
NOTE: Better to use ON method instead of click
Not the most cross browser solution, but probably one of the shortest:
$('.employee_details').click(function() {
var params = this.href.split('?').pop().split(/\?|&/).reduce(function(prev, curr) {
var p = curr.split('=');
prev[p[0]] = p[1];
return prev;
}, {});
console.log(params);
});
Output:
Object {name: "user1", id: "123"}
If you need IE7-8 support this solution will not work, as there is not Array.reduce.
$(function () {
$('.employee_details').click(function () {
var query = $(this).attr('href').split('?')[1];
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
var varName = decodeURIComponent(pair[0]);
var varValue = decodeURIComponent(pair[1]);
if (varName == "name") {
alert("name = " + varValue);
} else if (varName == "id") {
alert("id = " + varValue);
}
}
});
});
It's not very elegant, but here it is!
var results = new Array();
var ref_array = $(".employee_details").attr("href").split('?');
if(ref_array && ref_array.length > 1) {
var query_array = ref_array[1].split('&');
if(query_array && query_array.length > 0) {
for(var i = 0;i < query_array.length; i++) {
results.push(query_array[i].split('=')[1]);
}
}
}
In results has the values. This should work for other kinds of url querys.
It's so simple
// function to parse url string
function getParam(url) {
var vars = [],hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// your code
$(function () {
$('.employee_details').click(function (e) {
e.preventDefault();
var qs = getParam($(this).attr('href'));
alert(qs["name"]);// user1
var status_id = $(this).attr('href').split('name');
});
});

passing page scraped data in the URL

In my Chrome extension, I'm trying to scrape information from the current tab (in content.js) and send it as parameter to the provided URL (background.js). It seems like I can scrape everything from the tab and append it to the URL except the values of input tags. Here's my code:
content.js:
var elements = new Array("form","h1","input","td","textarea","time","title","var");
//declare an array for found elements
var foundElements = new Array();
//declare an array for found ids
var foundIds = new Array();
//this counter is used to hold positions in the element array.
var elementCounter = 0;
//this counter is used to hold positions in the foundIds array
var idsCounter = 0;
//this counter is used to hold positions in the classCounter array.
var classCounter = 0;
//and we're going to output everything in a giantic string.
var output = "URL=" + document.URL;
//scrape the page for all elements
for (var i = 0; i < elements.length; i++)
{
var current = document.getElementsByTagName(elements[i]);
if(current.length>0)
{
for (var z=0; z<current.length; z++)
{
var inTxt = current[z].innerText;
output += "&" + elements[i] + "=" + inTxt;
}
elementCounter++;
//now that we have an array of a tag, check it for IDs and classes.
for (var y = 0; y<current.length; y++)
{
//check to see if the element has an id
if(current[y].id)
{
//these should be unique
var hit = false;
for (var x = 0; x<foundIds.length; x++)
{
if(foundIds[x]==current[y].id)
{
hit=true;
}
}
//if there was no hit...
if(!hit)
{
foundIds[idsCounter]=current[y].id;
idsCounter++;
var currVal = current[y].value;
output+="&" + current[y].id + "=" + currVal;
}
}
//now we pull the classes
var classes = current[y].classList;
if(classes.length>0)
{
for (var x = 0; x<classes.Length; x++)
{
var hit = false;
for (var z = 0; z<foundClasses.length; z++)
{
if(foundClasses[z]==classes[x])
{
hit=true;
}
}
//if there was not a hit
if(!hit)
{
foundClasses[classCounter]=classes[x];
classCounter++;
output+="&" + classes[x] + "=";
}
}
}
}
}
}
chrome.runtime.sendMessage({data: output});
background.js:
var output2;
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
output2 = "text_input1=";
output2 += request.data;
});
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.create({url: "http://www.google.com?" + output2}, function(tab) {
chrome.tabs.executeScript(tab.id, {file: "content.js"}, function() {
sendMessage();
});
});
});
Does anyone know why the input tags values are passed as blank?
Because you're trying to get the input text by using current[z].innerText.
However, you have to use current[z].value for inputs.

Categories