Show bootstrap modal when url has some parameters - javascript

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>

Related

How to avoid appending duplicates on ajax after second call?

I have a button called File which is a dropdown that has another button called open. Once the user clicks open I have an ajax GET request that appends a button after each call.
When the user clicks open once, the button is appended. However, when the user clicks open again, the same button is appended again with the same attributes and if the user clicks the open button the third time the button is appended once more, so a total of three times.
How do I ensure the button is only appended once?
The {{}} is from the django web framework and is not a concern
<input type = "button" class = "openGraph" value = "{{titles}}" id="{% url 'openGraph' title=titles.id %}">
This is the occurence when the user presses the open button.
$(document).ready(function(){
$('#openXML').on('click',function(event){
var csrftoken = getCookie('csrftoken');
$.ajax({
type: "GET",
url: "/loadTitles/",
dataType: 'text',
headers:{
"X-CSRFToken": csrftoken
},
success: function(data){
var json = JSON.parse(data)
var length = Object.keys(json).length
var pk = "/openGraph/" + json[length-1]['pk']
var title = json[length-1]['fields']['title']
myButton="<input type=\"button\" class = \"openGraph\" value=\""+title+"\" id="+pk+"/\>";
$("#loadAllTitles").append(myButton)
}
});
})
});
Because the IDs must be unique I'd suggest to test if the button already exist before adding. Hence, you need to change this line:
$("#loadAllTitles").append(myButton)
with:
if ($("#loadAllTitles").find('#' + $.escapeSelector(pk + '/')).length == 0)
$("#loadAllTitles").append(myButton)
I get the following console error: Uncaught Error: Syntax error, unrecognized expression: #/openGraph/104 –
If you are using jQuery 3.x you need to use:
jQuery.escapeSelector(): Escapes any character that has a special meaning in a CSS selector.
UPDATE
While pk is the ID when you create a new element you add to this ID a final /. This is your issue.
$('button').on('click', function(e) {
var pk = '#/openGraph/104';
var title='title';
myButton="<input type=\"button\" class = \"openGraph\" value=\""+title+"\" id="+pk+"/\>";
if ($("#loadAllTitles").find('#' + $.escapeSelector(pk + '/')).length == 0)
$("#loadAllTitles").append(myButton)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="loadAllTitles">
</form>
<button type="button">Click to add the same input field</button>
Check for the presence of a button on line 3
$(document).ready(function(){
$('#openXML').on('click',function(event){
if (!$('#+pk+').length) {
// Your code
}
}
}

Refresh Button when clicking on it

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.

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;
}

JavaScript href onclick not working with Perl

The below is my code. All my button functions are working perfectly, but if I click the link click the value of server should be remembered and the page should be reloaded again with the parameters view and subsys.
But the value for the server is empty when I getting reloaded.
my $server = $q->param('server') ;
my $unit = $q->param('unit') ;
my $bfile = __FILE__ ;
$bfile = `basename $bfile` ;
chomp $bfile ;
print "<form name=\"form1\" action =\"/cgi-bin/$bfile\" onsubmit=\"javascript:onsubmitform(doc_press)\">";
print "<input type=\"hidden\" name=\"server\" id=\"server\">";
print "<input type=\"hidden\" name=\"unit\" id=\"unit\">";
print "\n\n<input type=submit name=view value=\"View\" onClick=\"doc_press=this.value\">";
print "<input type=submit name=save value=\"Save\" onClick=\"doc_press=this.value\">";
print $var{$a}."<a href=\"/cgi-bin/$bfile?view=5&SUBSYS=$subsys\" onClick=javascript:click_page(\"$_\")>CLICK</a>\n" ;
print <<"END_OF_SCRIPT";
<script type="text/javascript">
function onsubmitform(doc_press) {
if (doc_press == "View"){
document.getElementById('unit').value="$unit";
}
else if (doc_press == "Save") {
END_OF_SCRIPT
var x = "$user=$val";
document.cookie=x;
document.getElementById('unit').value="$unit";
}
if (document.getElementById('HTTP_TYPE').value == "post") {
document.form1.method='post';
}
else if(document.getElementById('HTTP_TYPE').value == "get") {
document.form1.method='get';
}
}
function click_page(server){
document.getElementById('server').value=server;
}
</script>
END
When you click on a link (<a href="..."/>), the browser will make a new GET request for the given link, regardless of any forms you might have. This means that your form is NOT submitted; so any value in the form will be lost. For this reason, your onclick handler as posted here is useless.
Sometimes, if you’re really linking to the same page, modern browsers are smart enough to recognize that, and fill in the values you already had. This is only a commodity to users who get frustrated if their values are not kept, and so this doesn't work for hidden fields.
If you want clicking on the link to submit the form, you should either a) use a button, or b) change your onclick handler to submit the form and return false (so that the link isn’t followed):
function click_page(server){
document.getElementById('server').value=server;
document.forms[0].submit();
return false;
}
To make this work correctly, also change the onclick declaration:
CLICK

Categories