I'm currently working on building a Ambient Sound Generator for a college project and am running into a slight issue.
Basically I currently have 3 different files the user can pause/play in combination, and each pause/play ok. The only issue is that if I play more than one sound at a time, one of my 2 sounds continues to play after I've hit stop.
Maybe someone can point me in the direction of where I'm going wrong and/or to resources where I can learn more about the API.
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/loopy_styles.css" />
<!--<script type="text/javascript" src="js/loop_functions.js"></script>-->
<script>
context = new (window.AudioContext || window.webkitAudioContext)();
var soundBuffer1 = null;
var soundBuffer2 = null;
var soundBuffer3 = null;
var soundBuffer4 = null;
var soundBuffer5 = null;
window.onload = function() {
create_buffers();
};
function create_buffers(){
soundBufferSourceNode1 = context.createBufferSource();
soundBufferSourceNode1.looping = true;
soundBufferSourceNode2 = context.createBufferSource();
soundBufferSourceNode2.looping = true;
soundBufferSourceNode3 = context.createBufferSource();
soundBufferSourceNode3.looping = true;
soundBufferSourceNode4 = context.createBufferSource();
soundBufferSourceNode4.looping = true;
soundBufferSourceNode5 = context.createBufferSource();
soundBufferSourceNode5.looping = true;
};
loadSound('sounds/fire_test1.wav', 1);
loadSound('sounds/wind_test.wav', 2);
loadSound('sounds/rain_test1.wav', 3);
loadSound('sounds/stream.mp3', 4);
loadSound('sounds/spring_test.wav', 5);
function play_sound1(){
document.getElementById('playBtn1_play').style.display = 'none';
document.getElementById('playBtn1_stop').style.display = 'block';
playSound(soundBuffer1, soundBufferSourceNode1);
}
function stop_sound1(){
document.getElementById('playBtn1_play').style.display = 'block';
document.getElementById('playBtn1_stop').style.display = 'none';
stopSound(soundBufferSourceNode1);
create_buffers();
}
function play_sound2(){
document.getElementById('playBtn2_play').style.display = 'none';
document.getElementById('playBtn2_stop').style.display = 'block';
playSound(soundBuffer2, soundBufferSourceNode2);
p2=true;
};
function stop_sound2(){
document.getElementById('playBtn2_play').style.display = 'block';
document.getElementById('playBtn2_stop').style.display = 'none';
p2=false;
stopSound(soundBufferSourceNode2);
create_buffers();
};
function play_sound3(){
document.getElementById('playBtn3_play').style.display = 'none';
document.getElementById('playBtn3_stop').style.display = 'block';
p3=true;
playSound(soundBuffer3, soundBufferSourceNode3);
}
function stop_sound3(){
document.getElementById('playBtn3_play').style.display = 'block';
document.getElementById('playBtn3_stop').style.display = 'none';
p3=false;
stopSound(soundBufferSourceNode3);
create_buffers();
}
function playSound(buffer, bufferSourceNode) {
bufferSourceNode.buffer = buffer;
bufferSourceNode.connect(context.destination);
bufferSourceNode.noteOn(0);
};
function stopSound(bufferSourceNode) {
bufferSourceNode.noteOff(0);
};
function loadSound(url, bufferNum) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
var successCallback = function(buffer) {
switch(bufferNum) {
case 1:
soundBuffer1 = buffer;
break;
case 2:
soundBuffer2 = buffer;
break;
case 3:
soundBuffer3 = buffer;
break;
case 4:
soundBuffer4 = buffer;
break;
case 5:
soundBuffer5 = buffer;
break;
}
}
var errorCallback = function(e) {
console.log(e);
}
context.decodeAudioData(request.response, successCallback, errorCallback);
}
request.send();
}
</script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>Ambient Sound Generator</title>
</head>
<body>
<div class="background">
<div id="intro-text">
<h1 id="site-title">Ambient Sound Generator</h1>
<p>Mix ambient sounds together to block out distractions and help you focus or relax</p>
<p>Click the buttons below to begin</p>
</div>
<div id="button-container">
<div id="btn1">
<input type="image" class="pp_img" src="img/fire-pause.png" name="Fire" id="playBtn1_play" onclick="play_sound1();" />
<input type="image" class="pp_img" src="img/fire-play.png" name="Fire" id="playBtn1_stop" onclick="stop_sound1();" style="display:none" />
<p><input type="range" min="0" max="100" value="100" onchange="sample.changeVolume();"> Volume</p>
</div>
<div id="btn2">
<input type="image" class="pp_img" src="img/wind-pause.png" name="Wind" id="playBtn2_play" onclick="play_sound2();" />
<input type="image" class="pp_img" src="img/wind-play.png" name="Wind" id="playBtn2_stop" onclick="stop_sound2();" style="display:none" />
<p><input type="range" min="0" max="100" value="100" onchange="sample.changeVolume();"> Volume</p>
</div>
<div id="btn3">
<input type="image" class="pp_img" src="img/rain-pause.png" name="Rain" id="playBtn3_play" onclick="play_sound3();"/>
<input type="image" class="pp_img" src="img/rain-play.png" name="Rain" id="playBtn3_stop" onclick="stop_sound3();" style="display:none"/>
<p><input type="range" min="0" max="100" value="100" onchange="sample.changeVolume();"> Volume</p>
</div>
<div id="btn4">
<input type="image" class="pp_img" src="img/stream-pause.png" name="Stream" id="playBtn4_play" onclick="play_sound4();"/>
<input type="image" class="pp_img" src="img/stream-play.png" name="Stream" id="playBtn4_stop" onclick="stop_sound4();" style="display:none"/>
<p><input type="range" min="0" max="100" value="100" onchange="sample.changeVolume();"> Volume</p>
</div>
<div id="btn5">
<input type="image" class="pp_img" src="img/forest-pause.png" name="Rain" id="playBtn5_play" onclick="play_sound5();"/>
<input type="image" class="pp_img" src="img/forest-play.png" name="Rain" id="playBtn5_stop" onclick="stop_sound5();" style="display:none" />
<p><input type="range" min="0" max="100" value="100" onchange="sample.changeVolume();"> Volume</p>
</div>
</div>
</div>
</body>
<script>
function refreshData(){
x = 1; // x = seconds
var d = new Date()
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
if (h<=9) {h = '0'+h};
if (m<=9) {m = '0'+m};
if (s<=9) {s = '0'+s};
var color = '#'+h+m+s;
$("div.background").css("background-color", color );
$("p#hex").text(color);
setTimeout(refreshData, x*1000);
}
refreshData(); // execute function
</script>
You need to cache any currently-playing sound in playSound, and stop it prior to starting a new one.
You shouldn't create all those buffersourcenodes before the fact; just create one when you want to start playing.
Also, you should use start() and stop(), not noteOn() and noteOff() - the latter are deprecated.
Try this:
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/loopy_styles.css" />
<!--<script type="text/javascript" src="js/loop_functions.js"></script>-->
<script>
context = new (window.AudioContext || window.webkitAudioContext)();
var soundBuffers = [null,null,null,null,null,null]; // extra entry in array as dummy '0' entry
window.onload = function() {
loadSound('sounds/fire_test1.wav', 1);
loadSound('sounds/wind_test.wav', 2);
loadSound('sounds/rain_test1.wav', 3);
loadSound('sounds/stream.mp3', 4);
loadSound('sounds/spring_test.wav', 5);
};
var currentlyPlayingSoundNum = 0;
var currentlyPlayingSound = null;
function play_sound(num){
stop_any_currently_playing_sound();
if (num) {
document.getElementById('playBtn'+num+'_play').style.display = 'none';
document.getElementById('playBtn'+num+'_stop').style.display = 'block';
currentlyPlayingSoundNum = num;
currentlyPlayingSound = context.createBufferSource();
currentlyPlayingSound.looping = true;
currentlyPlayingSound.buffer = soundBuffers[num];
currentlyPlayingSound.connect(context.destination);
currentlyPlayingSound.start(0);
}
}
function stop_sound(){
if (currentlyPlayingSound) {
document.getElementById('playBtn'+currentlyPlayingSoundNum+'_play').style.display = 'block';
document.getElementById('playBtn'+currentlyPlayingSoundNum+'_stop').style.display = 'none';
currentlyPlayingSound.stop(0);
currentlyPlayingSound = null;
currentlyPlayingSoundNumber = 0;
}
}
function loadSound(url, bufferNum) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
var successCallback = function(buffer) {
soundBuffers[bufferNum] = buffer;
}
var errorCallback = function(e) {
console.log(e);
}
context.decodeAudioData(request.response, successCallback, errorCallback);
}
request.send();
}
</script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>Ambient Sound Generator</title>
</head>
<body>
<div class="background">
<div id="intro-text">
<h1 id="site-title">Ambient Sound Generator</h1>
<p>Mix ambient sounds together to block out distractions and help you focus or relax</p>
<p>Click the buttons below to begin</p>
</div>
<div id="button-container">
<div id="btn1">
<input type="image" class="pp_img" src="img/fire-pause.png" name="Fire" id="playBtn1_play" onclick="play_sound(1);" />
<input type="image" class="pp_img" src="img/fire-play.png" name="Fire" id="playBtn1_stop" onclick="stop_sound();" style="display:none" />
<p><input type="range" min="0" max="100" value="100" onchange="sample.changeVolume();"> Volume</p>
</div>
<div id="btn2">
<input type="image" class="pp_img" src="img/wind-pause.png" name="Wind" id="playBtn2_play" onclick="play_sound(2);" />
<input type="image" class="pp_img" src="img/wind-play.png" name="Wind" id="playBtn2_stop" onclick="stop_sound();" style="display:none" />
<p><input type="range" min="0" max="100" value="100" onchange="sample.changeVolume();"> Volume</p>
</div>
<div id="btn3">
<input type="image" class="pp_img" src="img/rain-pause.png" name="Rain" id="playBtn3_play" onclick="play_sound(3);"/>
<input type="image" class="pp_img" src="img/rain-play.png" name="Rain" id="playBtn3_stop" onclick="stop_sound();" style="display:none"/>
<p><input type="range" min="0" max="100" value="100" onchange="sample.changeVolume();"> Volume</p>
</div>
<div id="btn4">
<input type="image" class="pp_img" src="img/stream-pause.png" name="Stream" id="playBtn4_play" onclick="play_sound(4);"/>
<input type="image" class="pp_img" src="img/stream-play.png" name="Stream" id="playBtn4_stop" onclick="stop_sound();" style="display:none"/>
<p><input type="range" min="0" max="100" value="100" onchange="sample.changeVolume();"> Volume</p>
</div>
<div id="btn5">
<input type="image" class="pp_img" src="img/forest-pause.png" name="Rain" id="playBtn5_play" onclick="play_sound(5);"/>
<input type="image" class="pp_img" src="img/forest-play.png" name="Rain" id="playBtn5_stop" onclick="stop_sound();" style="display:none" />
<p><input type="range" min="0" max="100" value="100" onchange="sample.changeVolume();"> Volume</p>
</div>
</div>
</div>
</body>
<script>
function refreshData(){
x = 1; // x = seconds
var d = new Date()
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
if (h<=9) {h = '0'+h};
if (m<=9) {m = '0'+m};
if (s<=9) {s = '0'+s};
var color = '#'+h+m+s;
$("div.background").css("background-color", color );
$("p#hex").text(color);
setTimeout(refreshData, x*1000);
}
refreshData(); // execute function
</script>
Related
I am new in node js and trying to integrate single file upload using dropzone js. I want to upload image before submitting form. I have managed to call the upload action before submitting.
Here is my html code:
<form id="add_user" name="add_user" class="form-horizontal" action="/add-new-user" method="POST">
<div class="directory-bg text-center">
<div class="directory-overlay">
<span id="imageuploader">
<input name="profileimg" id="profileimg" type="hidden" value="">
<img id="ws_user_avatar" class="rounded-circle thumb-lg img-thumbnail dropzone" data-thumb="public/assets/images/users/user.png" src="public/assets/images/users/user.png" alt="Generic placeholder image">
<!--<div class="fallback">
<input name="image" id="image" type="file">
</div>-->
x
</span>
</div>
</div>
<div class="directory-content p-4">
<div class="mt-4">
<% if(success != "") {%>
<div class="alert alert-success" role="alert">
<strong>Done!</strong> <%= success %>
</div>
<% } %>
<div class="row">
<div class="col-md-12">
<div class="mb-3">
<label class="form-label" for="email">Email Address</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Email Address" data-key="Email Address" autocomplete="off" autofill="false">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label class="form-label" for="fname">First Name</label>
<input type="text" class="form-control" name="fname" id="fname" placeholder="First Name" data-key="First Name" autocomplete="off" autofill="false">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label class="form-label" for="lname">Last Name</label>
<input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" data-key="Last Name" autocomplete="off" autofill="false">
</div>
</div>
</div>
</div>
</div>
</form>
Here is the js code to handle dropzone event
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone(".dropzone", {
url: '/upload-image',
autoProcessQueue: false,
uploadMultiple: false,
maxFiles:2,
maxFilesize: 2,
createImageThumbnails:false,
hiddenInputContainer: "img.rounded-circle",
init: function(file) {
var prevFile = null;
this.on("addedfile", function(file) {
var $this = this;
setTimeout(function () {
if(file.status == "error"){
alert(file.previewTemplate.innerText);
} else {
if(prevFile){
$this.removeFile($this.files[0])
}
prevFile = file;
$("#user_avatar").attr('data-imgname', file.name);
previewImage($this);
}
}, 10);
});
}
});
function previewImage(input){
let fileReference = input.files && input.files[0];
if(fileReference){
var reader = new FileReader();
reader.onload = (event) => {
document.getElementById('user_avatar').src = event.target.result;
}
reader.readAsDataURL(fileReference);
}
}
$(document).on('click','#btn_submit', function(e){
e.preventDefault();
if(myDropzone.getQueuedFiles().length > 0){
myDropzone.processQueue();
} else {
$("#add_user").submit();
}
});
Here is the post handler code in router.js file:
const express = require('express');
const router = express.Router();
router.post('/upload-image', function(req, res){
console.log('requested inage',req.files.file.path);
// fs.readFile(request.files.file.path, function(err, data) {
// var newPath = __dirname + "/public/img/xspectra/customlogo.png";
// fs.writeFile(newPath, data, function (err) {
// console.log("Finished writing file..." + err);
// response.redirect("back");
// });
// });
});
When the dropzone myDropzone.processQueue() function called, I get an error message in the post handler function TypeError: Cannot read property 'file' of undefined.
Can anyone suggest me where I am doing wrong?
Many Thanks!
That means that the file uploaded didn't properly make it to your web server. Are you using express-fileupload on the nodejs side to handle the uploads?
If so, I recommend checking out this link on a really great tutorial
I have automated data entry in to webpage and in the last when I click submit button it shows one pop up in which the registration no. Generated is displayed.
I want to know is there any way I can copy that registration no and save it in excel.
Please find the pic attached.
[enter image description here][1]
[1]:
I did automated to click on submit button but after that how to read pop up have no idea where to begin, searched a lot on internet but didn't find what I was looking for.
https://i.stack.imgur.com/zMhX4.png
Please find HTML code on top there is button save named after clicking on which the pop is generated.
<input type="submit" name="ctl00$ContentPlaceHolder1$btnOk" value="Ok" id="ctl00_ContentPlaceHolder1_btnOk" class="btn" style="display:none;" />
</div>
<div id="ctl00_ContentPlaceHolder1_UpdateProgress" style="display:none;">
<img id="ctl00_ContentPlaceHolder1_Image1" src="images/loader.gif" alt="Processing" style="border-width:0px;" />
</div>
</td>
</tr>
</table>
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnVosFlag" id="ctl00_ContentPlaceHolder1_hdnVosFlag" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnLNEXP_TYPE" id="ctl00_ContentPlaceHolder1_hdnLNEXP_TYPE" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnHDRLNEXP_TYPE" id="ctl00_ContentPlaceHolder1_hdnHDRLNEXP_TYPE" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnPFID" id="ctl00_ContentPlaceHolder1_hdnPFID" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnpfRefNo" id="ctl00_ContentPlaceHolder1_hdnpfRefNo" value="0" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnflagNewPan" id="ctl00_ContentPlaceHolder1_hdnflagNewPan" value="N" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hndchkpan" id="ctl00_ContentPlaceHolder1_hndchkpan" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hndIsStatusEnabled" id="ctl00_ContentPlaceHolder1_hndIsStatusEnabled" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hndRetamt" id="ctl00_ContentPlaceHolder1_hndRetamt" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hndDdlNEFTAcc" id="ctl00_ContentPlaceHolder1_hndDdlNEFTAcc" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hndUsersol" id="ctl00_ContentPlaceHolder1_hndUsersol" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hndneft" id="ctl00_ContentPlaceHolder1_hndneft" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnAttchmentID" id="ctl00_ContentPlaceHolder1_hdnAttchmentID" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnPfLvl" id="ctl00_ContentPlaceHolder1_hdnPfLvl" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnvenStatus" id="ctl00_ContentPlaceHolder1_hdnvenStatus" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$TabName" id="ctl00_ContentPlaceHolder1_TabName" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnMode" id="ctl00_ContentPlaceHolder1_hdnMode" value="I" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$venid" id="ctl00_ContentPlaceHolder1_venid" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$siteid" id="ctl00_ContentPlaceHolder1_siteid" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdncrAcc" id="ctl00_ContentPlaceHolder1_hdncrAcc" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnNEFTAcc" id="ctl00_ContentPlaceHolder1_hdnNEFTAcc" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnduedtflag" id="ctl00_ContentPlaceHolder1_hdnduedtflag" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnpfidindex" id="ctl00_ContentPlaceHolder1_hdnpfidindex" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnlstPFids" id="ctl00_ContentPlaceHolder1_hdnlstPFids" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnUserType" id="ctl00_ContentPlaceHolder1_hdnUserType" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnDOPLimit" id="ctl00_ContentPlaceHolder1_hdnDOPLimit" value="1000000" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdn_IFSC_CODE" id="ctl00_ContentPlaceHolder1_hdn_IFSC_CODE" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdn_account_id" id="ctl00_ContentPlaceHolder1_hdn_account_id" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnExpenseSolId" id="ctl00_ContentPlaceHolder1_hdnExpenseSolId" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnOrgCreationDt" id="ctl00_ContentPlaceHolder1_hdnOrgCreationDt" />
<input type="hidden" name="ctl00$ContentPlaceHolder1$hdnChkerEin" id="ctl00_ContentPlaceHolder1_hdnChkerEin" />
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) { var oControl = args.get_postBackElement(); oControl.disabled = true; }
</script>
<script language="javascript" type="text/javascript">
function disposeTree(sender, args) {
var elements = args.get_panelsUpdating();
for (var i = elements.length - 1; i >= 0; i--) {
var element = elements[i];
var allnodes = element.getElementsByTagName('*'),
length = allnodes.length;
var nodes = new Array(length)
for (var k = 0; k < length; k++) {
nodes[k] = allnodes[k];
}
for (var j = 0, l = nodes.length; j < l; j++) {
var node = nodes[j];
if (node.nodeType === 1) {
if (node.dispose && typeof (node.dispose) === "function") {
node.dispose();
}
else if (node.control && typeof (node.control.dispose) === "function") {
node.control.dispose();
}
var behaviors = node._behaviors;
if (behaviors) {
behaviors = Array.apply(null, behaviors);
for (var k = behaviors.length - 1; k >= 0; k--) {
behaviors[k].dispose();
}
}
}
}
element.innerHTML = "";
}
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(disposeTree);
</script>
</td>
</tr>
</table>
</div>
<!-- #main (end) -->
</td>
</tr>
</table>
<!-- #wrapper (end) -->
<script type="text/javascript">Cufon.now();</script>
<script type="text/javascript">
//<![CDATA[
var ctl00_mnuCRM_Data = new Object();
ctl00_mnuCRM_Data.disappearAfter = 500;
ctl00_mnuCRM_Data.horizontalOffset = 0;
ctl00_mnuCRM_Data.verticalOffset = 0;
ctl00_mnuCRM_Data.hoverClass = 'ctl00_mnuCRM_14 hover';
ctl00_mnuCRM_Data.hoverHyperLinkClass = 'ctl00_mnuCRM_13 hover';
ctl00_mnuCRM_Data.staticHoverClass = 'ctl00_mnuCRM_12 statichover';
ctl00_mnuCRM_Data.staticHoverHyperLinkClass = 'ctl00_mnuCRM_11 statichover';
theForm.oldSubmit = theForm.submit;
theForm.submit = WebForm_SaveScrollPositionSubmit;
theForm.oldOnSubmit = theForm.onsubmit;
theForm.onsubmit = WebForm_SaveScrollPositionOnSubmit;
Sys.Application.add_init(function() {
$create(Sys.Extended.UI.CalendarBehavior, {"format":"dd/MM/yyyy","id":"ctl00_ContentPlaceHolder1_TextBox1_CalendarExtender"}, null, null, $get("ctl00_ContentPlaceHolder1_txtduedt"));
});
Sys.Application.add_init(function() {
$create(Sys.Extended.UI.AutoCompleteBehavior, {"completionInterval":10,"completionListCssClass":"autocomplete_completionListElement","completionListItemCssClass":"autocomplete_listItem","completionSetCount":20,"delimiterCharacters":"","highlightedItemCssClass":"autocomplete_highlightedListItem","id":"AutoCompleteVenEx","minimumPrefixLength":2,"onHide":"{\"AnimationName\":\"Parallel\",\"Duration\":\".4\",\"AnimationChildren\":[{\"AnimationName\":\"FadeOut\",\"AnimationChildren\":[]},{\"AnimationName\":\"Length\",\"PropertyKey\":\"height\",\"StartValueScript\":\"$find(\\u0027AutoCompleteVenEx\\u0027)._height\",\"EndValue\":\"0\",\"AnimationChildren\":[]}]}","onShow":"{\"AnimationName\":\"Sequence\",\"AnimationChildren\":[{\"AnimationName\":\"OpacityAction\",\"Opacity\":\"0\",\"AnimationChildren\":[]},{\"AnimationName\":\"HideAction\",\"Visible\":\"true\",\"AnimationChildren\":[]},{\"AnimationName\":\"ScriptAction\",\"Script\":\"\\r\\n // Cache the size and setup the initial size\\r\\n var behavior = $find(\\u0027AutoCompleteVenEx\\u0027);\\r\\n if (!behavior._height) {\\r\\n var target = behavior.get_completionList();\\r\\n behavior._height = target.offsetHeight - 2;\\r\\n target.style.height = \\u00270px\\u0027;\\r\\n }\",\"AnimationChildren\":[]},{\"AnimationName\":\"Parallel\",\"Duration\":\".4\",\"AnimationChildren\":[{\"AnimationName\":\"FadeIn\",\"AnimationChildren\":[]},{\"AnimationName\":\"Length\",\"PropertyKey\":\"height\",\"StartValue\":\"0\",\"EndValueScript\":\"$find(\\u0027AutoCompleteVenEx\\u0027)._height\",\"AnimationChildren\":[]}]}]}","serviceMethod":"GetVendorList","servicePath":"/rfp/frmGSTINPaymentformTax.aspx"}, {"itemSelected":SettxtVDName_hiddenValue,"populated":HidevenImage,"populating":ShowvenImage}, null, $get("ctl00_ContentPlaceHolder1_txtVDName"));
});
Sys.Application.add_init(function() {
$create(Sys.Extended.UI.CalendarBehavior, {"format":"dd/MM/yyyy","id":"ctl00_ContentPlaceHolder1_CalendarExtender1"}, null, null, $get("ctl00_ContentPlaceHolder1_txtInvoicedt"));
});
Sys.Application.add_init(function() {
$create(Sys.Extended.UI.CalendarBehavior, {"format":"dd/MM/yyyy","id":"ctl00_ContentPlaceHolder1_CalendarExtender2"}, null, null, $get("ctl00_ContentPlaceHolder1_txtdoa"));
});
Sys.Application.add_init(function() {
$create(Sys.Extended.UI.AutoCompleteBehavior, {"completionInterval":10,"completionListCssClass":"autocomplete_completionListElement","completionListItemCssClass":"autocomplete_listItem","completionSetCount":20,"delimiterCharacters":"","highlightedItemCssClass":"autocomplete_highlightedListItem","id":"AutoCompleteEx","onHide":"{\"AnimationName\":\"Parallel\",\"Duration\":\".4\",\"AnimationChildren\":[{\"AnimationName\":\"FadeOut\",\"AnimationChildren\":[]},{\"AnimationName\":\"Length\",\"PropertyKey\":\"height\",\"StartValueScript\":\"$find(\\u0027AutoCompleteEx\\u0027)._height\",\"EndValue\":\"0\",\"AnimationChildren\":[]}]}","onShow":"{\"AnimationName\":\"Sequence\",\"AnimationChildren\":[{\"AnimationName\":\"OpacityAction\",\"Opacity\":\"0\",\"AnimationChildren\":[]},{\"AnimationName\":\"HideAction\",\"Visible\":\"true\",\"AnimationChildren\":[]},{\"AnimationName\":\"ScriptAction\",\"Script\":\"\\r\\n // Cache the size and setup the initial size\\r\\n var behavior = $find(\\u0027AutoCompleteEx\\u0027);\\r\\n if (!behavior._height) {\\r\\n var target = behavior.get_completionList();\\r\\n behavior._height = target.offsetHeight - 2;\\r\\n target.style.height = \\u00270px\\u0027;\\r\\n }\",\"AnimationChildren\":[]},{\"AnimationName\":\"Parallel\",\"Duration\":\".4\",\"AnimationChildren\":[{\"AnimationName\":\"FadeIn\",\"AnimationChildren\":[]},{\"AnimationName\":\"Length\",\"PropertyKey\":\"height\",\"StartValue\":\"0\",\"EndValueScript\":\"$find(\\u0027AutoCompleteEx\\u0027)._height\",\"AnimationChildren\":[]}]}]}","serviceMethod":"GetHSNSACList","servicePath":"/rfp/frmGSTINPaymentformTax.aspx"}, {"itemSelected":SetddlTypeValue,"populated":HidehsnImage,"populating":ShowhsnImage}, null, $get("ctl00_ContentPlaceHolder1_txtHSN_SAC"));
});
Sys.Application.add_init(function() {
$create(Sys.UI._UpdateProgress, {"associatedUpdatePanelId":"ctl00_ContentPlaceHolder1_UpdatePanel10","displayAfter":500,"dynamicLayout":true}, null, null, $get("ctl00_ContentPlaceHolder1_UpdateProgress9"));
});
Sys.Application.add_init(function() {
$create(Sys.UI._UpdateProgress, {"associatedUpdatePanelId":"ctl00_ContentPlaceHolder1_savepnlData","displayAfter":500,"dynamicLayout":true}, null, null, $get("ctl00_ContentPlaceHolder1_UpdateProgress"));
});
//]]>
</script>
</form>
</body>
</html>
my modal code
<form action="/update" method="post">
<div class="modal fade" id="duzen" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="Moda1">Etiketi Düzenle</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" name="okuyucu" class="form-control okuyucu" placeholder="okuyucu" required>
</div>
<div class="form-group">
<input type="text" name="x" class="form-control x" placeholder="x" required>
</div>
<div class="form-group">
<input type="text" name="y" class="form-control y" placeholder="y" required>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="idnew_table" class="idnew_table">
<button type="button" class="btn btn-secondary btn-pill" data-dismiss="modal">Kapat</button>
<button type="submit" class="btn btn-primary btn-pill">Güncelle</button>
</div>
</div>
</div>
</div>
</form>
my ajax code
<script>
$(document).ready(() => {
var x1="";
var y1="";
var okuyucu1="";
var id="";
$.ajax({
url: "http://localhost:10001/etiketokuyucu",
method: 'GET',
success: function(response){
if(response.length > 0){
for(let index = 0; index < response.length; index++) {
var newRow = $("<tr>");
var cols = "";
var okuyucu = '';
var x = '';
var y = '';
var id='';
cols += '<td>' + response[index].idnew_table+'</td>';
cols += '<td> '+ response[index].okuyucu +'</td>' ;
cols += '<td> '+ response[index].x +'</td>';
cols += '<td> '+ response[index].y +'</td>';
cols += '<td>'
+
'<div class="dropdown d-inline-block widget-dropdown">'+
'<a class="dropdown-toggle icon-burger-mini" href="" role="button" id="dropdown-recent-order1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-display="static"></a>'+
'<ul class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdown-recent-order1">'+
'<li class="dropdown-item edit">'+
'Düzenle'+
'</li>'+
'<li class="dropdown-item delete">'+
'Sil'+
'</li>'+
'</ul>'+
'</div>'+
'</td>' ;
newRow.append(cols);
$("#example .tbody").append(newRow);
}
}
}
})
})
my modal script code
<script>
$(document).ready(function(){
//showing data to modal for edit record
$('#example').on('click','.edit',function(){
var idnew_table = $(this).data('idnew_table');
var okuyucu= $(this).data('okuyucu');
var x = $(this).data('x');
var y = $(this).data('y');
console.log(idnew_table+"okuyucu="+okuyucu + "x=" +x+" y="+y);
var modal = $(this);
modal.find('#okuyucu').text(okuyucu);
modal.find('#x').text(x);
modal.find('#y').text(y);
/*$('#duzen').modal('show');
$('.okuyucu').val($(this).data('okuyucu'))
$('.x').val(x);
$('.y').val(y);
$('.idnew_table').val(idnew_table);
*/ });
//showing modal for delete record
});
I want to show my mysql data on modal but ı got an error.In this code first show true value in console okuyucu,x,y etc but in modal shows they are undefined.why are they not show true value in my console when they second run?It passes data from ajax to table and I read that value from script code but doesn't show in my modal
Thank you for your help
Your current code for appending value to table was having 2 class edit i.e : li and <a> so when you click on edit link both class where getting called and it was returning undefined .Also , your input inside modal doesn't have any id instead it only have namei have corrected your code .
Demo Code :
//demo data
var response = [{
"idnew_table": "1",
"okuyucu": "abc",
"x": "12",
"y": "fbg"
}, {
"idnew_table": "2",
"okuyucu": "abcd",
"x": "152",
"y": "f5bg"
}, {
"idnew_table": "3",
"okuyucu": "abce",
"x": "125",
"y": "fb5g"
}]
if (response.length > 0) {
for (let index = 0; index < response.length; index++) {
var newRow = $("<tr>");
var cols = "";
var okuyucu = '';
var x = '';
var y = '';
var id = '';
cols += '<td>' + response[index].idnew_table + '</td>';
cols += '<td> ' + response[index].okuyucu + '</td>';
cols += '<td> ' + response[index].x + '</td>';
cols += '<td> ' + response[index].y + '</td>';
cols += '<td>' +
'<div class="dropdown d-inline-block widget-dropdown">' +
'<a class="dropdown-toggle icon-burger-mini" href="" role="button" id="dropdown-recent-order1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-display="static"></a>' +
'<ul class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdown-recent-order1">' +
'<li class="dropdown-item ">' + //<--remove class edit
'Düzenle'+
'</li>' +
'<li class="dropdown-item delete">' +
'Sil' +
'</li>' +
'</ul>' +
'</div>' +
'</td>';
newRow.append(cols);
$("#example .tbody").append(newRow);
}
}
//showing data to modal for edit record
$('#example').on('click','.edit',function(){
var idnew_table = $(this).data('idnew_table');
var okuyucu = $(this).data('okuyucu');
var x = $(this).data('x');
var y = $(this).data('y');
console.log(idnew_table + "okuyucu=" + okuyucu + "x=" + x + " y=" + y);
//find input under modal and set value of inputs
$("#duzen").find('input[name=okuyucu]').val(okuyucu);
$("#duzen").find('input[name=x]').val(x);
$("#duzen").find('input[name=y]').val(y);
$('#duzen').modal('show');
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<table id="example" border="1">
<thead>
<th>idnew_table</th>
<th>okuyucu</th>
<th>x</th>
<th>y</th>
<th>Action</th>
</thead>
<tbody class="tbody">
</tbody>
</table>
<form action="/update" method="post">
<div class="modal fade" id="duzen" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="Moda1">Etiketi Düzenle</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" name="okuyucu" class="form-control okuyucu" placeholder="okuyucu" required>
</div>
<div class="form-group">
<input type="text" name="x" class="form-control x" placeholder="x" required>
</div>
<div class="form-group">
<input type="text" name="y" class="form-control y" placeholder="y" required>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="idnew_table" class="idnew_table">
<button type="button" class="btn btn-secondary btn-pill" data-dismiss="modal">Kapat</button>
<button type="submit" class="btn btn-primary btn-pill">Güncelle</button>
</div>
</div>
</div>
</div>
</form>
I have some code that I wrote to essentially handle a login with a back end API supporting it.
My problem is that after the form POSTS the data to the server (and it is accepted), the index page (which is the same place this form is located on) still shows the login form instead of the different if statement I have in the file.
BUT, if I refresh the page, the correct part of the if statement displays. I have been at this all day, and I need a fresh pair of eyes to look over it and see what I'm doing something wrong:
define([
'lodash',
'log4js',
'path',
'when',
'common/lang/Disposable',
'common/commands/CommandHandler',
'common-node/network/http/Verb',
'common-node/network/server/endpoints/html/PageContainer',
'common-node/network/server/endpoints/html/PageEndpoint',
'common-node/network/server/ServerDefinition',
'common-node/network/server/ServerFactory.instance',
], function(_, log4js, path, when, Disposable, CommandHandler, Verb, PageContainer, PageEndpoint, ServerDefinition, serverFactory) {
//'use strict';
var m;
var session = require('client-sessions');
session({
cookieName: 'GBE_OWNED',
secret: '12112asdfasdf',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
});
var logger = log4js.getLogger('server/GbeSeasonalsWebServer');
var GbeSeasonalsWebServer = Disposable.extend({
init: function() {
},
start: function(configuration) {
var port = getContainerPort(configuration.container);
var state = false;
var indexHandler = new CommandHandler.fromFunction(function(input) {
console.log(input || { });
if(input.logout == ''){
session.qry = '';
session.Name = '';
return {
name: '',
currentState: false,
reloadLogout: true
};
}
if(typeof session.qry === 'undefined' || session.qry === null || session.qry === ''){
//the user isn't logged in
state = false;
}
else{
console.log(session.qry);
state = true;
}
return {
name: session.Name,
currentState: state
};
});
var loginHandler = new CommandHandler.fromFunction(function(input) {
var userName = input.username;
var userPass = input.password;
var rememberMe = input.remember;
var retro = false;
var iResponse;
var productIDs = 'USC_SEASONAL_CB,USC_SEASONAL_CB'; // this will be changed when jose gets back to me with the specifics
var https = require('https');
var callback = function(response){
var str = '';
response.on('data', function(chunk){
str += chunk;
});
response.on('end', function () {
try{
var DOMParser = require('xmldom').DOMParser;
}catch(err){
return {error: "There appeared to be an error. Please try again."};
}
var doc = new DOMParser().parseFromString(str,'text/xml');
var isSuccessful = doc.firstChild.attributes[1].nodeValue;
if(isSuccessful == 'True'){
retro = true;
//I need to set a session here
console.log("The account was logged in successfully.");
session.qry = '?username=' + userName + '&password=' + userPass + '&productids=' + productIDs;
//console.log(session.username);
if(typeof str === 'undefined' || str === null){return {error: "There appeared to be an error. Please try again."};}
session.Name = doc.firstChild.attributes[4].nodeValue + ' ' + doc.firstChild.attributes[5].nodeValue;
var state = true;
iResponse = function (){
return {
name: session.Name,
currentState: true,
reload: true,
};
};
}
else{
iResponse = function (){
return {
error: "There appeared to be a problem while trying to log you in.",
name: "WHATTHEHELL",
state: false
};
};
}
return iResponse;
});
response.on('error', function (e) {
console.log(e);
});
};
return https.request('https://secure.barchart.com/banker/getuserpermissions.ashx?username=' + userName + '&password=' + userPass + '&productids=' + productIDs, callback).end();
});
var definition = ServerDefinition
.withContainer(
new PageContainer(port, '/')
.addEndpoint(new PageEndpoint(Verb.GET, '', 'index', indexHandler))
.addEndpoint(new PageEndpoint(Verb.POST, '', 'index', loginHandler))
.addEndpoint(new PageEndpoint(Verb.GET, '/index', 'index', indexHandler))
.addEndpoint(new PageEndpoint(Verb.POST, '/index', 'index', loginHandler))
.addEndpoint(new PageEndpoint(Verb.GET, '/signup', 'signup'))
.addEndpoint(new PageEndpoint(Verb.POST, '/signup', 'signup'))
.addEndpoint(new PageEndpoint(Verb.GET, '/more', 'more'))
);
definition.withTemplatePath(path.join(configuration.server.path, configuration.container.http.templatePath));
_.forEach(configuration.container.http.staticPaths, function(filePath, serverPath) {
definition.withStaticPath(path.join(configuration.server.path, filePath), serverPath);
});
return when.try(function() {
serverFactory.build(definition);
}).then(function() {
return true;
});
},
_onDispose: function() {
logger.warn('GBE Seasonals web server is being disposed');
},
toString: function() {
return '[GbeSeasonalsWebServer]';
}
});
function getContainerPort(containerConfiguration) {
var port = parseInt(process.env.PORT);
if (_.isNaN(port)) {
port = null;
}
return port || containerConfiguration.port || 8080;
}
return GbeSeasonalsWebServer;
});
And the index page:
<!DOCTYPE html>
<html lang="en">
<head>
<title>GBE SEASONALS STAGING SITE © Barchart™</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Custom theme -->
<link rel="stylesheet" type="text/css" href="static/css/custom.css">
</head>
<body>
<script type="text/javascript">
var c = '{{name}}';
var state = '{{currentState}}';
{{#if reload}}
window.location = window.location.href;
{{/if}}
{{#if reloadLogout}}
window.location = window.location.href.split("?")[0];
{{/if}}
if(state==''){window.location = window.location.href; }
</script>
<div class="container">
<div class = "row">
<div class="col-md-10 col-md-offset-1">
<a href="index">
<img style = "vertical-align:middle;display:inline-block" src="http://www.gbemembers.com/images/GBE_Logo_horiz.png" class="img-responsive">
<p style="color:white;margin-top:50px;margin-right:20px;font-size:20px" class="pull-right">Seasonals</p>
</a>
</div>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading"></div>
<div class="panel-body">
<div class = "row">
{{#if error}}
<div class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class=""><b>Error:</b></span>
{{error}}
</div>
{{/if}}
{{#if currentState}}
<div class = "col-md-12">
<p class = "pull-right">Welcome back {{name}}! Click here to log out.</p>
</div>
{{else}}
<center>
<div class = "col-md-12">
<form class="form-inline" style = "width:100%;margin:0 auto;" method="post" action = "?"><label>Already a member? Login here: </label>
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">Email address</label>
<input type="" class="form-control" id="exampleInputEmail3" placeholder="Email" name = "username">
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Password</label>
<input type="password" class="form-control" id="exampleInputPassword3" placeholder="Password" name = "password">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name = "remember"> Remember me
</label>
</div>
<button type="submit" class="btn btn-default">Sign in</button>
<input type = "button" value = "Register" class="btn btn-default">
</form>
<p></p>
</div>
</center>
{{/if}}
</div>
<div class = "row">
<div class = "col-md-12">
<div class="jumbotron">
<h1>Hello, world!</h1>
<p>This is an example of a jumbotron....because you're worth it.</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
</div>
</div>
</div>
<div class = "row">
<div class = "col-md-12">
<p>
Freegan tacos before they sold out, health goth sriracha chartreuse kinfolk jean shorts man braid artisan literally. Brooklyn vice hashtag, meh tumblr kombucha marfa readymade. Ennui cold-pressed distillery freegan. Kale chips tilde +1, mumblecore franzen migas paleo. Offal 3 wolf moon before they sold out, health goth disrupt fixie bitters flannel meditation pop-up flexitarian irony meh. Deep v put a bird on it pork belly cardigan etsy. Lumbersexual literally crucifix slow-carb cardigan.
</p>
</div>
</div>
<div class = "row">
<div class = "col-md-12">
<p>Asymmetrical readymade brooklyn, blue bottle master cleanse disrupt artisan +1 actually affogato roof party DIY polaroid next level retro. Brooklyn poutine vegan bitters you probably haven't heard of them. Celiac helvetica master cleanse williamsburg, synth shabby chic fixie. Viral typewriter cred, roof party kombucha readymade offal shabby chic meggings. Gochujang chillwave VHS food truck. Ennui ugh twee, mumblecore sriracha DIY gastropub hella 3 wolf moon pabst kale chips typewriter trust fund direct trade. Neutra microdosing selfies listicle.</p>
</div>
</div>
<div class = "row">
<div class = "col-md-12">
<p>
Gochujang farm-to-table offal, distillery tofu migas skateboard 90's. Ethical ramps hoodie, YOLO vice before they sold out four loko literally mustache post-ironic. Fixie ennui literally lumbersexual photo booth umami disrupt messenger bag man braid polaroid. Cold-pressed aesthetic marfa, vinyl truffaut squid 3 wolf moon sriracha keytar knausgaard echo park. Chambray leggings microdosing mustache migas. Keytar portland chambray, quinoa ugh farm-to-table mustache cred mixtape craft beer. Thundercats chia keytar beard, drinking vinegar mustache man bun slow-carb wayfarers polaroid lo-fi chicharrones.
</p>
</div>
</div>
<div class = "row">
<div class = "col-md-12">
<p>
Quinoa cred taxidermy, cold-pressed microdosing offal mustache gluten-free small batch tousled twee wayfarers. Wolf williamsburg normcore lo-fi, tilde seitan hammock bushwick DIY organic single-origin coffee quinoa microdosing man braid. Fap small batch PBR&B microdosing, migas pork belly occupy aesthetic pop-up slow-carb 3 wolf moon. Blue bottle XOXO occupy +1, pabst lomo chicharrones ethical heirloom helvetica asymmetrical. Bushwick shabby chic yr kombucha, flannel truffaut raw denim banh mi bitters gluten-free pickled hoodie letterpress sartorial. YOLO whatever tacos meggings venmo, keytar knausgaard mumblecore. Tilde waistcoat offal, locavore cred umami mlkshk vice lomo lo-fi tousled selvage blog tattooed poutine.
</p>
</div>
</div>
<div class = "row">
<div class = "col-md-12">
<button type="button" class="btn btn-primary btn-lg btn-block">Click here to sign up!</button>
</div>
</div>
</div>
<div class = "panel-footer">GBE Seasonal © 2016 Barchart</div>
</div>
</div>
</div>
</div> <!-- /container -->
<!-- Let's load the javascript dendencies now -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script type="text/javascript" src = "http://getbootstrap.com/assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
I believe it is a session issue, but I cannot seem to get around the issue. What's more, I cannot even get the callback function to return the needed data.
Please consider the following (Issue is, the results of the Google Search on our page is not registering within our Google Analytics Account):
HTML FORM:
<div style="float:right; margin-right:12px;">
<form id="cse-search-box" name="srchfrm" action="http://google.com/cse" target="_blank" onsubmit="validatesearch()">
<input value="999999999999999999999:srraaaaaaaa" name="cx" type="hidden"/>
<input id="q" name="q" type="text" onKeyPress="return submitenter(this,event)" placeholder="Search"/>
<a href="javascript:;" onmouseover="MM_swapImage('go','','/btn_go_on.gif',1)" onmouseout="MM_swapImgRestore()" />
<input type="image" src="/btn_go.gif" alt="Go" width="20" height="21" border="0" align="top" id="go"/>
<input value="UTF-8" name="ie" type="hidden"/>
</form>
</div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
google.setOnLoadCallback(function() {
google.search.CustomSearchControl.attachAutoCompletion(
'999999999999999999999:srraaaaaaaa',
document.getElementById('q'),
'cse-search-box');
});
</script>
URL ON EXECUTING A SEARCH:
http://www.google.com/cse?cx=999999999999999999999:srraaaaaaaa&q=test+search&x=12&y=11&ie=UTF-8&oq=&gs_l=#gsc.tab=0&gsc.q=test%20search&gsc.page=1
QUERY PARAMETERS BEING USED:
q
query (I read in another post to try this)
Thank you for all the help in advance!
By changing:
action="http://google.com/cse"
within,
<form id="cse-search-box" name="srchfrm" action="http://google.com/cse" target="_blank" onsubmit="validatesearch()">
to redirect to a page within the website, this resolved the issue.
Working code:
<div style="float:right; margin-right:12px;">
<form id="searchbox_99999999999999999999:srraaaaaaaa" name="srchfrm" action="/search" target="_self" onsubmit="validatesearch()">
<input value="99999999999999999999:srraaaaaaaa" name="cx" type="hidden"/>
<input id="q" name="q" autocomplete="off" type="text" onKeyPress="return submitenter(this,event)" placeholder="Search"/>
<input name="ie" value="UTF-8" type="hidden"/>
<a href="javascript:;" onmouseover="MM_swapImage('go','','/btn_go_on.png',1)" onmouseout="MM_swapImgRestore()" />
<input type="image" src="/btn_go.png" alt="Go" width="20" height="21" border="0" align="top" id="go"/>
</form>
</div>
The Search Page itself has the following code as per Google documentation:
HEAD:
<script>
(function() {
var cx = '99999999999999999999:srraaaaaaaa';
var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
</script>
BODY:
<gcse:searchresults-only></gcse:searchresults-only>