My code works when i'm slowly stepping through in debug mode, but when i try it in real time, it doesn't seem to want to update the page.
Here is the javascript:
searchButton = document.getElementById("searchButton");
var searchBox = document.getElementById('searchBox');
searchButton.addEventListener("click", searchItem);
function searchItem(){
searchString = searchBox.value;
article = document.getElementById("homeSection");
var xmlhttp = getXmlHttpRequestObject();
var string = '';
if(xmlhttp){
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var response = JSON.parse(xmlhttp.responseText);
for(var i=0; i<response.length; i++){
string += '<section class="searchResult">';
string += '<h1>' + response[i].Name + '</h1>';
string += '<p class="photo"></p>';
string += '<p class="price">£' + response[i].Price + '</p>';
string += '<p class="productID">ID: ' + response[i].ID + '</p>';
string += '<p class="description">' + response[i].Description + '</p>';
string += '<p class="quantity">Quantity: ' + response[i].Quantity + '</p>';
string += '</section>';
}
article.innerHTML = '<h1>Search</h1><section><h1 class="bottomBorder">You searched for: "' + searchString + '"</h1></section>';
article.innerHTML += string;
}
};
xmlhttp.open("GET", "search.php?search=" + searchString, true);
xmlhttp.send(null);
}
}
Two things you need to do
Cancel the click action that is triggering the function
Second encode the content you are sending to the server
Updated code:
function searchItem (event){
event.preventDefault();
var searchStringEnc = encodeURIComponent(searchBox.value);
...
xmlhttp.open("GET", "search.php?search=" + searchStringEnc, true);
It's not working on IE, rest of the responses and suggestions here are correct. Why IE only? because you have undefined vars:
searchString = searchBox.value;
correct
var searchString = searchBox.value;
To check if your script is truly working just alert the formatted string.
article.innerHTML += string;
alert(string);
then you will know what is wrong.
If you're using a button in a form to post with AJAX, make sure the button type="button" or it will act as a submit button and submit the form. This little feature cost me days of frustration!!!
Related
I am trying to make tabulator to show clickPopup with data that comes with additional http-request. Here is the definition of certain column, which calls cellPopupFormatterVV function:
{title:"WSCReportVolumes", field:"WSCReportVolumes.ErrorShort",
mutator:mutatorNoData,
clickPopup:cellPopupFormatterVV
},
Here is function itself:
var cellPopupFormatterVV = function(e, cell, onRendered){
var cellContent = cell.getData();
var data = handlerCellPopup();
var container = document.createElement("div");
var contents = "<strong style='font-size:1.2em;'>Status details</strong><br/><ul style='padding:0; margin-top:10px; margin-bottom:0;'>";
contents += "<li><strong>Error:</strong> " + data.ErrorShort + "</li>";
contents += "<li><strong>Error Code:</strong> " + data.ErrorCode + "</li>";
contents += "<li><strong>Error Description:</strong> " + data.ErrorLong + "</li>";
contents += "<li><strong>Failed Check:</strong> " + data.FunctionName + "</li>";
contents += "<li><strong>Result:</strong> " + data.ShortMsg + "</li>";
contents += "</ul>";
container.innerHTML = contents;
return container;
};
I'm trying to get data through function handlerCellPopup() which is in separate file "controller_ajax.js":
<script type="text/javascript" src="controller_ajax.js"></script>
The function itself:
function handlerCellPopup() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
let Response = xhttp.response;
return (Response);
};
xhttp.open("GET", "http://localhost:8003/ajax?cellPopup=rov_WSCReportVolumes_Last&computerName=ALAV706", true);
xhttp.responseType = 'json';
xhttp.send();
}
When I do request through browser, it returns exactly what I expect:
[{"ErrorLong":"Free disk space is low","ExecCode":1,"ErrorShort":"Warning","FunctionName":"Check-IsVolumeLowSpace","ErrorCode":201,"ShortMsg":"C:\\"}]
But if I try to click cell in tabulator no popup is shown. I think there is a problem with handlerCellPopup() but no idea how should I change function. Please, help.
I have written this code which is supposed to print the information from the xml file into a list for each faculty member. I want to eventually place all of these into a table, but need to know how to print them to the screen first.
function init() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseXML);
var faculty = this.responseXML.getElementsByTagName("faculty");
var strOut = "<ul>";
for (i = 0; i < faculty.length; i++) {
var name = faculty[i].getElementsByTagName("name")[0].innerHTML;
var title = faculty[i].getElementsByTagName("title")[0].innerHTML;
var office = faculty[i].getElementsByTagName("office")[0].innerHTML;
var phone = faculty[i].getElementsByTagName("phone")[0].innerHTML;
var email = faculty[i].getElementsByTagName("email")[0].innerHTML;
strOut += "<li><a href = " + name + title + "</a></li>";
}
strOut += "<ul>";
document.getElementById("output").innerHTML = strOut;
}
};
xhttp.open("GET", "faculty.xml", true);
xhttp.send();
}
window.onload = init;
Here is the XML file:
<facultyInfo>
<faculty>
<name>Prof A</name>
<title>Professor and Program Coordinator</title>
<office>CI 555</office>
<phone>(999-999-9999</phone>
<email>ProfA#school.edu</email>
</faculty>
<faculty>
<name>Prof B</name>
<title>Visiting Professor</title>
<office>CI 333</office>
<phone>999-999-9999</phone>
<email>ProfB#school.edu</email>
</faculty>
</facultyInfo>
This line:
strOut += "<li><a href = " + name + title + "</a></li>";
... is both malformed and probably not what you intended. Between the missing quotes for the href attribute, missing the ">" to close off the <a> start, and not putting any text in between <a></a>, this results in a link tag where the link destination (href) is set, but the actual text to show to the user is not set. I don't see any links in your XML (maybe that is for the future), so for now you probably want something like this:
strOut += '<li>' + name + ', ' + title + '</li>';
Here is a quick demo with your XML input:
<div id="output"></div>
<script>
var xmlString = '<facultyInfo> <faculty> <name>Prof A</name> <title>Professor and Program Coordinator</title> <office>CI 555</office> <phone>(999-999-9999</phone> <email>ProfA#school.edu</email> </faculty> <faculty> <name>Prof B</name> <title>Visiting Professor</title> <office>CI 333</office> <phone>999-999-9999</phone> <email>ProfB#school.edu</email> </faculty> </facultyInfo>';
var xmlDoc = (new DOMParser()).parseFromString(xmlString,'text/xml');
// var faculty = this.responseXML.getElementsByTagName("faculty");
var faculty = xmlDoc.getElementsByTagName("faculty");
var strOut = "<ul>";
for (i = 0; i < faculty.length; i++){
var name = faculty[i].getElementsByTagName("name")[0].innerHTML;
var title = faculty[i].getElementsByTagName("title")[0].innerHTML;
var office = faculty[i].getElementsByTagName("office")[0].innerHTML;
var phone = faculty[i].getElementsByTagName("phone")[0].innerHTML;
var email = faculty[i].getElementsByTagName("email")[0].innerHTML;
strOut += '<li>' + name + ', ' + title + '</li>';
}
strOut += "<ul>";
document.getElementById("output").innerHTML = strOut;
</script>
I'm trying to run the following script on a specific Wordpress page, but it's not working. The script does work but when not applied to the specific page. Yes the page id is correct. What did I do wrong? Thanks in advance.
<?php if (is_page('page-id-48857') ):?>
<script>
jQuery(document).ready(function ($) {
$(function () {
var $content = $('#jsonContent');
var data = {
rss_url: 'https://inside.calpoly.edu/feed'
};
$.get('https://api.rss2json.com/v1/api.json', data, function (response) {
if (response.status == 'ok') {
var output = '';
$.each(response.items, function (k, item) {
output += '<div class="post-card category-medium published">';
//output += '<h3 class="date">' + $.format.date(item.pubDate, "dd<br>MMM") + "</h4>";
var tagIndex = item.description.indexOf('<img'); // Find where the img tag starts
var srcIndex = item.description.substring(tagIndex).indexOf('src=') + tagIndex; // Find where the src attribute starts
var srcStart = srcIndex + 5; // Find where the actual image URL starts; 5 for the length of 'src="'
var srcEnd = item.description.substring(srcStart).indexOf('"') + srcStart; // Find where the URL ends
var src = item.description.substring(srcStart, srcEnd); // Extract just the URL
output += '<p class="post-meta">';
//output += '<span class="published">' + item.pubDate + '</span>';
output += '#inside.calpoly.edu</span>';
output += '</p>';
output += '<h2 class="entry-title">' + item.title + '</h2>';
//output += '<div class="post-meta"><span>By ' + item.author + '</span></div>';
var yourString = item.description.replace(/<img[^>]*>/g,""); //replace with your string.
var maxLength = 300 // maximum number of characters to extract
//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
output += '<div class="excerpt">'+trimmedString + '</div>';
output += 'Read More';
output += '<a class="entry-featured-image-url" href="'+ item.link + '"><img src="' + src + '"></a>';
output += '</div>';
return k < 1;
});
$content.html(output);
}
});
});
</script>
<?php endif; ?>
You are passing in an invalid ID to the is_page() function.
Based off of your code sample, you should be using an integer for your post ID and not a string and also not the 'page-id' portion.
https://developer.wordpress.org/reference/functions/is_page/
Here's some example usages:
// When any single Page is being displayed.
is_page();
// When Page 42 (ID) is being displayed.
is_page( 42 );
// When the Page with a post_title of "Contact" is being displayed.
is_page( 'Contact' );
// When the Page with a post_name (slug) of "about-me" is being displayed.
is_page( 'about-me' );
In your case you should be using:
<?php if (is_page(48857) ):?>
WordPress' is_page() function requires a "Page ID, title, slug, or array of such.". 'page-id-48857' is the body class, you need to just use is_page( 48857 ) since the actual ID is just 48857.
Also note that you should seriously consider using wp_enqueue_script() instead of coding in a custom script tag. It will save you countless headaches in the future.
I'm sending an xmlhttprequest to youtube to get some videos. I have gone to the google developer's console and set up an api key with WORK URL I'm requesting from connected to it. When I try to run the script from WORK URL, I get an 'ipreferrer not allowed' error, even though I specified that url on my api key.
But when I connect the api key to MY OWN PERSONAL URL and run the same script from that url, it works fine. So when it's run from WORK URL it must be sending the wrong referral url to youtube.
The question is, how can I tell what referral url my xmlhttprequest is telling youtube it is coming from?
My code is below:
function createCORSRequest(myurl, cb)
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
if( typeof cb === 'function' )
cb(xmlhttp.responseText);
}
}
xmlhttp.open("GET",myurl,true);
xmlhttp.send();
}
function buildVideoMenu()
{
openDiv = true;
mainVideoTarget = 'main_video';
playlistID = 'PLAg45-Ox3WR4gODmcAmIYHVvCpngXcCTZ';
menuDiv = 'video_menu_images';
thumbnailDiv = 'thumb';
APIKey = 'AIzaSy...';
url = 'https://www.googleapis.com/youtube/v3/playlistItems?' +
'&part=snippet' +
'&maxResults=25' +
'&playlistId=' + playlistID +
'&key=' + APIKey;
//alert(url);
createCORSRequest(url, function(srchJSON) //Get JSON for search
{
myDivHTML = '';
myDiv = document.getElementById("video_menu_images"); //get div in variable
console.log("YouTube returned the json code: " + srchJSON);
srchObj = JSON.parse(srchJSON); //parse JSON for playlistItems
for(i=0;i<srchObj.items.length;i++) //For items in srchObj.items:
{
console.log("item number " + i);
if(srchObj.items[i].snippet.thumbnails!=undefined)
{
if(openDiv)
{
myDivHTML += '<div id = "tnvertblock">';
}
myDivHTML += ' <div class = "' + thumbnailDiv + '">';
//console.log(srchObj.items[i].snippet.title);
vidFrameURL = 'https://www.youtube.com/embed/' + srchObj.items[i].snippet.resourceId.videoId;
//console.log("url = " + vidFrameURL);
imgUrl = srchObj.items[i].snippet.thumbnails.default.url; //get thumbnail image url
myDivHTML += ' <a href = "' + vidFrameURL + '" target = "' + mainVideoTarget +'">';
myDivHTML += ' <img width = "120" height = "90" class = "thumbnail" src = "' + imgUrl + '" />';
myDivHTML += ' </a>';// Put in the item.snippet.thumbnails.default.url (its own div)
myDivHTML += ' </div>'; //close thumbnail div
if(!openDiv)
{
myDivHTML += '</div>';
}
openDiv = !openDiv;
}
}
//alert(myDivHTML);
myDiv.innerHTML = myDivHTML;
});
}
buildVideoMenu();
UPDATE: To clarify my question, here's a screenshot of the console developer's page with an explanation:
var pre = '<a href=someDirectoryPath';
var mid = '.aspx">';
var post = '</a>';
var trailHTML = '';
for(i=0;i<trail.length;i++) {
trailHTML = trailHTML + pre + getURL(trail[i]) + mid + trail[i] + post;
if(i!=(trail.length-1)) {
trailHTML += ' > ';
}
}
document.write(trailHTML);
trail is an arraylist of valid pages, like so:
['some name', 'another name','yet another name','name']
getURL just takes that name and adds a '-' in between words, which is the page name. This has been tested and works. (for example, getURL('some name') returns 'some-name')
The problem is, when run in IE9 (untested in other browsers), when I write trailHTML to the page, I only get the last element in the array. Why is this?
Let me know if you need any clarification...
function getURL(txt){
return txt.replace(/ /g,"-");
}
var trail = ['some name', 'another name','yet another name','name'];
///////////////////////////////////////////////////
var pre = '<a href="someDirectoryPath/'; // changed
var mid = '.aspx">';
var post = '</a>';
var trailHTML = '';
for(i=0;i<trail.length;i++) {
trailHTML += pre + getURL(trail[i]) + mid + trail[i] + post;
if(i<trail.length-1)trailHTML+=" > " // changed
}
document.write(trailHTML);
You have a syntax error in your for-loop: The open "{" on the if does not have a matching "}".
I ran a small sample in IE9 and got all items in the array, not just the last item as you report. Here's what I ran:
<script type="text/javascript">
function getURL(s){
return s.replace(" ", "-");
}
var trail = ['some name', 'another name','yet another name','name'];
var pre = '<a href=someDirectoryPath';
var mid = '.aspx">';
var post = '</a>';
var trailHTML = '';
for(i=0;i<trail.length;i++) {
trailHTML = trailHTML + pre + getURL(trail[i]) + mid + trail[i] + post;
if(i!=(trail.length-1)) {
trailHTML += " > ";
}
}
trailHTML = trailHTML + getURL(trail[0]);
document.write(trailHTML);
</script>
The output looked like this:
some name > another name > yet another name > namesome-name
Most likely your issue is caused by the syntax error, or in how the array is built/passed into your function.