search result won't automatically display - javascript

i have building a Giphy Gif search app through giphy API and it works fine just each time when i tried to type something new in the search text and the new search result won't pop out unless i reload the page.
the HTML code as following:
<html>
<head>
<title>My Giphy Search App</title>
<style>
.container-image {
width: 30%;
display: inline-block;
float: left;
margin-right:3%;
}
</style>
</head>
<body>
<div class="container container-padding50">
<input type="text" class="js-userinput container-textinput" placeholder="refresh the page if you wanna searching more">
<button class="js-go container-button">Go!</button>
</div>
<div class="js-container">
</div>
<script src ="javascript/main.js"></script>
</body>
the js code in main.jsfile as:
document.querySelector(".js-go").addEventListener("click",function(e){
var input = document.querySelector("input").value;
searchGiphy(input);
});
document.querySelector(".js-userinput").addEventListener("keyup",function(e){
var input = document.querySelector("input").value;
if(e.which == 13){
searchGiphy(input);
}
});
function searchGiphy(searchResult){
var url = "http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&q=" + searchResult;
var GiphyAJAXCall = new XMLHttpRequest();
GiphyAJAXCall.open("GET",url);
GiphyAJAXCall.send();
GiphyAJAXCall.addEventListener("load",function(e){
var data = e.target.response;
pushToDOM(data);
});
}
function pushToDOM(input){
var response = JSON.parse(input);
var imageUrls = response.data;
var container = document.querySelector(".js-container");
imageUrls.forEach(function(image){
var src = image.images.fixed_height.url;
container.innerHTML += "<img src=\"" + src + "\" class=\"container-image\">";
});
}
I am pasting all the js code above and wondering am i wrong with the ajax calling here? Could some one help me with this?

You are appending the results to the end of the current html instead of replacing what is already there. Instead use another variable to build the new html string you are constructing and then when you are done replace the innerHTML of the container with the new string.
function pushToDOM(input){
var response = JSON.parse(input);
var imageUrls = response.data;
var container = document.querySelector(".js-container");
var html = "";
imageUrls.forEach(function(image){
var src = image.images.fixed_height.url;
html += "<img src=\"" + src + "\" class=\"container-image\">";
});
container.innerHTML = html;
}

Related

I am using TypeForm and need to autofill hidden fields from a .js script

I am using TypeForm and need to autofill utm fields from javascript, everything works except I cant get the html created from the script to show on the page. I am embedding the below code in a html/js module in a clickfunnels page. Any help is very much appreciated.
<div id="typeform"></div>
<script>
//<div id="typeform"></div> <div id="row--27712"></div>
window.onload = function(){
var source = "utm_source=1";
var medium = "utm_medium=2";
var campaign = "utm_campaign=3";
var content = "utm_content=4";
var keyword = "utm_term=5"
var HTMLA = '<div data-tf-widget="mYH43Dz4" data-tf-iframe-props="title=TFS - ANALYTICSDEV V1.1" data-tf-medium="snippet" data-tf-hidden=';
var HTMLquote = '"';
var HTMLcomma = ',';
var HTMLB = '" style="width:100%;height:600px;"></div><script src="//embed.typeform.com/next/embed.js">';
var HTMLC = '</'
var HTMLD = 'script>'
var form = HTMLA.concat(HTMLquote).concat(source).concat(HTMLcomma).concat(medium).concat(HTMLcomma).concat(campaign).concat(HTMLcomma).concat(content).concat(HTMLcomma).concat(keyword).concat(HTMLB);
var form2 = form.replaceAll("undefined","");
document.getEIementById('typeform').innerHTML = form2;
};
</script>
You can pass custom values to hidden fields like this:
<div id="typeform"></div>
<link rel="stylesheet" href="//embed.typeform.com/next/css/widget.css" />
<script src="//embed.typeform.com/next/embed.js"></script>
<script>
var source = '1';
var medium = '2';
var campaign = '3';
var content = '4';
var keyword = '5';
window.tf.createWidget('mYH43Dz4', {
container: document.getElementById('typeform'),
hidden: {
utm_source: source,
utm_medium: medium,
utm_campaign: campaign,
utm_content: content,
utm_term: keyword
}
});
</script>
In case you already have those values in your host page URL, you could use transitive search params feature:
<div
data-tf-widget="mYH43Dz4"
data-tf-transitive-search-params="utm_source,utm_medium,utm_campaign,utm_content,utm_term"
></div>
<script src="//embed.typeform.com/next/embed.js"></script>
Your code does not work because you are adding script tag via innerHTML. This script tag will not execute for security purposes:
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations
https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0

Having trouble appending javascript into my html

OK,so I am trying to pull some data from an api. The problem that I have run into is that I am able to find out the information that I am looking for, but am having trouble getting that information out of the console and onto my main index.html page.
Here is my JS code
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
$.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
console.log(info);
});
});
});
Here is my html code
<div id="search">
<h1>API Test</h1>
<input type="search" id="search-keyword">
<button id="myBtn">Try it</button>
</div>
<div id="results"></div>
By doing this, I am able to get pretty much what I am looking for. However I cannot get the data from the console to the actual page.
I have tried appendChild
var bob = document.getElementById(results);
var content = document.createTextNode(info);
bob.appendChild(info);
I have tried innerHTML
var theDiv = document.getElementById(results);
theDiv.innerHTML += info;
..and I have tried .append()
$('#myBtn').click(function() {
$(results).append(info)
})
I'm out of ideas. I realize that I probably have a small problem somewhere else that I am not seeing that is probably the root of this. Much thanks to anyone who can help me with this issue.
"results" needs to be in quotes with regular javascript and for jquery you have already decalred the results variable.
var theDiv = document.getElementById("results");
theDiv.innerHTML += info;
$('#myBtn').click(function(){
results.append(info)
})
Also since you are declaring results outside of your document ready call you have to make sure you html comes before the javascript.
<script>
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
var resultedData = $.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
return info;
});
var resultDiv = document.getElementById("results");
resultDiv.innerHTML += resultedData;
});
});
</script>

JavaScript: string use in dynamic HTML

I'm new to JavaScript and have an issue with passing a string to 'innerHTML' as part of the dynamic creation of an HTML document. Reason for this: I need to specify an image path and want to be able to output a different image onto the screen depending on the details retrieved from a cookie (i.e. the image path changes each time so that image = 1001.jpg, image = 1002.jpg etc, depending on the object details retrieved). At present, unless I hardcode the line:
"<p><img src=\images/1005.jpg"\"</p>";
I don't get an output. I tried various ways of inputting a string into this line but no joy so far. My code is probably not the best, but it works, apart from the image issue:
function changeMe(){
...
var studentObject = JSON.parse(getName); // info from cookie
var path = studentObject.imagePath; // works: images/1005.jpg
var res = path.charAt(10)
//alert(res); // = 5, works
var newPath = "<p><img src=\"images/1001.jpg\"></p>";
// I 'amend' the newPath string value:
**var answer = newPath.substr(0, 23) + res + newPath.substr(25.26);**
//alert(answer); // works: <p><img src=\"images/1005.jpg"\</p>
var oPara = document.createElement('p');
oPara.style.fontFamily = "Arial sans-serif";
oPara.style.fontSize = "20px";
oPara.style.color = "#77787E";
oPara.style.fontWeight = "bold";
oPara.innerHTML = "<p><br>Name & Surname: " + studentObject.name + " " +
studentObject.surname + "</p>" + answer; // doesn't work
//"<p><img src=\\" + "\"" + path + "\"" +"></p>"; // this doesn't work either
document.body.appendChild(oPara);
}
What am I missing here?
Is this example helps?
<!DOCTYPE html>
<html lang="en">
<head>
<title> Bla! </title>
<script type='text/javascript'>
function AddStudent() {
var studentData = { "name":"John Dou" }; // for the exmaple.
var paragraph = document.createElement('p');
// set any style
paragraph.innerHTML = "The student " + studentData.name + " added to the family";
document.body.appendChild(paragraph);
}
</script>
</head>
<body>
<button onclick='AddStudent()'> Add Student </button>
</body>
</html>

adding results of XML request to a page

I am trying to get a feel for adding content to a page with XMLHTTPRequest. I would like to add the results to existing page content say in a second column, but I am not having any luck. I would appreciate a shove in the right direction. Thanks for any help.
<!DOCTYPE html>
<html>
<head>
<style>
#button{
float: left;
}
#team{
float: left;
}
</style>
<title>XMLHTTPRequest</title>
<script src="jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200) {
xmlDoc = xhr.responseXML;
var team = xmlDoc.getElementsByTagName("teammember");
var html = "";
for (i = 0; i < team.length; i++){
html +=
xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue + "<br>" +
xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue + "<br>" +
xmlDoc.getElementsByTagName("bio")[i].childNodes[0].nodeValue + "<br><br>";
}
//this is the code I would like help with
var team = document.getElementById("team");
team.appendChild(document.createTextNode("html"));
}
}
xhr.open("GET", "team.xml", true);
});
</script>
</head>
<body>
<div id="button">
<button onclick="xhr.send()">Click Me!</button>
</div>
<div id="team">
</div>
</body>
</html>
I wrote a script fairly similar to yours that does nearly exactly what you are on about. Below is the some normal JavaScript I used to put it all on the page, I have changed some of the variable names so it compares nicely with your code.
for (i=0; i<team.length; i++)
{
//Create text nodes for each element as that's what appendChild() needs
var nameText = document.createTextNode(xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue);
var titleText = document.createTextNode(xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue);
var bioText = document.createTextNode(xmlDoc.getElementsByTagName("bio")[i].childNodes[0].nodeValue);
//This div will contain one team member's info
var memberDiv = document.createElement('div');
//Add text to the div created
memberDiv.appendChild(nameText);
//Line break
memberDiv.appendChild(document.createElement('br'));
memberDiv.appendChild(titleText);
memberDiv.appendChild(document.createElement('br'));
memberDiv.appendChild(bioText);
//Add the div we've just created to the document.
document.getElementById('team').appendChild(memberDiv);
}
This may need some more adapting to suit your needs but you get the general idea. This is just one way of doing it, there's probably loads of other ways including with jQuery that may be a bit neater actually.
You can use memberDiv.setAttribute('class', className) to set the class of each div to whatever you want
Below is a visual representation of this code to make it easier to understand, click for full scale (500*1750):

Replacing DIV content based on variable sent from another HTML file

I'm trying to get this JavaScript working:
I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.
<!-- ORIGINAL DIV -->
<div id="Email">
</div>
<!-- DIV replacement function -->
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';
ReplaceContentInContainer('Email1',content);
}
</script>
<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';
ReplaceContentInContainer('Email2',content);
}
</script>
Any ideas what I've done wrong that is causing it not to work?
Rather than inserting the element as text into innerHTML create a DOM element, and append it manually like so:
var obj = document.createElement("div");
obj.innerText = "Email 2 content";
obj.className = "test"
document.getElementById("email").appendChild(obj);
See this working here: http://jsfiddle.net/BE8Xa/1/
EDIT
Interesting reading to help you decide if you want to use innerHTML or appendChild:
"innerHTML += ..." vs "appendChild(txtNode)"
The ReplaceContentInContainer calls specify ID's which are not present, the only ID is Email and also, how are the two scripts called, if they are in the same apge like in the example the second (with a corrected ID) would always overwrite the first and also you declare the content variable twice which is not permitted, multiple script blocks in a page share the same global namespace so any global variables has to be named uniquely.
David's on the money as to why your DOM script isn't working: there's only an 'Email' id out there, but you're referencing 'Email1' and 'Email2'.
As for grabbing the content parameter from the query string:
var content = (location.search.split(/&*content=/)[1] || '').split(/&/)[0];
I noticed you are putting a closing "}" after you call "ReplaceContentInContainer". I don't know if that is your complete problem but it would definitely cause the javascript not to parse correctly. Remove the closing "}".
With the closing "}", you are closing a block of code you never opened.
First of all, parse the query string data to find the desired content to show. To achieve this, add this function to your page:
<script type="text/javascript">
function ParseQueryString() {
var result = new Array();
var strQS = window.location.href;
var index = strQS.indexOf("?");
if (index > 0) {
var temp = strQS.split("?");
var arrData = temp[1].split("&");
for (var i = 0; i < arrData.length; i++) {
temp = arrData[i].split("=");
var key = temp[0];
var value = temp.length > 0 ? temp[1] : "";
result[key] = value;
}
}
return result;
}
</script>
Second step, have all possible DIV elements in the page, initially hidden using display: none; CSS, like this:
<div id="Email1" style="display: none;">Email 1 Content</div>
<div id="Email2" style="display: none;">Email 2 Content</div>
...
Third and final step, in the page load (after all DIV elements are loaded including the placeholder) read the query string, and if content is given, put the contents of the desired DIV into the "main" div.. here is the required code:
window.onload = function WindowLoad() {
var QS = ParseQueryString();
var contentId = QS["content"];
if (contentId) {
var source = document.getElementById(contentId);
if (source) {
var target = document.getElementById("Email");
target.innerHTML = source.innerHTML;
}
}
}
How about this? Hacky but works...
<!-- ORIGINAL DIV -->
<div id="Email"></div>
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
var txt = document.createTextNode(content);
container.appendChild(txt);
}
window.onload = function() {
var args = document.location.search.substr(1, document.location.search.length).split('&');
var key_value = args[0].split('=');
ReplaceContentInContainer('Email', key_value[1]);
}
</script>

Categories