Wordpress can't handle jQuery code - javascript

I have requested an API from a website to check availability of an email, and I got a jQuery code to integrate the API to my website.
I use WordPress, and I tried to add the code, but it doesn't work and I don't know why.
I suspected it was a jQuery library problem, so I loaded it in the "function" file, and in the script from google API, but nothing.
Thanks for your help, and here is the code (by the way I also tried changing with 'jQuery.')
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>emailverifyapi.com : License Key Sample.</title>
<style type="text/css">
.statusUnknown {
color: #c1c72c;
}
.statusOk {
color: #009933;
}
.statusBad, .errorMsg {
color: #ff0000;
}
input[type='text'] {
width: 300px;
}
p label {
display: inline-block;
width: 60px;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<h1>emailverifyapi.com : email verification demo using simple key authentication with jQuery.</h1>
<h2>About</h2>
<p>This example shows how to perform email verification using just client side scripting and invoking a simple key based RESTful endpoint at api.emailverifyapi.com.</p>
<h2>How to run this sample</h2>
<p>This page can be hosted anywhere (i.e. any web host or platform). The only thing needed is a valid license key.</p>
<h2>Key features</h2>
<ul>
<li>Compatible with all modern browsers</li>
<li>Uses jQuery 1.11.1</li>
<li>No server side scripting required</li>
</ul>
<hr />
<h2>Try it</h2>
<p>
<label for="key">Key:</label>
<input type="text" id="key" name="key" tabindex="1" maxlength="20" />
</p>
<p>
<label for="email">Email:</label>
<input type="text" name="email" id="email" tabindex="2" />
<input type="button" name="submit" id="submit" tabindex="3" value="verify" />
</p>
<div id="validationResult"></div>
<!--Result output here-->
<script>
/*nest key logic inside document.ready to ensure functionality only available once document has fully loaded in browser.*/
$(function() {
console.log("ready!");
$('#submit').click(function() {
var emailText = $('#email').val(); // get key from text box entry
var keyText = $('#key').val(); // get email address to be checked from text box
if (keyText.length == 0) {
$('#validationResult').html("<span class='errorMsg'>Please enter key.</span>");
return;
}
if (emailText.length == 0) {
$('#validationResult').html("<span class='errorMsg'>Please enter something for email.</span>");
return;
}
$('#validationResult').html("verifying...");
var emailVerifyApi = '//api.emailverifyapi.com/api/a/v1?email=' + encodeURIComponent(emailText) + '&key=' + keyText;
/*execute remote request to perform email verification. Any errors will appear in the developer console (e.g. viewable using Chrome developer tools)*/
$.getJSON(emailVerifyApi, {})
.done(function(data) {
reportResult(data);
})
.fail(function(jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request failed: " + err);
});;
});
});
/*Output result to the 'validationResult' div element*/
function reportResult(data) {
var status = data['status'].toLowerCase(); // get 'status' from REST response
var additionalStatus = data['additionalStatus']; // get 'additionalStatus' from REST response
var message = data['Message']; // if there is an error (e.g. license issues), a notification will appear in the 'Message" from REST response.
console.log(status);
console.log(additionalStatus);
console.log(message);
var statusHtml;
// if there is an error message, show here
if (message != null && message != '') {
statusHtml = "<span class='errorMsg'>Error. Message='" + message + "' .</span>";
} else {
// map REST response data to presentation messages.
switch (status) {
case 'ok':
statusHtml = "<span class='statusOk'>Email address is ok.</span>";
break;
case 'bad':
statusHtml = "<span class='statusBad'>Email address is not valid.</span>";
break;
default:
statusHtml = "<span class='statusUnknown'>Unable to validate email. Reason=" + additionalStatus + "</span>";
break;
}
}
console.log(statusHtml);
// present the result on screen
$('#validationResult').html(statusHtml);
}
</script>
</body>
</html>

Is that the output of your page as HTML or is that the code of the page itself?
All scripts should be loaded using the wp_enqueue_scripts() function which you use in your functions.php file.
You could use the following code:
function myScriptFunction() {
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/js/script.js',
array( 'jquery', true )
);
}
add_action( 'wp_enqueue_scripts', 'myScriptFunction' );
This tells WordPress to load your custom script, where it is located, that it depends on jQuery, and that it should be loaded in the footer.
WordPress loads jQuery in noconflict mode so it will not recognize "$" so instead use jQuery.

Related

Fiber web framework can not send ajax request

Forgive me, but I do not know English well. I use the translator deepl.com. At this point Russian programmers could not help me.
I am not a programmer, "I program only for myself". I have a problem - I can't send POST (JSON) request to server.
What I want to do - the server at Fiber which takes via POST request (JSON, XMLHttpRequest) 2 parameters from html page and after processing server gives me one string.
I use Fiber because I once made a small static site for myself, and there in the "examples" was all clear. I did a quick ctrl+C - ctrl+V, just tweaked my code. Then I tweaked the html, js, css. And I have a working site! :-)
main.go - start the server (no problems here)
package main
import (
"github.com/gofiber/fiber"
"github.com/gofiber/fiber/middleware/logger"
)
func main() {
app := fiber.New()
app.Use(logger.New())
app.Static("/", ".")
app.Get("/", func(c *fiber.Ctx) error {
return c.SendFile("./main.html")
})
app.Post("/search", PostTodo)
app.Listen(":3003")
}
search.go - logic on what to do after receiving the data. (so far just a kind of template, there is a small problem, but it mostly works).
package main
import (
"fmt"
"github.com/gofiber/fiber"
)
type Response_JSON struct {
Name string `json:"name"`
Surname string `json:"surname"`
}
func PostTodo(c *fiber.Ctx) error {
type request struct {
Name string `json:"name"`
Surname string `json:"surname"`
}
var body request
err := c.BodyParser(&body)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "Cannot parse JSON",
})
}
fmt.Println("body: ", err)
todo := Response_JSON{
Name: body.Name,
Surname: body.Surname,
}
fmt.Println("todo: ", todo)
my_request := "<div>" + todo.Name + "</div>"
my_request = my_request + "<hr><div>" + todo.Surname + "</div>"
return c.SendString(my_request)
}
main.html - home page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Proba</title>
</head>
<body>
<div class="container">
<div class="logo">
<h1>Proba</h1>
</div>
<form action="/search" class="search_form" method="POST">
<div class="search">
<input type="text" id="search_name" value="" name="search_name" placeholder="Search name...">
<input type="text" id="search_surname" value="" name="search_surname" placeholder="Search surname...">
<input type="submit" id="send" class="search_button" value="Go">
</div>
</form>
<div id="result" class="result">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
main.js - script processing forms after clicking (the main problem here)
let mybutton = document.getElementById("send");
mybutton.addEventListener("click", () => {
let name = document.getElementById("search_name").value;
let surname = document.getElementById("search_surname").value;
let s = {};
s.name = `${name}`;
s.surname = `${surname}`;
let search_json = JSON.stringify(s);
console.log("s: ", s);
console.log("name: ", name);
console.log("surname: ", surname);
console.log("search_json ", search_json);
let request = new XMLHttpRequest();
request.open('POST','/search');
request.setRequestHeader('Content-type', 'application/json');
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200)
document.getElementById("result").innerHTML=request.responseText;
}
request.send(search_json);
});
main2.js - a trial js that works without "click" (through it I tried to understand where the problem is)
let user = {
name: "Ivan",
surname: "Ivanov"
};
console.log("user:", user);
let json = JSON.stringify(user);
console.log("json:", json);
let request = new XMLHttpRequest();
request.open("POST", "/search");
request.setRequestHeader('Content-type', 'application/json');
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200)
document.getElementById("result").innerHTML=request.responseText;
}
request.send(json);
What I have:
1 - I start the server and go to the main.html. I fill in the data and click on the button (submit (Go)) and I see this result. The request is not sent and also strangely enough line console.log("s: ", s); did not work (output in the console did not happen).
enter image description here
enter image description here
2 - However, if you use the script main2.js, which works immediately when the page loads, then everything seems to work. The data was sent and the server processed it and returned it to me.
Although, for some reason in the file search.go output fmt.Println("body: ", err) - "nil", but in the variable "body" is decoded query body (application/json) according to the documentation.
enter image description here
enter image description here
Please help me solve the problem. I spent 2 days looking for a solution to my problem on google, yandex, youtube, but I could not find a solution to my problem.
I will be grateful to you in advance for the answer!
The issue you are seeing isn't related to Go (or even Fiber), it's because your form is being posted immediately, the javascript doesn't get a chance to fire.
You need to add preventDefault(); to stop the event "bubbling up" and triggering a form submit.
// Bind the call to the variable 'e'
mybutton.addEventListener("click", (e) => {
// Add this line!
e.preventDefault();
/* ... the rest is the same ... */

Why my postMessage does not working properly?

I have a index page contains the iframe element, this iframe refer to another DOMAIN page.
and i need to get the data from iframe page, so i applied the postmessage concept.
but it does not working.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Using PostMessage for Cross-Domain Access to an Iframe</title>
<meta name="description" content="Example demonstrates using postMessage to interact with an iframe on another domain and obtain information about its objects and properties." />
<script type="text/javascript">
// check for browser support
if ( window.addEventListener ) {
// when DOM is ready assign button onclick handlers
window.addEventListener('DOMContentLoaded', function() {
// where to send messages with postMessage
var target_origin = 'Myiframe.html';
// get reference to form to attach button onclick handlers
var form = document.getElementById('demoForm');
// get reference to iframe window
var win = document.getElementById('ifrm').contentWindow;
// set height of iframe and display value
form.elements.button1.onclick = function() {
var ifrm = document.getElementById('ifrm');
var ht = ifrm.style.height = '160px';
this.form.display.value = 'The iframe\'s height is: ' + ht;
}
// to increment and display counter variable in iframed document
form.elements['button2'].onclick = function() {
win.postMessage( {'task': 'ctr'}, target_origin );
}
// to get value of form element in iframed document
form.elements.button3.onclick = function() {
win.postMessage( {'task': 'val'}, target_origin );
}
// to invoke function in iframed document
form.elements.button4.onclick = function() {
win.postMessage( {'task': 'clear'}, target_origin );
}
}, false);
// message handler
window.addEventListener('message', function (e) {
// check message origin
if ( e.origin === 'Myiframe.html' ) {
var task = e.data['task']; // task received in postMessage
// get reference to demo form
var form = document.getElementById('demoForm');
switch ( task ) { // postMessage tasks
// display counter received in postMessage
case 'ctr' :
form.display.value = 'counter in iframe is: ' + e.data['counter'];
break;
// display text box value received in postMessage
case 'val' :
form.display.value = 'The greeting is: ' + e.data['val'];
break;
case 'clear' :
// nothing to do for this one
break;
//default:
}
}
}, false);
}
</script>
</head>
<body>
<form id="demoForm" action="#">
<p>
<input name="button1" type="button" value="Button 1" />
<input name="button2" type="button" value="Button 2" />
<input name="button3" type="button" value="Button 3" />
<input name="button4" type="button" value="Button 4" />
</p>
<p><input type="text" name="display" size="30" readonly="readonly" /></p>
</form>
<iframe name="ifrm" id="ifrm" src="Myiframe.html"></iframe>
</body>
</html>
Myiframe.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>untitled</title>
<meta name="robots" content="noindex" />
<script type="text/javascript">
// example variable and function for cross-document demo
counter = 0;
function clearGreeting() {
document.forms['iframeDemoForm'].elements['greeting'].value = '';
}
// check for browser support
if ( window.addEventListener ) {
// message handler
window.addEventListener('message', function(e) {
// check message origin
if ( e.origin === 'index.html' ) {
var task = e.data['task']; // task received in postMessage
var msg; // for postMessage reply to e.source
switch ( task ) { // postMessage tasks
// increment counter variable and send
case 'ctr' :
msg = { 'task': 'ctr', 'counter': ++counter };
e.source.postMessage(msg , e.origin );
break;
// send value of entry in text box (validate first)
case 'val' :
var re = /[^-a-zA-Z!,'?\s]/g; // to filter out unwanted characters
var fld = document.forms['iframeDemoForm'].elements['greeting'];
var val = fld.value.replace(re, '');
var msg = {'task': 'val', 'val': val};
e.source.postMessage(msg , e.origin );
break;
// clear text box by calling function
case 'clear' :
clearGreeting();
break;
//default:
}
}
}, false);
}
</script>
</head>
<body>
<h1>Iframe</h1>
<ul>
<li>Button 1 sets iframe style height</li>
<li>Button 2 increments global variable in iframed document</li>
<li>Button 3 transfers Greeting below to text box above iframe</li>
<li>Button 4 clears Greeting text box below (calls function in iframe)</li>
</ul>
<form action="#" id="iframeDemoForm">
<label for="greeting">Enter a Greeting: </label>
<input type="text" name="greeting" id="greeting" value="Hello there!" />
</form>
<script type="text/javascript">
(function() {
// disable submission of all forms on this page
for (var i=0, len=document.forms.length; i<len; i++) {
document.forms[i].onsubmit = function() { return false; };
}
}());
</script>
<p id="demoInfo"><span class="news">Note</span>: This page is part of a tutorial on postMessage and is intended to display in an iframe. Click here to see it in its proper context.</p>
<script type="text/javascript">
// if not in iframe, display link to tutorial
if ( self === top ) {
document.getElementById('demoInfo').style.display = 'block';
}
</script>
</body>
</html>
I appled some operation when buttoon is fired, ut nothing will work except the first button.
what i make mistake and guide me plz
The target origin is not specified properly.
Refer origin specifications here, https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage .
The origin of the window that sent the message at the time postMessage was called. This string is the concatenation of the protocol and "://", the host name if one exists, and ":" followed by a port number if a port is present and differs from the default port for the given protocol. Examples of typical origins are https://example.org (implying port 443), http://example.net (implying port 80), and http://example.com:8080. Note that this origin is not guaranteed to be the current or future origin of that window, which might have been navigated to a different location since postMessage was called.

Fill different data of the same form multiple times and auto submit to google sheet

I have one some data need transfer to array, and send it to google sheet
Data look like below
-|PO: 2005 |
12121211212121,| Qty: 45|
BIN:110|
eBay| 11/6/2017-|
PO: 2165 |
333333333,| Qty: 54|
BIN:20|
google| 11/6/2017-|
First I user JS transfer to array, and I put all data from array to form, and click submit form.
Array like
(6) ["PO: 2005 ", " 12121211212121,", " Qty: 45", " BIN:110", " eBay", " 11/6/2017"]
index.html:62
(6) [" PO: 2165 ", " 333333333,", " Qty: 54", " BIN:20", " google", " 11/6/2017"]
The form should be submitted multiple times, but on the google sheet I only got the data for the first one
This is my main HTML
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//
$(document).ready(function() {
//
$('#googleSheetInsert').bootstrapValidator({
//submitButtons: '#postForm',
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
})
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
var url = ' ';
var redirectUrl = 'index.html';
// show the loading
$('#postForm').prepend($('<span></span>').addClass('glyphicon glyphicon-refresh glyphicon-refresh-animate'));
var jqxhr = $.post(url, $form.serialize(), function(data) {
console.log("Success! Data: " + data.statusText);
// $(location).attr('href',redirectUrl); relocation
})
.fail(function(data) {
console.warn("Error! Data: " + data.statusText);
// HACK - check if browser is Safari - and redirect even if fail b/c we know the form submits.
if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
//alert("Browser is Safari -- we get an error, but the form still submits -- continue.");
$(location).attr('href',redirectUrl);
}
});
});
});
<html>
<head>
<title>Getting Started Extension's Popup</title>
<link href="http://cdn.jsdelivr.net/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="http://cdn.jsdelivr.net/fontawesome/4.1.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="http://cdn.jsdelivr.net/jquery.bootstrapvalidator/0.5.0/css/bootstrapValidator.min.css"/>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.bootstrapvalidator/0.5.0/js/bootstrapValidator.min.js"></script>
<style type="text/css">
body {
margin: 10px;
white-space: nowrap;
}
h1 {
font-size: 15px;
}
#container {
align-items: center;
display: flex;
justify-content: space-between;
}
</style>
<!--
- JavaScript and HTML must be in separate files: see our Content Security
- Policy documentation[1] for details and explanation.
-
- [1]: https://developer.chrome.com/extensions/contentSecurityPolicy
-->
<script>
function submitDataToGoogleSheet(){
var dataFromInput = document.getElementById("SOS_POData").value;
// Split by -| and put to array
var filter0 = dataFromInput.split("-|");
// Remove Empty Element
var unitArray =[];
for(var i=0;i<filter0.length;i++){
if(filter0[i]!==""){
unitArray.push(filter0[i].split("|"));
}
}
// insert data to google sheet
for(j=0;j<unitArray.length;j++){
doSubmite(unitArray,j);
}
}
function doSubmite(unitArray,j){
console.log(unitArray[j]);
document.getElementById('PO_Number').value = ((unitArray[j][0]).substring(4)).replace(/(^\s*)|(\s*$)/g,"");
document.getElementById('Part_Number').value = (unitArray[j][1]).replace(/(^\s*)|(\s*$)/g,"");
document.getElementById('Qty').value = ((unitArray[j][2]).substring(5)).replace(/(^\s*)|(\s*$)/g,"");
document.getElementById('BIN').value = (unitArray[j][3]).substring(5);
document.getElementById('Receiver_Name').value = (unitArray[j][4]).replace(/(^\s*)|(\s*$)/g,"");
document.getElementById('Receiver_Data').value = (unitArray[j][5]).replace(/(^\s*)|(\s*$)/g,"");
document.getElementById('postForm').click();
}
</script>
</head>
<body>
<h1>Please copy all information from laeb in there.</h1>
<div id="container">
<form id="dataFromSOS" action="#" method="post">
<input type="text" name="SOS_POData" id="SOS_POData" required="" placeholder="Please copy all label information in there">
<input type="button" name="submit_form" value="Submite" onclick="submitDataToGoogleSheet()">
</form >
</div>
<div>
<form id="googleSheetInsert">
<label>PO</label>
<input id='PO_Number' name='PO_Number' type='text'>
<label>PartNumber</label>
<input id='Part_Number' name='Part_Number' type='text'>
<label>Qty</label>
<input id='Qty' name='Qty' type='text'>
<label>BIN</label>
<input id='BIN' name='BIN' type='text'>
<label>Receiver_Name</label>
<input id='Receiver_Name' name='Receiver_Name' type='text'>
<label>Receiver_Data</label>
<input id='Receiver_Data' name='Receiver_Data' type='text'>
<input type="submit" name="submit" id="postForm" />
</form>
</div>
<script src="js/sendDataToGoogleSheedAjax.js"></script>
</body>
</html>
Did you set up the Google Sheet to handle your forms being submitted at the same time?
You might follow the below example:
https://medium.com/#dmccoy/how-to-submit-an-html-form-to-google-sheets-without-google-forms-b833952cc175
As far as your multiple submits, they seem to be working as far as I can tell (without a sheet to submit to). If I step through the code I can see the form being updated with the values and everything seems parsed okay. Which is what leaves me to believe the problem is on the receiving side.
To get it to work for me I did the following:
Have your names in the google sheet columns and form <input name=""> match.
In your google sheets go to Tools->Script editor and insert the script from here: https://gist.github.com/mhawksey/1276293
In the script editor Do Run->Run Function->setup
In the script editor Do Publish->Deploy as web app...
set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
Be sure to note the url as that's what we will POST to
It should look like https://script.google.com/macros/s/<GIBERISH>/exec
Update how you call the ajax POST function (I couldn't get the bootstrap validator to work. In fact it was causing only 1 POST to be sent, so I just removed it and everything functions as expected.)
Code:
$('#googleSheetInsert').on('submit', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Use Ajax to submit form data
var url = 'https://script.google.com/macros/s/<GIBERISH>/exec';
var redirectUrl = 'index.html';
// show the loading
$('#postForm').prepend($('<span></span>').addClass('glyphicon glyphicon-refresh glyphicon-refresh-animate'));
var jqxhr = $.post(url, $form.serialize(), function(data) {
console.log("Success! Data: " + data.statusText);
// $(location).attr('href',redirectUrl); relocation
})
.fail(function(data) {
console.warn("Error! Data: " + data.statusText);
// HACK - check if browser is Safari - and redirect even if fail b/c we know the form submits.
if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
//alert("Browser is Safari -- we get an error, but the form still submits -- continue.");
$(location).attr('href',redirectUrl);
}
});
});
Images Showing the working code:
Submitting your test data a couple times
Form updated

PHP not working on js form

I have a form on my website(http://hokuco.com/test/). It creates a folder with php, but ever since I installed a javascript my php is not working. The javascript redirects to the folder the php creates. Ironically, before I made the javascript work, the php works.
focus on the area between the two barriers that look like this:
<!--===========-->
index.php:
<?php
function recurse_copy($src,$dst) {
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
$src = "./xe7";
$dst = $_POST['foldername'];
recurse_copy($src,$dst);
?>
<link rel="stylesheet" type="text/css" href="style.css" />
<div>
<body onload="timer=setTimeout('removeControls();',3)">
<h1>Drawblog</h1>
<div class="FAQ" style ="box-shadow: 1px 1px 3px rgba(0,0,0,0);">
Controls
-
<div class="list" style ="box-shadow: 1px 1px 3px rgba(0,0,0,0);">
<!--===========-->
<form method="post" id ="form" action ="index.php">
<input type="text" name="foldername" id ="togl">
<input type="submit" name="submit" value="Create panorama">
<script type="text/javascript">
window.onload = function () {
document.getElementById("form").onsubmit = function () {
var folder = document.getElementById("togl").value;
window.location.href ="http://hokuco.com/test/" + folder + "/toggle.php";
return false;
}
}
</script>
</form>
<!--===========-->
<h3>Or,</h3>
<h2>Login with an access code(the account you just typed into the box above, or a code someone shared with you)</h2>
<input type="text" id="field" />
<button id="submit">Go</button>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
document.getElementById("submit").addEventListener("click", function(){
var folder = document.getElementById("field").value;
var url = "http://hokuco.com/test/" + folder + "/index.html";
window.location.href = url;
});
</script>
</div>
</div>
<h1> </h1>
<h1> </h1>
<p>make shocking panoramas in minutes, no account needed</p>
<br/>
<br/>
<br/>
<br/>
<p>special thanks to:</p>
<div id="info">three.js css3d - panorama.</div>
<h5>a hokuco company</h5>
</div>
You are redirecting the user when the on-submit button is pressed. This happens instead of submitting the form.
If you want to submit the form, wait till it's work is done, and then redirect the user to the new location, you could use AJAX to submit the form, and a callback to redirect the user once it's done. See this: submit the form using ajax
Alternatively you could just use a php redirect in the page form submits to, and send the user there. Since this page is both the form and the submit target you could use something like:
if (isset($_POST['foldername'])) {
$dst = $_POST['foldername'];
recurse_copy($src, $dst);
$destURL = "http://hokuco.com/test/".$dst."/toggle.php";
header('Location: '.$destURL);
die('redirecting, please wait. Alternatively use this url: '.$destURL);
}
This is very rudimentary and dangerous, since you are not cleaning the user input for the folder name (See this: Regular expression for folders), however it may help you understand the concept, in order to get to the next step.
<form method="post" id ="form" action ="index.php">
<input type="text" name="foldername" id ="togl">
<input type="submit" name="submit" value="Create panorama">
</form>
Alright. Before you added JS code, your form used to be submitted to index.php when the user pressed the submit button.
However, now you have added a handler to onsubmit event for this form.
<script type="text/javascript">
window.onload = function () {
document.getElementById("form").onsubmit = function () {
var folder = document.getElementById("togl").value;
window.location.href ="http://hokuco.com/test/" + folder + "/toggle.php";
return false;
}
}
</script>
Note that your handler returns false, thus suppressing the default behaviour of form submission. Indeed, it needs to return false to be able to perform redirection.
However, now that you've introduced your own onsubmit handler, you need to provide your own custom JavaScript code to submit form. One way to do so, using jQuery, is like this:
<script type="text/javascript">
window.onload = function () {
document.getElementById("form").onsubmit = function () {
// Submit form to index.php
$.post('index.php', $('#form').serialize(), function() {
// Perform redirection, once submission succeeds
var folder = document.getElementById("togl").value;
window.location.href ="http://hokuco.com/test/" + folder + "/toggle.php";
});
return false;
}
}
</script>
You might also want to consider removing JS handler altogether and instead implementing redirection logic in PHP.

youtube api v3 search by keyword javascript

The javascript example for "search by keyword" that is given at the google developers page isn't working for me. https://developers.google.com/youtube/v3/code_samples/javascript
When I run the code, I get a disabled search box with "cats" inside. Also, the example doesn't explain how to write in the API key as opposed to the Client ID. It says it's possible, but gives no concrete example of how to do it. Can someone point out where this code is going wrong. The code for the two .js files and the html is as follows:
auth.js file:
// The client ID is obtained from the Google Developers Console
// at https://console.developers.google.com/.
// If you run this code from a server other than http://localhost,
// you need to register your own client ID.
var OAUTH2_CLIENT_ID = '__YOUR_CLIENT_ID__';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
// Upon loading, the Google APIs JS client automatically invokes this callback.
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
}
// Attempt the immediate OAuth 2.0 client flow as soon as the page loads.
// If the currently logged-in Google Account has previously authorized
// the client specified as the OAUTH2_CLIENT_ID, then the authorization
// succeeds with no user intervention. Otherwise, it fails and the
// user interface that prompts for authorization needs to display.
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
// Handle the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
$('.pre-auth').hide();
$('.post-auth').show();
loadAPIClientInterfaces();
} else {
// Make the #login-link clickable. Attempt a non-immediate OAuth 2.0
// client flow. The current function is called when that flow completes.
$('#login-link').click(function() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
});
}
}
// Load the client interfaces for the YouTube Analytics and Data APIs, which
// are required to use the Google APIs JS client. More info is available at
// http://code.google.com/p/google-api-javascript-client /wiki/GettingStarted#Loading_the_Client
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
handleAPILoaded();
});
}
search.js file:
// After the API loads, call a function to enable the search box.
function handleAPILoaded() {
$('#search-button').attr('disabled', false);
}
// Search for a specified string.
function search() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
$('#search-container').html('<pre>' + str + '</pre>');
});
}
search.html
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="buttons">
<label> <input id="query" value='cats' type="text"/><button id="search-button" disabled onclick="search()">Search</button></label>
</div>
<div id="search-container">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="auth.js"></script>
<script src="search.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
</body>
</html>
The documentation is misleading a bit (one might even say incorrect); the HTML for the "search by keyword" is loading the same "auth.js" that the other two examples on that page are, but it doesn't then have any HTML elements to actually trigger the login process (i.e. a "login button" if a user isn't already authorized) like the other two examples do. Bascially, if you're using that provided auth.js, you need to have, in your HTML, a section that looks like this:
<div id="login-container" class="pre-auth">
This application requires access to your YouTube account.
Please authorize to continue.
</div>
Then, you can also add the class of "post-auth" on a new div that wraps around your existing buttons and search container. The demo will then, when a user visits, only present the login link; when clicked on, and when a user allows the authorization, then the login link will be hidden and your search area will be shown (and the button enabled). That's just how the demo is set up.
Of course, search by keyword does NOT require oAuth2, and so (to answer your 2nd question) you might find it easier to A) remove the handleApiLoaded method (so your button is never disabled), and B) call gapi.client.load() manually (i.e. not triggered by an oAuth success). Then, call gapi.client.setApiKey({YOUR KEY}) so that all of your requests will include your key in their header.
Thanks so much jlmcdonald for your help. It took me a while to figure out the second part of your response, but I finally had success. The following html gets the example on the google developers webpage to work. Note though, at first I was getting a 401 error. To fix it, I had to go to the google developers console and select my project. Then, APIs&auth->consent screen and then fill in the email address and product name:
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="login-container" class="pre-auth">
This application requires access to your YouTube account.
Please authorize to continue.
</div>
<div id="buttons" class="post-auth">
<label> <input id="query" value='cats' type="text"/><button id="search-button" disabled onclick="search()">Search</button></label>
</div>
<div id="search-container">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="/files/theme/auth.js"></script>
<script src="/files/theme/search.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
</body>
</html>
As you noted in your response, oAuth2 isn't necessary for a simple keyword search. The following is some html that just uses the API key. I didn't reference the two .js files like before, rather, I just included the script in the html. Your post at gapi.client.youtube is undefined? really helped me figure it out:
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="buttons">
<label> <input id="query" value='cats' type="text"/><button id="search-button" onclick="keyWordsearch()">Search</button></label>
</div>
<div id="search-container">
</div>
<script>
function keyWordsearch(){
gapi.client.setApiKey('API key here');
gapi.client.load('youtube', 'v3', function() {
makeRequest();
});
}
function makeRequest() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
$('#search-container').html('<pre>' + str + '</pre>');
});
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
</body>
</html>
Now that I got the search part, could you explain how I can display the thumbnails and titles of the results and then when I click them, the video opens in an embedded player on the same page? Thanks.
Thank you for your coding. Let me share my code:
function makeRequest(){
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response){
var str = JSON.stringify(response.result,'',4);
$('#search-container').val( str);
makeControl(response);
});
}
function makeControl(resp){
var stList = '<table id="res1" border="1" cellspacing="1" width="100%"><tbody>';
for (var i=0; i<resp.items.length;i++){
var vid = resp.items[i].id.videoId;
var tit = resp.items[i].snippet.title;
if(typeof vid != 'undefined'){
stList += '<tr><td style="width:80px;vertical-align:top">'+
'<a class="show" href="#" title="'+ vid + '" onclick="playVid(this);'+
' return false">'+
'<img width="80" height="60" src="http://img.youtube.com/vi/'+
vid +'/default.jpg"></a></td>'+
'<td><b>'+i+'</b>-'+ tit +'</td></tr>';
}
}
document.getElementById('list1').innerHTML = stList + '</tbody></table>';
//HTML: <div id="list1"
//style="width:853px;height:400px;overflow:auto;background-color:#EEEEEE">
//</div>
}
function playVid(thi){
var st = 'https://www.youtube.com/embed/'+thi.title+'?autoplay=1';
document.getElementById('player').src = st;
//HTML: <iframe id="player" width="853" height="480" src="" frameborder="1" allowfullscreen>
//</iframe>
}

Categories