I am writing some JavaScript code, where I am using a closure for a counter. The code is given below:
function userHandler(){
var counter = 0;
var limit = "<?php echo ($_SESSION['limit']); ?>";
return function(){
var args = {
n : $('#name').val(),
s : $('#ssn').val(),
i : $('#id').val()
};
$.post("adduser.php",args,function(data){
var response = JSON.parse(data);
console.log(args);
if(response.status == 0){
counter += 1;
alert(counter);
if (counter == limit){
$('#limit').text(limit-counter);
}
}
console.log(data);
});
};
}
var opcall = userHandler();
$('#addUser').on("click", opcall);
I am using this guide to write the code. The problem is, my counter always shows 1 in the alert box. It does not increment. Am I not calling the inner method correctly?
EDIT: There's a span in the HTML which is receiving the limit-counter value:
<p>
<span>Add User</span>
You can add <span id="limit"></span> more users. <a href='<?php echo $root; ?>editaccount.php?action=addOp'>Add another operator?</a>
</p>
It always shows (20-1)=19 every time I submit the form which uses the Javascript.
UPDATE: Thank you for pointing out my mistake, after clicking the "addUser" button, another page was opening with a confirmation message, where a link had to be clicked to return to the original page. I moved the confirmation message to the original page and now it works fine!!
Related
i'm creating a form of inscription and i want to get info from a first page to show in a second one. I've tried to use local storage, but it doesn't work.
I've tried to test in the same page, which works, but when i try it with the localstorage, it doesn't work, and when i click on submit it reloads the page and nothing happens
Here is the code for the first page:
function rform()
{
document.getElemeentByName('insc').reset;
}
function client()
{
var sexe=document.getElemeentByName('gender');
var userT=document.getElementById('choice').selectedIndex;
var name = document.getEelementById('name').value;
localStorage.setItem('name',name)
if (userT[1] || userT[2] &&sexe[0].checked )
{
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice)
else
{
var res = document.getElementById('choice').value + 'e';
localStorage.setItem('choice',choice)
}
return false;
}
And the second page:
<span id="result"></span>
<script type="text/javascript">
document.getElementById("result").innerHTML= 'welcome '
+localStorage.getItem('name')+ ' you are '
+localStorage.getItem('choice');
</script>`
I get nothing in the second page, but expect to get a welcome message with the name and the user type
var choice = document.getElementById('choice').value;
localStorage.setItem('choice','choice')
This isn't setting the value of Choice into localStorage, this is simple setting the value of localStorage named Choice to the string "Choice".
Should be;
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice);
I'm trying to show a notifications counter updated upon javascript.
I have tried to use the following to refresh the html:
At the top of the page declaring the counter value (how many messages user has):
<?php
$nc = notificationCount($user_data['id']);
$ng = $user_data['id'];
if ($nc >= 1){
$nstyle = 'style="display:block;"';
} else {
$nstyle = 'style="display:block;"';
}
?>
Then the standard initial loading of the counter value that works properly:
<li id ="ndiv" class="nav-item pt8" <?php echo $nstyle; ?>><a href="javascript:void(0);" data-toggle="modal" data-target="#myModal" onclick="showUser(<?php echo $ng;?>)">
<i class="fa fa-bell f18 cr"></i><span id ="nc" class="f16 cr"><?php echo $nc;?></span></a>
</li>
In attempt to keep the counter refreshing every 5000 I tried the following, but it does not refresh despite the increase in value taking place.
<script>
function checkNotification() {
console.log(' each 5 second...');
document.getElementById("nc").value = "<?php echo $nc;?>";
}
var myVar = setInterval(checkNotification, 5000);
</script>
A PHP page returns a result to the client. Once the page returns its result, it's done. You can't have a PHP page return a result every so often. But, what you can do is call out to a PHP page (using AJAX) that returns the notification count at regular intervals using setInterval().
let notifications = document.getElementById("notifications");
// This would be a function that calls a .php page to get
// the notification count returned. You could use AJAX
// to make that call.
function simulateServerCode(){
return Math.floor(Math.random() * 100);
}
let timer = setInterval(function(){
notifications.textContent = simulateServerCode();
}, 5000);
<div>You have <span id="notifications"></span> notifications.<div>
You don't need the server side for showing the notifications.
Try this:
JS:
notificationsCount = document.getElementById("notificationsCount");
numberOfNotification = 10; // example
showing = setInterval(function(){
notificationsCount.textContent = numberOfNotificaton;
}, 5000);
HTML:
<h1>
Number of notifications <h1 id="notificationsCount"></h1>
</h1>
I got a button which i want to reload on click. But only the button should be reloaded, not the rest of the page.
The button looks like this:
<a href="{$module_data.GM_PRODUCTS_BUTTON_BUY_NOW_URL}" id="click{php}echo ''.$counter.'';{/php}" class="addcart button_green button_set action_add_to_cart"{if $module_data.PRODUCTS_NAME != ''} title="{$module_data.PRODUCTS_NAME|replace:'"':'"'} {$txt.text_buy}"{/if}
onclick="return checkAddToCart(event, '{$module_data.QTY_DATA.ID}', {$product_stock}, {$product_max_order}, {$module_data.PRODUCTS_ID}, {php}echo $row['customers_basket_quantity']{/php}, {php}echo "'click".$counter."'";{/php});">
<span class="button-outer">
<span class="button-inner">{$button.add_to_cart}</span>
</span>
</a>
Now i told javascript that echo "'click".$counter."'"; is the clickid.
I tried the following thing to reload my page on click:
function checkAddToCart(event, tid, stock, maxallowed, pid, pquantity, clickid)
{
var clickid_string = clickid.toString();
var bought = Number($("#"+tid).val());
stock = Number(stock);
maxallowed = Number(maxallowed);
var ans = (bought>stock) || (bought > maxallowed);
if(ans)
{
event.stopPropagation();
event.preventDefault();
alert("Maximale Bestellmenge: " + Math.min(maxallowed, stock));
}
else {
$("#"+clickid_string).load("#"+clickid_string);
}
return !ans;
}
It is not working, and i have absolutly no idea why. By the ay, my system works with SMARTY tpl.
If you want to run a php script on click of a button you need to learn ajax. Ajax its just a simple way to use javascript, to run pages in background without reload the current page.
<span class="button-outer" onClick="addDataToDB(this);">...</span>
<script>
function addDataToDB(el) {
var elem = $(el);
/* GET ALL YOUR DATA*/
var name = ...
/* Create an AJAX request to your phpfunction */
}
</script>
Check some tutorials in youtube.
I am trying to build a quiz environment. The user selects an answer and then clicks submit. Upon submit, the following jquery is called:
$(document).ready(function() {
$('.btn-large').click(function() {
$.post("correct_quiz.php",
{
choices : $('input[name=choice][type=radio]:checked').serialize()
},
function(data) {
var temp = '#correct' + data;
var temp2 = '#correct3';
$(temp).show(); // Make the wrong/right icons visible
});
});
});
This jquery makes a green or red icon appear, based on whether the answer was correct or not. The correct_quiz.php script contains:
<?php
$root = "/users/stadius/maapc/public_html/";
include($root . "connect_to_database.php");
$choices = $_POST['choices']; // This will for example output "choice=3"
echo substr($choices,7,7); // This will then output "3"
?>
I ran into a problem, when I try the above jquery code with variable temp2 the script works like I want. But when I try it with variable temp it doesn't. When I debug, I see that they contain exactly the same string though: both are '#correct3' (when I choose the 3rd answer).
So why is this not working when I use variable temp, and is working when using temp2?
I think your problem is in this line:
echo substr($choices,7,7);
Try to use:
$list = explode('=', $choices);
echo $list[1];
instead of substr
Below is a function where it controls whatever happens after a file has finished uploading in its own table row. Each table row consists of a file input where the user can upload a file and then the name of the file is appended within it's own table row.
If the upload was successful then it displays a successful message, if upload was not successful then it displays a message stating there is an error. But I also have another function within the function where the user can delete a file by clicking on the "Delete" button. The only problem I have is with this line of code:
$(".imagemsg" + counter).html(data);
Let's say that I have 2 table rows, and I delete a file in the first row, the message within .imagemsg should only be displayed in the first row as that was the row the deletion occured, it shouldn't display the message in the first and second row.
Another example is that if I have 4 table rows and I delete the file in the third row, then the message should be displayed in the 3rd row as that is where the deletion has occured.
So my question is what do I need to add to $(".imagemsg" + counter).html(data); so that the message is only displayed within the row the deletion of the file occured and not in all .imagemsg which is in every row?
Below is full code:
function stopImageUpload(success, imagefilename){
var result = '';
var counter = 0;
counter++;
if (success == 1){
result = '<span class="imagemsg'+counter+'">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
}
else {
result = '<span class="imageemsg">There was an error during file upload!</span><br/><br/>';
}
$(".deletefileimage").on("click", function(event) {
var image_file_name = $(this).attr('image_file_name');
jQuery.ajax("deleteimage.php?imagefilename=" + image_file_name)
.done(function(data) {
$(".imagemsg" + counter).html(data);
});
$(this).parent().remove();
});
return true;
}
BELOW IS HTML CODE:
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><p class='listImage' align='left'></p>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
I believe that your counter variable will always be 1. So, all your span.imagemsg1 are the same. This is why you get the message in every row. Set the counter outside the function to increment the counter.
I believe that will stop the behavior that you are seeing, but I would like to give a shout out to the other answers as they are giving good advice to cleaning this code up.
Frankly, you should never use unique identifier in the class. Why not use an id or a data-image-count attribute?
In your html code you'll need to add a unique identifier, I would suggest using id. This way when you try to reference the element to add the error message in, it will only find one element. Currently it's looking for the first occurrence of the element with class = "imagemsg". You'll need a way to loop through each "row" and make the id's "imagemgs1", "imagemsg2", etc...Hope it helps.
It would be helpful to be able to see the HTML. Also, I cannot see in your script what you do with the "result" value. At this stage, I personally don't think there is enough info to help satisfactorily you yet.
However, an issue you will undoubtedly see is with your "counter" variable. Maybe that is your problem - hard to tell without the detail I asked for above. Your jQuery.ajax call will complete at some point but the value of "counter" may not be the same as when you called the jQuery.ajax() method. This is because the "counter" variable is being declared in a different scope.
E.g. Look at the code below. It sort of demonstrates your problem with the counter variable. It may look like at the end of 5 seconds it will spit out the numbers from 1 to 10 but it won't. It will spit out the value "10" ten times.
var x = 0;
for (var i = 0; i < 10; i++)
{
x++;
setTimeout(function() { console.log(x); }, 5000);
}
This problem applies to your code as well. You can fix the above by copying the variable value in to a variable of your local scope. E.g.:
var x = 0;
for (var i = 0; i < 10; i++)
{
var newScope = function() {
x++;
var y = x;
setTimeout(function() { console.log(y); }, 5000);
}();
}