Refresh Button when clicking on it - javascript

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.

Related

Counter in Javascript closure not incrementing

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!!

download file without using ajax

I am trying to follow this example to show progress bar without using ajax to download file.
I use knockout,html and webapi. I am having below code which calls href on click event of button
this.getMeData= function () {
uRlPath("/api/GetSomeData?id=" + 12)
+ "&name=" + getName.toString()
+ "&downloadtoken=" + new Date().getTime());
$('#myLink').click();
location.href = $('#myLink').attr('href');
};
This is my html
<tr>
<td class="labelText">
<button data-bind="click: getMeData">
Download Data
</button>
</td>
</tr>
<tr>
<td>
<a id="myLink" data-bind="attr: { href: uRlPath }" style="visibility: hidden">Open </a>
</td>
</tr>
I now want to call some function on click event of my href
This is my webapi method which returns me cookie and binary file
public HttpResponseMessage GetSomeData(int id, string name, string downloadtoken)
{
var returnData= new HttpResponseMessage(HttpStatusCode.OK);
returnData.Content = new ByteArrayContent(mybyteArray);
var cookie = new CookieHeaderValue("downloadtoken", downloadtoken);
returnData.Headers.AddCookies(new CookieHeaderValue[] { cookie });
returnData.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
returnData.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
returnData.Content.Headers.ContentDisposition.FileName = "myfile.pdf";
return returnData;
}
To be very precise i want to have same behaviour as provided in example. In example they use form to submit but i dont have any form as i just use html,knockout. I have included all libraries mentioned in example.
Do let me know if you need more inputs.
I found solution myself. I used below code to check constantly for cookie
var attempts = 30;
var checkTime
startProgressBar(true)
checkTime= window.setInterval(function () {
var cookieValue = $.cookie('downloadtoken');
if ((cookieValue == token) || (attempts == 0)){
stopDownload();
}
attempts --;
}, 1000);
In finishDownload function i clear cookie and stop progress bar
function stopDownload() {
window.clearInterval(checkTime);
$.cookie('downloadtoken', null); //clears this cookie value
stopProgressBar(false);
}
This is html code for progress bar
<div data-bind="visible: stopProgressBar" style="top:248px;left: 320px;">
<img src="../images/ProgressBar.jpg" />
</div>
If you just want to call the blockUIForDownload function when the link is clicked, you can do it with a "click" binding, just like you did for the button:
<a id="myLink" data-bind="attr: {href: uRlPath}, click: blockUIForDownload" style="visibility: hidden">Open</a>
(This assumes the function is already defined within the viewModel.)
See official documentation for the "click" binding here: http://knockoutjs.com/documentation/click-binding.html
However, it looks to me like you're overcomplicating it a bit - in the example you posted, a hidden input field is required because they're using a form input as a means to transfer the token to the server.
In your case the token is passed as a part of an href attribute, so you can greatly simplify the code:
1) Remove the invisible link completely
2) Replace the getMeData function with the following:
this.getMeData= function () {
window.open("/api/GetSomeData?id=" + 12
+ "&name=" + getName.toString()
+ "&downloadtoken=" + new Date().getTime());
blockUIForDownload();
};

How to show a popup before submitting the information

I am using Asp.Net/C# , I am having a requirement wherein I want to display a confirm before submission of data , if user clicks OK button , then proceed , or else cancel the submission.I know javascript confirm box does this , but in my case I need to show my own popup , Can anyone suggest me how can I achieve this.I would not want to use any plugin here.
Thanks for any suggestions.
you can create as follow:
function createPopup() {
//Get the data from the form fields
var background = document.custom.back.value;
var title = document.custom.title.value;
var text = document.custom.text.value;
//Now create the HTML code that is required to make the popup
var content = "<html><head><title>"+title+"</title></head>\
<body bgcolor='"+background+"'><h1>"+title+"</h1>"+text+"<br />\
<a href='javascript:window.close()'>Close the popup</a></body></html>";
//Create the popup
var popup = window.open("","window","resizeable,width=400,height=300");
popup.document.write(content); //Write content into it.
pops.document.close();
}
the logic should like as follow: i have not executed and tested just see the logic ignore minore mistakes if any.. also set the layout, border look like the confirmation window.
function popup() {
alert('popup called');
//Now create the HTML code that is required to make the popup
var content = "<html><head><title>ConfirmBox</title></head><body >Do you want to continue ? <br />
<input type='button' value='ok' onclick='return true'/>
<input type='button' value='cancel' onclick='return false'/> <a href='javascript:window.close()'>Close the popup</a></body></html>";
//Create the popup
var popup = window.open("","window","resizeable,width=400,height=300");
popup.document.write(content); //Write content into it.
pops.document.close();
}
refer http://www.openjs.com/tutorials/advanced_tutorial/popup.php

using the method onclick () to trigger a function that opens a window it grabs from the clicked button

<script language="JavaScript">
function goThere()
{
var the_url = window.document.form.button.value;
var good_url = fixURL(the_url);
var new_window = window.open(good_url,"new_window","menubar,resizeable");
}
function fixURL(the_url)
{
var the_first_seven = the_url.substring(0,7);
the_first_seven = the_first_seven.toLowerCase();
if (the_first_seven != 'http://')
{
the_url = "http://" + the_url;
}
return the_url;
}
</script>
</head>
<body>
<form name="the_form" onclick="goThere()"; return false;">
<input type="button" name="the_url" class="broadGroups" onClick="goThere()" value="http://en.wikipedia.org/wiki/Category:Sports"></input>
<input type="button" name="the_url" class="broadGroups" onclick="goThere()" value="http://en.wikipedia.org/wiki/Category:Film"></input>
</form>
</body>
</html>
So this code may be totally messed up, but here is what I am trying to do.
There are two buttons inside the tag. I want each to use the method onsubmit to trigger the function goThere(). How do I set it up so that the_url is set to a value that I pull from the button tag. I also want to be able to put non-url text on the button itself while allowing it to call goThere () through the method call onsubmit.
In the end it should just take the url, make sure it starts with http:// (in this case it doesnt matter because the user isn't inputting the url, but I'd like to keep it in for other purposes later on) and open it in a new window with a menubar and the resizable property.
Sorry for the long post. Any help would be greatly appreciated.
Pass in this in your goThere call. This will bring in the clicked element to your goThere function. Then you access the attributes for the clicked button.
http://jsfiddle.net/wJMgb/
onClick="goThere(this)"
function goThere(elem) {
var the_url = elem.value;
var good_url = fixURL(the_url);
var new_window = window.open(good_url, "new_window", "menubar,resizeable");
}
function fixURL(the_url) {
var the_first_seven = the_url.substring(0, 7);
the_first_seven = the_first_seven.toLowerCase();
if (the_first_seven != 'http://') {
the_url = "http://" + the_url;
}
return the_url;
}

Show bootstrap modal when url has some parameters

I'm new to develop web apps, I'm creating a mini project which has a simple signup, signing system, I don't want user to go to a different page to login, instead I have used a bootstrap modal which has a login form for which I have a button that on click also changes the url and also triggers the modal. Now I only want to show the modal, if url has parameter = ?action=login.
Firstly, I have tried document.getElementById('#myBtn').addEventListener('click', setQry) to my button which calls the function which on click changes the url parameter. The url parameter changes on click really fine, but the modal does not show up, please note that I have data-target and data-toggle attributes on my button for the modal to show. I have also tried this example. But its not working.
I just want to achieve that modal should show up, if url has the parameter
and on login success I want to hide the modal and also delete the url parameter.
Here's my HTML:
<button type='button' id='toggle-modal' data-toggle='modal' data-target='#login-modal'></button>
My JavaScript:
document.getElementById('#toggle-modal').addEventListener('click', setQry);
function setQry() {
const url = new URL('http://localhost/learning%20php/practice%20programs/login%20system/');
var qry_params = new URLSearchParams(url.search);
if (!qry_params.has('action', 'login')) {
qry_params.set('action', 'login');
window.location.search = qry_params;
}
if (window.location.search == qry_params) {
$('#login-modal').modal('show');
}
};
This code should work, your handler only fires on click, it doesn't have effect on page load, for this reason, it should be called to handle parameters on a page loading, sorry for my bad english
setQry();
function setQry() {
const url = new URL('http://localhost/learning%20php/practice%20programs/login%20system/');
var qry_params = new URLSearchParams(url.search);
if (!qry_params.has('action', 'login')) {
qry_params.set('action', 'login');
window.location.search = qry_params;
}
if (window.location.search == qry_params) {
$('#login-modal').modal('show');
}
};
Consider using PHP for that. You can get the GET Params in PHP and then change the content dependent on the get parameters.
<?php
if ($_GET['action'] == "login")
{
?>
<!-- Add content in html if action code is set to "login" -->
<?php
}
else
{
....
}
?>
The event is called twice when the button is clicked. so I have remove other attributes from button.
<button type='button' id='toggle-modal' ></button>
the # used in document.getElementById('#toggle-modal').addEventListener('click', setQry); is also creating the issue.
setting parameters in javascript qry_params.set('action', 'login'); is refreshing the page. so the popup gets close.
so the update code is given below hope it will resolve the issue
``'`
<button type='button' id='toggle-modal' ></button>
<script>
document.getElementById('toggle-modal').addEventListener('click', setQry);
function setQry() {
const url = new URL('http://localhost/learning%20php/practice%20programs/login%20system/?action=login');
var qry_params = new URLSearchParams(url.search);
if (window.location.search.replace("?", "") == qry_params) {
$('#login-modal').modal('show');
}
}; </script>

Categories