Disable rating stars after once rated js - javascript

Hi I want to put rating stars on my webpage.
Its is working fine. Rating is being added to database
But a user can rate again and again.
I want that stars should disable after rate once.
Here is my code. Kindly help me Thank you.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="http://online-btw-berekenen.nl/rating/rating.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://online-btw-berekenen.nl/rating/rating.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
$("#rating_star").codexworld_rating_widget({
starLength: '5',
initialValue: '',
callbackFunctionName: 'processRating',
imageDirectory: 'images/',
inputAttr: 'postID'
});
});
function processRating(val, attrVal){
$.ajax({
type: 'POST',
url: 'rating.php',
data: 'postID='+attrVal+'&ratingPoints='+val,
dataType: 'json',
success : function(data) {
if (data.status == 'ok') {
alert('You have rated '+val+' to CodexWorld');
$('#avgrat').text(data.average_rating);
$('#totalrat').text(data.rating_number);
}else{
alert('Some problem occured, please try again.');
}
}
});
}
</script>
<style type="text/css">
.overall-rating{font-size: 14px;margin-top: 5px;color: #8e8d8d;}
</style>
</head>
<body style="background-color:black">
<h1>Give us star</h1>
<input name="rating" value="0" id="rating_star" type="hidden" postID="1" />
<div class="overall-rating">(Average Rating <span id="avgrat"><?php echo $ratingRow['average_rating']; ?></span>
Based on <span id="totalrat"><?php echo $ratingRow['rating_number']; ?></span> rating)</span></div>
</body>
</html>
Click and Hover funtion in javascript.
(function(a){
a.fn.codexworld_rating_widget = function(p){
var p = p||{};
var b = p&&p.starLength?p.starLength:"5";
var c = p&&p.callbackFunctionName?p.callbackFunctionName:"";
var e = p&&p.initialValue?p.initialValue:"0";
var d = p&&p.imageDirectory?p.imageDirectory:"images";
var r = p&&p.inputAttr?p.inputAttr:"";
var f = e;
var g = a(this);
b = parseInt(b);
init();
g.next("ul").children("li").hover(function(){
$(this).parent().children("li").css('background-position','0px 0px');
var a = $(this).parent().children("li").index($(this));
$(this).parent().children("li").slice(0,a+1).css('background-position','0px -28px')
},function(){});
g.next("ul").children("li").click(function(){
var a = $(this).parent().children("li").index($(this));
var attrVal = (r != '')?g.attr(r):'';
f = a+1;
g.val(f);
if(c != ""){
eval(c+"("+g.val()+", "+attrVal+")")
}
});
g.next("ul").hover(function(){},function(){
if(f == ""){
$(this).children("li").slice(0,f).css('background-position','0px 0px')
}else{
$(this).children("li").css('background-position','0px 0px');
$(this).children("li").slice(0,f).css('background-position','0px -28px')
}
});
function init(){
$('<div style="clear:both;"></div>').insertAfter(g);
g.css("float","left");
var a = $("<ul>");
a.addClass("codexworld_rating_widget");
for(var i=1;i<=b;i++){
a.append('<li style="background-image:url('+d+'/widget_star.gif)"><span>'+i+'</span></li>')
}
a.insertAfter(g);
if(e != ""){
f = e;
g.val(e);
g.next("ul").children("li").slice(0,f).css('background-position','0px -28px')
}
}
}
})(jQuery);

ok, in you click handler just remove the click event listener using the jquery off() method.

There are a few steps to disable to click and hover events AFTER a user has successfully selected (& recorded) a rating:
Add a line into your ajax success
success : function(data) {
if (data.status == 'ok') {
alert('You have rated '+val+' to CodexWorld');
$('#avgrat').text(data.average_rating);
$('#totalrat').text(data.rating_number);
$('.codexworld_rating_widget').addClass('already_set');
}else{...
Then add a function to disable each hover & click on the <li> in the "http://online-btw-berekenen.nl/rating/rating.js" script. See example below:
g.next("ul").children("li").hover(function(){
if ('.codexworld_rating_widget.alreadyset') {
$('.codexworld_rating_widget').off('click','li').off('hover','li');
}else{
// original script goes here
});
});
Anyways, I'm not able to test it without building a sandbox, so...hope it helps to point you in the right direction.

Related

Code working in Chrome and Edge but not in IE - setimeout?

I have the following downloadZip.html. The download works in Chrome and Edge, but not in IE. This file gets called as below from jspf page. When I click "Download listed documents" it call popupDownloadWindow(), which will open downloadZip.html in plainview. This html when loaded calls enableLink() and the flow goes. As the view is plainview, only first if block of enableLink() is executed (if(callerview == "plainview")). Not sure if this is happening because of setTimeout(). Please help me here. Let me know for any information.
function checkReturn(){
//alert('checkReturn - sessionsNotOk global var = '+sessionsNotOk);
if (sessionsNotOk != "DEF") {
var docbases = sessionsNotOk.split(",");
//alert('checkReturn - docbases arr = '+docbases+', length='+docbases.length);
if (docbases.length == 1 && docbases[0] == "OK"){
// All sessions are faja
document.getElementById('divIndicator').style.display='none';
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='none';
document.getElementById('dlink').style.display='inline';
document.getElementById('dlink').style.textAlign='center';
document.getElementById('dlink').style.display='';
} else {
// We need to show the sublogin dialog
var nextDocbase = docbases[0];
//alert("Next NOT AVAILABLE session = "+nextDocbase);
window.opener.$('#subloginmessage').css('display','none');
window.opener.$('#loginIndicator').css('display','none');
window.opener.$('#sub-uid').val(window.opener.$('#user_name').text());
window.opener.$('#sub-uid').attr('disabled','disabled');
window.opener.$('#sub_docbase').text(nextDocbase);
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='inline';
document.getElementById('noSession').style.textAlign='center';
document.getElementById('noSession').style.display='';
window.opener.sublogin_fw = "download";
window.opener.sublogin_db = nextDocbase;
window.opener.$('#sublogindialog').dialog('open');
window.opener.$('#sublogindialog').dialog('option','title','Login to docbase: ' + nextDocbase + ' and click on Download listed documents link again!');
}
return;
}
//Check again in 0.5 second
setTimeout("checkReturn()",500);
//setTimeout(function() {
// checkReturn();
//}, 500);
}
Complete code:
<script>
var downloadZipChildWindow;
function popupDownloadWindow(){
downloadZipChildWindow = window.open('../html/downloadZip.html?view=plainview','downloadwindow','width=300,height=200,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=no');
}
</script>
<a id='download_link' class='download_link' href="#" onClick="popupDownloadWindow()">Download listed documents</a>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Download documents as Zip file</title>
<script type="text/javascript" src="../js/jquery-1.6.1.min.js" ></script>
<style type="text/css">
p
{
font-family:"Verdana";
font-size:small;
}
a
{
font-family:"Helvetica";
font-size:small;
}
</style>
<script type="text/javascript">
var lastParam;
var sessionsNotOk = "DEF";
var callerView;
function getParam( paramName )
{
paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+paramName+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
/*
* Checks the return from ajax servlet call "../downloadzip?ask=isSRPsessionsOK&packageIDs="+pIDs".
* Called always right after checkDocbaseSessions() call.
*/
function checkReturn(){
//alert('checkReturn - sessionsNotOk global var = '+sessionsNotOk);
if (sessionsNotOk != "DEF") {
var docbases = sessionsNotOk.split(",");
//alert('checkReturn - docbases arr = '+docbases+', length='+docbases.length);
if (docbases.length == 1 && docbases[0] == "OK"){
// All sessions are faja
document.getElementById('divIndicator').style.display='none';
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='none';
document.getElementById('dlink').style.display='inline';
document.getElementById('dlink').style.textAlign='center';
document.getElementById('dlink').style.display='';
} else {
// We need to show the sublogin dialog
var nextDocbase = docbases[0];
//alert("Next NOT AVAILABLE session = "+nextDocbase);
window.opener.$('#subloginmessage').css('display','none');
window.opener.$('#loginIndicator').css('display','none');
window.opener.$('#sub-uid').val(window.opener.$('#user_name').text());
window.opener.$('#sub-uid').attr('disabled','disabled');
window.opener.$('#sub_docbase').text(nextDocbase);
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='inline';
document.getElementById('noSession').style.textAlign='center';
document.getElementById('noSession').style.display='';
window.opener.sublogin_fw = "download";
window.opener.sublogin_db = nextDocbase;
window.opener.$('#sublogindialog').dialog('open');
window.opener.$('#sublogindialog').dialog('option','title','Login to docbase: ' + nextDocbase + ' and click on Download listed documents link again!');
}
return;
}
//Check again in 0.5 second
//setTimeout("checkReturn()",500);
setTimeout(function() {
checkReturn();
}, 500);
}
function enableLink(){
callerView = getParam("view");
var pkgType = "";
var params = "";
var packageIDs = "";
if (callerView == "plainview") {
pkgType = window.opener.$('#hiddenPkgType').attr('value');
// Check available sessions
if (pkgType == 'srp'){
document.getElementById('dlink').style.display='none';
document.getElementById('checkSession').style.display='inline';
document.getElementById('checkSession').style.textAlign='center';
document.getElementById('checkSession').style.display='';
packageIDs = window.opener.$('#hiddenSRPIDs').attr('value');
checkDocbaseSessions(packageIDs);
checkReturn();
}
params = window.opener.$('#hiddenDownloadParams').attr('value');
} else if (callerView == "packagedetailview") {
pkgType = window.opener.$('#hiddenPkgType_DetailedPackageView').attr('value');
if (pkgType == "" || pkgType == null) {
alert("Still loading data, window will be closed. Please click on download button after all data have been loaded on the page!");
window.close();
}
params = window.opener.$('#hiddenDownloadParams_DetailedPackageView').attr('value');
} else if (callerView == "SRP_packagedetailview") {
// Prepare/check remote sessions
packageIDs = window.opener.$('#SRP_DPV_pkgIDs').attr('value');
checkDocbaseSessions(packageIDs);
checkReturn();
pkgType = 'srp';
if (pkgType == "" || pkgType == null) {
alert("Still loading data, window will be closed. Please click on download button after all data have been loaded on the page!");
window.close();
}
params = window.opener.$('#hiddenDownloadParams_SRP_DetailedPackageView').attr('value');
} else if (callerView == "SRP_checkstatusview") {
// Prepare/check remote sessions
packageIDs = window.opener.$('#SRP_CSV_pkgIDs').attr('value');
checkDocbaseSessions(packageIDs);
checkReturn();
pkgType = 'srp';
if (pkgType == "" || pkgType == null) {
alert("Still loading data, window will be closed. Please click on download button after all data have been loaded on the page!");
window.close();
}
params = window.opener.$('#hiddenDownloadParams_SRP_CheckStatusView').attr('value');
}
if (pkgType == 'nlp' || pkgType == 'monnlp') {
document.getElementById('download_zip_stdfilenames_nlp_country').style.display='inline';
document.getElementById('download_zip_stdfilenames_nlp_product').style.display='inline';
document.getElementById('download_zip_stdfilenames_nlp_country').style.textAlign='center';
document.getElementById('download_zip_stdfilenames_nlp_product').style.textAlign='center';
document.getElementById('download_zip_stdfilenames').style.display='none';
} else if (pkgType == 'clp') {
document.getElementById('download_zip_stdfilenames_nlp_country').style.display='none';
document.getElementById('download_zip_stdfilenames_nlp_product').style.display='none';
document.getElementById('download_zip_stdfilenames').style.display='inline';
document.getElementById('download_zip_stdfilenames').style.textAlign='center';
} else if (pkgType == 'ipl') {
document.getElementById('download_zip_stdfilenames_nlp_country').style.display='none';
document.getElementById('download_zip_stdfilenames_nlp_product').style.display='none';
document.getElementById('download_zip_stdfilenames').style.display='inline';
document.getElementById('download_zip_stdfilenames').style.textAlign='center';
}
//Defined as global
zipParamsImp = params + "&filename=import";
zipParamsStd = params + "&filename=standard";
}
function showIndicator(param){
document.getElementById('divIndicator').style.display='inline';
document.getElementById('divIndicator').style.textAlign='center';
document.getElementById('divIndicator').style.display='';
document.getElementById('dlink').style.display='none';
var parameters = "";
if (param == 'import'){
parameters = zipParamsImp;
} else if (param == 'standard') {
parameters = zipParamsStd;
} else if (param == 'standard_nlp_country') {
parameters = zipParamsStd + "_nlp_country";
} else if (param == 'standard_nlp_product') {
parameters = zipParamsStd + "_nlp_product";
}
lastParam = param;
postwith("../downloadzip",parameters);
}
function postwith (to, params) {
var myForm = window.opener.document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
myForm.style.display = 'none';
jQuery.each(params.split('&'), function(){
var pair = this.split('=');
var myInput = window.opener.document.createElement("input") ;
myInput.setAttribute("name", pair[0]) ;
myInput.setAttribute("value", pair[1]);
myForm.appendChild(myInput);
});
var lastInput = window.opener.document.createElement("input") ;
lastInput.setAttribute("name", "download_token_value_id") ;
lastInput.setAttribute("value", "");
myForm.appendChild(lastInput);
window.opener.document.body.appendChild(myForm) ;
myForm.submit();
window.opener.document.body.removeChild(myForm) ;
//setTimeout("checkProgress()",1000);
setTimeout(function(){
checkProgress();
},1000);
}
/*
* Checks return from servlet call "../downloadzip?ask=isready" -> ask whether DownloadAsZipServlet
* has finished its work or not. If finished, close this popup.
*/
function checkProgress(){
window.focus();
$.ajax({
type: "GET",
url: "../downloadzip?ask=isready",
dataType: "text",
//dataType: "script",
//timeout: 2000,
success: function(results)
{
// Normal flow
//var result = eval('('+results+')');
var currParams = window.opener.$('#hiddenDownloadParams').attr('value');
//After closing DPV and clicking on Download Listed Documents button, we have to remove caller param, because there is no caller.
//Caller exists only if openPackage function called, and Download is on a DPV page.
//If we do not remove caller param, then exception occurs.
var callerPrefix = currParams.substring(0,currParams.indexOf('&'));
if (callerPrefix.indexOf('caller=') > -1) {
window.opener.$('#hiddenDownloadParams').attr('value',currParams.replace(callerPrefix+'&',""));
} else {
// No caller param found
}
if (results.indexOf('window.close()') > -1) {
window.close();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
window.top.document.location.href = "../jsp/logout.jsp?msg=Application error (HTTPREQ quicksearch download documents). You have been logged out!";
}
});
}
/*
* In case of SRP - checks whether sessions for all required docbases are available.
* It is needed, because SRP package documents can be located in different docbases.
*/
function checkDocbaseSessions(pIDs){
sessionsNotOk = "DEF";
$.ajax({
type: "GET",
url: "../downloadzip?ask=isSRPsessionsOK&packageIDs="+pIDs,
dataType: "text",
success: function(results)
{
//alert(results);
if ($.trim(results) == 'OK'){
//alert("Sessions are OK!");
sessionsNotOk="OK";
} else {
sessionsNotOk=results;
//alert("Sessions are NOT OK! - "+sessionsNotOk);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
window.top.document.location.href = "../jsp/logout.jsp?msg=Application error (HTTPREQ quicksearch download documents). You have been logged out!";
}
});
}
</script>
</head>
<body style="background-color: #ffffff; font-family: Verdana, Helvetica; font-size: x-small;" onload="enableLink();">
<div id="divIndicator" style="display: none"><br />
<p>Zip file creation in progress. This may take a few minutes, please wait and do not navigate away or start another query!</p>
<br />
<br />
<span id="qIndicator"> <img border="0" src="../img/indicator.gif"></span>
<br />
<br />
</div>
<p style="text-align: center">Download listed documents</p>
<div id="dlink" style="text-align: center">
With import file names
<br />
With standard file names
With standard file names starting with country
With standard file names starting with product
</div>
<div id="noSession" style="display: none">
<p>Some required sessions are unavailable. Please login to the docbase!</p>
</div>
<div id="checkSession" style="display: none">
<p>Checking required sessions in progress. Please wait...</p>
<br />
<span id="qIndicator"> <img border="0" src="../img/indicator.gif"></span>
<br />
</div>
</body>
</html>

How post more than one variable in javascript?

There is 2 input type="text". First, user input 1st input text area with id="ncr_no". Then, cursor is in 2nd input type "text" with id="itm_cd". Now, I want to make, how the two input by user, when cursor is in 2nd input type, posted to other php (get_ncrnoitmcd.php) by javascript? That's the code.
<script type="text/javascript">
$(document).ready(function() {
$("#itm_cd").keyup(function (e) {
$(this).val($(this).val().replace(/\s/g, ''));
var itm_cd = $(this).val();
if(itm_cd.length < 1){$("#user-result3").html('');return;}
if(itm_cd.length >= 1 ){
$("#user-result3").html('<img src="image/ajax-loader.gif" />');
$.post('get_ncrnoitmcd.php', {'itm_cd':itm_cd}, function(data) {
$("#user-result3").html(data);
});
}
});
});
</script>
Thank a lot.
This is the way you can send the 2 values to server on 2nd element keyup after validation. Whats the problem that you are facing? I also added ncr_no in the post request.
<script type="text/javascript">
$(document).ready(function() {
$("#itm_cd").keyup(function (e) {
$(this).val($(this).val().replace(/\s/g, ''));
var itm_cd = $(this).val();
if(itm_cd.length < 1){
$("#user-result3").html('');
return;
}else if(itm_cd.length >= 1 ){
$("#user-result3").html('<img src="image/ajax-loader.gif" />');
$.post(
'get_ncrnoitmcd.php'
,{'itm_cd':itm_cd,'ncr_no':$('#ncr_no').val()}
,function(data) {
$("#user-result3").html(data);
}
);
}
});
});
</script>
I want to get available or not available, Mr. #joyBlanks
<?php
//connection.php
if(isset($_POST["itm_cd"],$_POST["ncr_no"]))
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
$itm_cd = strtolower(trim($_POST["itm_cd"]));
$itm_cd = filter_var($itm_cd, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
$results = mysqli_query($connecDB,"SELECT itm_cd,ncr_no FROM sqc_ncr WHERE itm_cd ='$itm_cd' AND ncr_no ='$ncr_no'");
$itm_cd_exist = mysqli_num_rows($results);
if($itm_cd_exist) {
die('<!--img src="image/available.png" /--> <i>Available in database</i>');
}else{
die('<!--img src="image/not-available.png" /--> <i>Not Available in database</i>');
}
mysqli_close($connecDB);
}
?>
I've not used , and used && and not used http_x_requested, but available or not available in html not shown.
<td><input type="text" class="input" name="itm_cd" id="itm_cd" onBlur="updateItemName()" required /> <span id="user-result3"></span></td>

Ajax call not working second time

I have this ajax/php structure that works perfectly when selecting one image. But, if I click on "selecteer" to perform the same code for the second time, no images are shown. The "ajax" page does load correctly though.
Basically what I have;
Article page: This page shows 10 buttons "Selecteer". Under these 10 buttons you have a div where some images are shown after pressing Selecteer. When clicking on one of those images, the clicked image is selected and will be shown solely.
Javascript: This script binds the click events, and performs the ajax loading aswell as the image showing.
Images page: this page is loaded by ajax and is shown in a div inside the article page.
EDIT:
I did some testing. The second time the div is loaded with an ajax call (the images page) it does "Create" all the images with the createImage function. Yet I only see the search bar and the "zoek" button. So the real problem is: the images aren't showing the second time!
The code (I left some things out which I think are irrelevant)
article:
<?php for($i = 0; $i < constant("MAX_PICS"); $i++) { ?>
<button <?php echo"id='select_portal$i' class='select_portal_class'";?> type="button">Selecteer</button>
<div <?php echo"id='dialog_form$i'";?> style="display:none; position:absolute; width:auto; height:auto; margin-left: auto; margin-right: auto; z-index:1;"></div>
<div <?php echo"id='selected_image$i'";?> style="display:block; width:auto; height:auto">
<?php if(isset($_GET['edit_artikel'])) { ?><img src="../images/<?php $beeldbank = Beeldbank::find_by_portal_id($artikel->portal_id); echo $beeldbank[0]->imagelib_id; ?>/<?php echo $artikel->portal_id;?>" id="selid" width="125" /> <?php } else {?>
<img src="../images/icons/no_image_found.png" alt="No image available" <?php echo"id='selid$i'";?> width="125" /> <?php } ?>
<input type="hidden" <?php echo"id='portal_id$i'";?> name="portal_id" value="<?php if(isset($_GET['edit_artikel'])) { echo $artikel->portal_id; } ?>" />
</div>
<div id="selected_portal"></div>
javascript:
$(document).ready(function() {
(function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = document.location.protocol + '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js';
var script2 = document.createElement('script');
script2.type = 'text/javascript';
script2.src = document.location.protocol + '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
document.getElementsByTagName('head')[0].appendChild(script2);
})();
$( ".select_portal_class" ).each(
function( intIndex ){
$(this).bind('click', function() {
loadAjaxFrame(intIndex);
});
}
);
});
function loadAjaxFrame(id)
{
var dialog = $("#dialog_form"+id);
//alert(dialog.attr('id'));
dialog.css("display", "block");
dialog.css("top", "auto");
dialog.css("left", "auto");
dialog.css("right", "auto");
dialog.css("backgroundColor", "white");
document.getElementById(dialog.attr('id')).style.visibility = 'visible';
tempDialogID = id;
if(!ajaxLoad){
dialog.load("imglib.php");
ajaxLoad = true;
}
}
function showImage()
{
var portal = $("#portal_id"+tempDialogID);
var dialog = $("#dialog_form"+tempDialogID);
var selid = $("#selid"+tempDialogID);
alert(tempDialogID);
var img = document.getElementById(selid.attr('id'));
img.src = imgname;
var portal_id = document.getElementById(portal.attr('id'));
portal_id.value= imgid;
document.getElementById(dialog.attr('id')).style.visibility = 'hidden';
dialog.unload();
ajaxLoad = false;
}
function create_image(src,alt) {
var img = document.createElement("img");
var objTo = document.getElementById('imagesDiv');
img.src = src;
img.alt = alt;
img.className= "imgid";
$(img).height(imageHeight);
$(img).width(imageWidth);
$(img).bind('click', 'span', function () { imgid = alt; imgname = src; showImage(); });
objTo.appendChild(img);
}
$('#formpie').on('submit', function(e) {
e.preventDefault();
var dialog = $("#dialog_form"+tempDialogID);
$.ajax({
type : 'POST',
url : "imglib.php",
data : $(this).serializeArray(),
success: function(data) {
dialog.html(data);
}
});
});
And finally the images page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="javascripts/SelectImage.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var photos = <?php echo json_encode($photoSources); ?>;
var photoAlts = <?php echo json_encode($photoAlts); ?>;
var photoTags = <?php echo json_encode($photoTags); ?>;
var photoCount= <?php echo $total_count; ?>;
photoCount = photoCount/10;
photoCount = Math.ceil(photoCount);
function buttonClicked(id){
var page = id;
photoPage = page*10;
minCount = photoPage-10;
maxCount = photoPage;
jQuery("#imagesDiv").html("");
createButtons();
$( "#imagesDiv" ).append( " <br/>");
populateDiv();
}
function createButtons() {
var i = 1;
var button= "";
while(i <= photoCount)
{
var button = document.createElement("BUTTON");
var buttonName= document.createTextNode(i);
button.appendChild(buttonName);
button.id = i;
jQuery(button).bind('click', { id: i}, function(event) {
var data = event.data;
buttonClicked(data.id);
});
var objTo = document.getElementById('imagesDiv');
objTo.appendChild(button);
i++;
}
}
$(".moreButton").click(function() {
maxCount += 10;
minCount += 10;
jQuery("#imagesDiv").html("");
populateDiv();
});
function populateDiv() {
for(var i = minCount;i < maxCount; i++)
{
if(i < <?php echo $total_count ?>)
{
create_image("../"+photos[i],photoAlts[i]);
$( "#imagesDiv" ).append( "<p style=\"display:inline; padding-left:10px;\">" + photoTags[i] + "</p><br/>" );
}
}
}
createButtons()
$( "#imagesDiv" ).append( " <br/>");
populateDiv();
});
</script> <?php
if(isset($_POST['submit'])) {
$artikel->portal_id = $_POST['portal_id'];
}?>
<fieldset>
Afbeelding zoeken
<form id="formpie" name="zoek" action="" method="POST">
<input type="hidden" name="zoek" value="zoek" id="zoek"/>
<input type="text" name="tags" size="31" id="tags"/>
<input type="submit" name="zoek" id="search" value="Zoek" />
</form>
<div id="imagesDiv" style="width:800px; height:780px;">
<label for="portal_id"></label>
</div>
</fieldset>
<div id="selected_img_div" style="display:none; width:auto; height:auto;">
<?php if($selected_image == NULL) { echo "No image selected"; }
else { echo '<img src="images/'.$selected_image.' class="selimgid"/>'; } ?>
</div>
If you load content dynamically and you want bind actions to them you shouldn't use the .bind(), .click() and .on([action], function(){}) functions. Because these functions can be only bind into elements which rendered at page loading.
So you should use that function:
$('body').on([action], [selector], function(){});
[action]: what type of binding do you want (ie: click, submit,...)
[selector]: select the element what you want to bind (ie: '.moreButton')
For example, instead of that code:
$(".moreButton").click(function() {
maxCount += 10;
minCount += 10;
jQuery("#imagesDiv").html("");
populateDiv();
});
Use this code:
$('body').on('click' , '.moreButton', function() {
maxCount += 10;
minCount += 10;
jQuery("#imagesDiv").html("");
populateDiv();
});
Try changing to,
$('body').on('submit','#formpie', function(e) {
e.preventDefault();
var dialog = $("#dialog_form"+tempDialogID);
$.ajax({
type : 'POST',
url : "imglib.php",
data : $(this).serializeArray(),
success: function(data) {
dialog.html(data);
}
});
});
$('#formpie').on('submit', function(e) {
e.preventDefault();
var dialog = $("#dialog_form"+tempDialogID);
$.ajax({
type: 'POST',
url: "imglib.php",
data: $(this).serializeArray(),
success: function(data) {
dialog.html(data);
urlRefresh();
}
});
});
replace your code with it. I think there is a problem on url refresh. so Try it.
maybe you are using functions or events with new content?
if you are doing that, maybe you have the same problem like this
https://stackoverflow.com/a/26559809/2043592
I had same problem and it got resolved after adding below code in head tag.
<meta charset="UTF-8">
<meta http-equiv="cache-control"
content="no-cache, must-revalidate, post-check=0, pre-check=0" />
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 G`enter code here`MT" />
<meta http-equiv="pragma" content="no-cache" />

setTimeout not working

My setTimeout seems to be working for logging in, but not for submitting data. :
<script type="text/javascript" src="../scripts/jquery.js"></script>
<script type="text/javascript">
$.ajaxSetup({async:false});
function Validate_submit(form) {
var Address1_input = form.address1.value;
var Address2_input = form.address2.value;
var City_input = form.city.value;
var State_input = form.state.value;
$.post('../scripts/submit_check.php', {address1php: Address1_input, address2php: Address2_input, cityphp: City_input, statephp: State_input},
function(output) {
$('#submit_msg').html(output).fadeIn(500);
if (output == 'Submitting...') {
var timeoutID = window.setTimeout(function () {location.reload();}, 1000);
} else {
$('#submit_msg').html('something went wrong').fadeIn(500);
}
}
);
}
The same code works in my log-in popup window:
<script type="text/javascript" src="../scripts/jquery.js"></script>
<script type="text/javascript">
$.ajaxSetup({async:false});
function Validate_login(form) {
var Email_input = form.email.value;
var Password_input = form.password.value;
var Rememberme_input = form.remember_me.checked;
$.post('../scripts/login_check.php', { emailphp: Email_input, passwordphp: Password_input, rememberphp: Rememberme_input},
function(output) {
$('#login_msg').html(output).fadeIn(500);
if (output == 'Logging in...') {
var timeoutID = window.setTimeout(function () {location.reload();}, 1000);
}
}
);
}
When I click the submit button in the submit form, it shows 'Submitting...' for a split second, but not for the whole second (like in the login-popup). Can someone help me?
You'll probably need to cancel the actual <form>'s submission. return false from the onsubmit handler after you call Validate_submit.

Temporarily remove access to execute function

I'm working on a project where I on a website display content users can "interact" with using keypress W or P. Doing this, the site executes a function posting to a php writing to a mysql-database. However, if the key is pressed and HOLD or pressed multiple times in a row - I get multiple setTimeouts running and crap happens. How can I temporarily remove access to running (or disable) the keypress-functions when executed once?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript" src="jquery-1.6.4.min.js"></script>
<script language="javascript" type="text/javascript" src="jquery.jkey-1.2.js"></script>
<link rel="stylesheet" href="custom.css">
<script>
$(function content(){
var reloading = function(data){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var field1 = data[3];
_field1 = field1;
var field2 = data[4];
_field2 = field2;
var ans1 = data[5];
_ans1 = ans1;
var ans2 = data[6];
_ans2 = ans2;
var val1 = parseInt(ans1, 10) ;
_val1 = val1;
var val2 = parseInt(ans2, 10) ;
_val2 = val2;
$('#output').hide().html( message ).fadeIn("slow");
$('#username').hide().html( "#"+vname +":" ).fadeIn("slow");
$('#valg1').hide().html( field1 ).fadeIn("slow");
$('#valg2').hide().html( field2 ).fadeIn("slow");
window["reload_timer"] = setTimeout(reloading,6000);
}
});
}
reloading();
$(document).jkey('p',function() {
$.post("update.php", { "id": _id} )
$('#output').hide().html( "<i>Thx!</i>< ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
clearTimeout(window["reload_timer"]);
setTimeout(reloading,5000);
});
$(document).jkey('w',function() {
$.post("update.php", { "id2": _id} )
$('#output').hide().html( "<i>Thx!</i>< ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
clearTimeout(window["reload_timer"]);
setTimeout(reloading,5000);
});
});
</script>
</head>
<body><div id="container">
<div id="username">
</div>
<div id="output"></div>
<div id="posted"></div>
<div id="field1"></div>
<div id="valg1"></div>
<div id="valg2"></div>
</div>
</body>
</html>
Introduce a variable called e.g. blocked:
var blocked = false;
In the key handlers, abort if blocked and set blocked to true otherwise:
$(document).jkey('w',function() {
if(blocked) return; // abort
blocked = true; // disallow any further key presses
Unblock in the success handler of reloading:
success: function() {
blocked = false; // allow again
Add a flag and check it in your two keypress handlers:
var allowKeyPress = true;
$(document).jkey('p',function() {
if (!allowKeyPress)
return;
allowKeyPress = false;
// your existing code here
}
Somewhere else in your code you then set allowKeyPress = true; again - I'm not sure exactly where you want to do that: perhaps within your reloading() function, perhaps in the success callback from your $.ajax() (in which case really you should add an error or complete handler to reset the flag if the ajax call fails), or perhaps just with a new, separate setTimeout().

Categories

Resources