href not working in greasemokey - javascript

I have following code in my greasemonkey script. In case, i am unable to save my order to server, i display an error message and then a link (created using <a href> to save it again. this link is save_order method again. But this is not working. I tried debugging into it but no luck. (I have basic understanding of JavaScript)
function save_order() {
server_url = 'https://server.com/api/put_order?user_id=' + form.user.value +'&order_id=' + orderId;
GM_xmlhttpRequest({
method: "GET",
url: server_url,
onload: function(response){
if(response.status == 200){
localstorage.removeItem(orderId);
messageBar.innerHTML += '<br/>Order has been saved successfully.';
} else {
if (errorBar.style.display === 'none'){
errorBar.style.display = 'block';
}
errorBar.innerHTML += '<br/>Error saving. <b>Try Again</b>';
}
}
});
}
=======
FULL CODE
// ==UserScript==
// #name SaveOrder
// #version 1.0
// #author myname
// #include https://xx*.xxxxxxxx.com*/*
// #run-at document-end
// #grant GM_xmlhttpRequest
// ==/UserScript==
var saveButton = document.getElementById('save-button');
saveButton.addEventListener("click", save_order,true);
var info_bar = document.getElementById('info_bar');
var error_bar = document.getElementById('error_bar');
var form = document.getElementById('place_order_form');
var order_id = form.order_id.value;
var localstorage = window.localStorage;
if (localstorage.getItem(order_id)){
save_to_db();
}
function save_order(){
localstorage.setItem(order_id, order_id);
}
function save_to_db() {
var random_boolean = false;//Math.random() >= 0.5;
console.log(random_boolean);
server_url = 'https://xxx.xxxx.com/api/put_order?user_id=' + form.user.value +'&order_id=' + order_id;
GM_xmlhttpRequest({
method: "GET",
url: server_url,
onload: function(response){
if(response.status == 200 && random_boolean){
localstorage.removeItem(order_id);
info_bar.innerHTML += '<br/>Order saved successfully';
} else {
if (error_bar.style.display === 'none'){
error_bar.style.display = 'block';
}
error_bar.innerHTML += '<br/>Error saving. <b>Try Again</b>';
}
}
});
}

Your method works just fine, as you can see in this example.
You probably have an error elsewhere.
function test(){
document.body.innerHTML += '<a class="function-link" href="#" onclick="test();">Test</a>';
}
<a class="function-link" href="#" onclick="test();">Test</a>
EDIT : I did some digging, and found a way around your issue.
Instead of adding an onclick on your link, create an event handler in javascript attached to a save-to-db class like this :
document.addEventListener("click", function(e) {
if (e.target.closest('a') && e.target.closest('a').classList.contains("save-to-db")) {
save_to_db();
}
});
Now all you need to do is get rid of your onclick and replace it with class="save-to-db"
document.body.innerHTML += '<br/>Error saving. <b>Try Again</b>';
It works like a charm now :
document.addEventListener("click", function(e) {
if (e.target.closest('a') && e.target.closest('a').classList.contains("save-to-db")) {
save_to_db();
}
});
save_to_db();
function save_to_db() {
console.log('Function called');
document.body.innerHTML += '<br/>Error saving. <b>Try Again</b>';
}

Related

Can't update iframe's src in the viewer in ASP.NET

In shared folder of ASP.NET C#, I create a .cshtml which defines a button that can GET data from an API. I would like to generate an url and use it to update an iframe of a viewer.
function callAPI(searchText) {
$.ajax({
url: '/Home/CallAPI',
data: { Text: searchText },
type: "GET",
success: function (result) {
var data = JSON.stringify(result); // server response
found_data = data;
$(result).each(function () {
if (this.status == "found") {
alert("Found!" + data);
var frameElement = document.getElementById("SearchingMap");
lon = result.results[0].lon;
lat = result.results[0].lat;
new_searching_url = "http://xx.xxx.xxx.xxx:8080/styles/osm-bright-tw/#17/" + lat.toString() + "/" + lon.toString();
console.log(frameElement.src); // undefined
frameElement.src = new_searching_url;
console.log(frameElement.src); // "http://xx.xxx.xxx.xxx:8080/styles/osm-bright-tw/#17/.../..."
}
else {
alert("Sorry! Not found");
}
});
},
error: function () {
alert("Sorry! Not found");
}
});
}
However, the iframe in the viewer, which named SearchingMap.cshtml, doesn't updated.
#{ViewBag.Title = "SearchingMap";}
<div id="SearchingMap">
<h3>Searching map</h3>
<iframe src="http://xx.xxx.xxx.xxx:8080/styles/osm-bright-tw/#10.01/25.0709/121.5008" frameborder="0" scrolling="no">Your browser doesn't support iframe.</iframe>
</div>
Why can't it work? How can I update the iframe of a viewer?
Here the iframe did not have the id SearchingMap so all javascript code fails because of this line:
var frameElement = document.getElementById("SearchingMap");
Just add this id, on your iframe
<iframe id="SearchingMap" ...

Copy jQuery object to modal, then hide or show, then display

I want to display a footer within a modal only when user is logged in (via ajax).
I want the footer itself to be contained in the main HTML page, which can be over-ridden by other users.
So I have a hidden container holding it on the main page:
<div style="display:none" id="signupModalFooterContainer">
<div class="modal__footer btn-group" class="signupModalFooter">
You are logged in
</div>
</div>
I can add it to the popup content:
popUpContent += $('#signupModalFooterContainer').html();
How can I make the browser re-draw the modal content between running $('.signupModalFooter').show() or $('.signupModalFooter').hide() after adding it to the window?
Empty and Replace your html content before showing
if (loggedin == 'yes') {
$('.signupModalFooter').html('You are logged in');
} else {
$('.signupModalFooter').html('');
}
$('.signupModalFooter').show();
What I ended up doing, recommended by a mentor, is to
create a "state object" which tracks the "logged in" state as well as holding various other attributes.
create two render() functions, one to render the modal main content and one to render the inner content, when events are showing feedback within the modal.
The state object looks like this:
var my_state = {
logged_in: (wordpress_i18n_key.loggedIn == 1) ? true : false,
message: undefined,
inner_container: '<div id="innerDiv"></div>',
other_attribute: undefined,
// Grab the login form from a hidden container in the DOM
login_form: $('#LogInContainer').html(),
initialize: function(target){
this.target = $(target).attr("href");
this.siteID = $(target).attr('data-someData');
}
}
Where wordpress_i18n_key.loggedIn is either a 0 or 1 that wordpress prints out to the HTML page in a <script></script> tag to make php variables available to javascript.
This function renders the main modal content:
function render_modal(){
var message = (my_state.message ? '<p>'+my_state.message+'</p>' : '');
my_state.wrapper = '<div class="modal__wrapper" id="wrapperDiv">';
if (my_state.logged_in){
my_state.wrapper += my_state.header;
my_state.wrapper += '<div class="modal__content" id="contentDiv">'+message+my_state.signup_button+'</div>';
my_state.wrapper += my_state.footer;
} else {
my_state.wrapper += my_state.header;
my_state.wrapper += '<div class="modal__content" id="contentDiv">'+message+my_state.login_form+'</div>';
}
my_state.wrapper += '</div>';
if ($('#cboxLoadedContent')) {
$('#cboxLoadedContent').html(my_state.wrapper);
}
my_state.message = undefined;
}
Where #cboxLoadedContent is the main container in the colorbox.js modal.
Then for activity that should show feedback within part of the modal:
function render_inner_modal_activity(){
my_state.content = '';
$('#innerDiv').html = '';
if (my_state.action == 'processing'){
my_state.content += my_state.spinner;
} else if (my_state.action == 'login_failed') {
my_state.content += my_state.message;
my_state.content += my_state.login_form;
} else {
// login, sign_up_form, etc
my_state.content += my_state.message;
}
if ($('#innerDiv')) {
$('#innerDiv').html(my_state.content);
}
}
When user clicks modal page button:
/**
* Initial Modal Window to Register for a Class
*
* Also leads to options to login and sign-up with API
*
*/
$(document).on('click', "a[data-target=someButton]", function (ev) {
ev.preventDefault();
my_state.initialize(this);
render_mbo_modal();
$("#modalContainer").load(my_state.target, function () {
$.colorbox({html: my_state.wrapper, href: my_state.target});
$("#modalContainer").colorbox();
});
});
Filling out the modal form, feedback stays in the modal:
/**
* Sign In to API
*/
$(document).on('submit', 'form[id="login"]', function (ev) {
ev.preventDefault();
var form = $(this);
var formData = form.serializeArray();
var result = { };
$.each($('form').serializeArray(), function() {
result[this.name] = this.value;
});
$.ajax({
dataType: 'json',
url: mz_mindbody_schedule.ajaxurl,
type: form.attr('method'),
context: this, // So we have access to form data within ajax results
data: {
action: 'client_log_in',
form: form.serialize()
},
beforeSend: function() {
my_state.action = 'processing';
render_mbo_modal_activity();
},
success: function(json) {
var formData = $(this).serializeArray();
var result = { };
$.each($('form').serializeArray(), function() {
result[this.name] = this.value;
});
if (json.type == "success") {
my_state.logged_in = true;
my_state.action = 'login';
my_state.message = json.message;
render_mbo_modal();
} else {
my_state.action = 'login_failed';
my_state.message = json.message;
render_mbo_modal_activity();
}
} // ./ Ajax Success
}) // End Ajax
.fail(function (json) {
my_state.message = 'ERROR SIGNING IN';
render_mbo_modal_activity();
console.log(json);
}); // End Fail
});
And this is the outer container the modal initially references:
<div class="modal fade" id="modalContainer" tabindex="-1" role="dialog" aria-labelledby="mzSmallModalLabel" aria-hidden="true"></div>

Trigger a php script using ajax - how and where to program this?

Good day,
I have a php file (db.php) which contains the following function
function edit_record($id, $value){
if($this->db->query('UPDATE tbl_prototype SET value = ' . $value .' WHERE id_component = '.$id)){
$this->register_changes();
return TRUE;
}
return FALSE;
}
Besides, I have some checkboxes in my html page as follows :
<input id="chk01" type="checkbox" data-onstyle="success" data-toggle="toggle">
<input id="chk02" type="checkbox" data-onstyle="success" data-toggle="toggle">
the html page contains also the following script.
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php',
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* check if with response we got a new update */
if(response.update==true){
var j = response.news;
$('#message-list').html(response.news);
sayHello(j);
}
});
};
//Every 1/2 sec check if there is new update
setInterval(check,500);
</script>
<script>
function sayHello(j){
var json=$.parseJSON(j);
var techname = "";
var techname1 = "";
var c;
var w;
$(json).each(function(i,val){
$.each(val,function(k,v){
if (k=="tech_name")
{
techname = "#" + v;
techname1 = v;
}
else
{
console.log("Mon nom est " + techname + " et ma valeur est " + v);
c=document.getElementById(techname1);
if (c.checked)
{
w = 1;
}
else
{
w = 0;
}
console.log(w);
console.log("techname : " + techname1);
if (v != w)
{
console.log ("Pas identique");
if (v==0)
{
// false
uncheckBox(techname);
}
else
{
// true
checkBox(techname);
}
}
else
{
console.log ("Identique");
}
}
});
});
}
function checkBox(pCtrl)
{
toggleOn(pCtrl);
}
function uncheckBox(pCtrl)
{
toggleOff(pCtrl);
}
</script>
Now for my question: where and how should I specify that I would like to run the function 'edit_record' stored in the 'db.php' file with the two parameters ($id and $value).
Contents of 'checker.php' :
<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
//if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
if(isset($_POST)){
$data['news'] = $db->get_news2();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
Thanks a lot for your valuable inputs. Sorry if the question sounds silly (I'm a newbie in php/ajax/jquery programming).
In modern web apps with rich interface You should go for REST API and create controller which should be in You case in checker.php. Example ( checker.php ):
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//update code
edit_record($_POST['id'],$_POST['counter]);
}
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
//get code
}
ps. i do not see passing id in ajax, you send only counter, so you should add id like:
...
data: {
id:yourId //here your id
counter:$('#message-list').data('counter')
}
Next thing remove from js:
setInterval(check,500);
and create bind:
$("yourcheckboxselector").on("click",function(e){
check($(this).prop("checked") ) //here you have it was checked or not as boolean
});

Prevent users from opening multiple instance of same website PHP

I need only one tab accessible for my website. When he tries to open in new tab or even tries to copy and paste the url in new tab should clear the user's session and logout from the application.
There are several reasons,
When a user opens a new tab connecting to the same application - the session id is the same.
Imagine that this user has reached a page X in the application flow from the first tab.
When he opens the second tab he might be in one of the following scenarios - depending how the second tab was opened - new tab, duplicate tab (this copies the URL to the newly opened tab), or new session.
All of the above will "confuse" the server as to what the next valid state of the application is, and could override data entered in different tab, without his/her knowledge
What I want is to prevent a single user to have several tabs in the same session, i.e. only one tab/window per user, per session.
Including the below script in dashboard.php after login
<script>
$(document).ready(function()
{
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
else
{
sessionStorage.pagecount = 1;
}
}
else
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
});
Below code in other sub pages in the application
<script>
$(document).ready(function()
{
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
sessionStorage.pagecount = Number(sessionStorage.pagecount) + 1;
}
else
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
}
else
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
});
</script>
Added the below script after I login(say dashboard.php)
<script>
$(document).ready(function()
{
$("a").attr("target", "");
if(typeof(Storage) !== "undefined")
{
sessionStorage.pagecount = 1;
var randomVal = Math.floor((Math.random() * 10000000) + 1);
window.name = randomVal;
var url = "url to update the value in db(say random_value)";
$.post(url, function (data, url)
{
});
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>
Added the below script in Header in rest of my pages - 'random_value' is from db for that user
<script>
$(document).ready(function()
{
$("a").attr("target", "_self");
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
if('<?=$random_value?>' == window.name)
{
sessionStorage.pagecount = Number(sessionStorage.pagecount) + 1;
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>
<script>
$(document).ready(function()
{
$("a").attr("target", "");
if(typeof(Storage) !== "undefined")
{
sessionStorage.pagecount = 1;
var randomVal = Math.floor((Math.random() * 10000000) + 1);
window.name = randomVal;
var url = "url to update the value in db(say random_value)";
$.post(url, function (data, url)
{
});
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>

Breaking out of iframes with Javascript

Edit (rephrasing): the website is loaded within an iframe, but there is 1 link inside the iframe which I would like to take the user out of the iframe when they click it, back into the main window that underlays the iframe.
I've found
top.location.href = 'page.htm';
, but I wouldn't know how to enter it into this 'complex' code.
This is the file I believe it should be in:
{literal}
$(document).ready( function() {
$('#payment_paypal_express_checkout').click(function() {
$('#paypal_payment_form').submit();
return false;
});
$('#paypal_payment_form').live('submit', function() {
var nb = $('#quantity_wanted').val();
var id = $('#idCombination').val();
$('#paypal_payment_form input[name=quantity]').val(nb);
$('#paypal_payment_form input[name=id_p_attr]').val(id);
});
function displayExpressCheckoutShortcut() {
var id_product = $('input[name="id_product"]').val();
var id_product_attribute = $('input[name="id_product_attribute"]').val();
$.ajax({
type: "GET",
url: baseDir+'/modules/paypal/express_checkout/ajax.php',
data: { get_qty: "1", id_product: id_product, id_product_attribute: id_product_attribute },
cache: false,
success: function(result) {
if (result == '1') {
$('#container_express_checkout').slideDown();
} else {
$('#container_express_checkout').slideUp();
}
return true;
}
});
}
$('select[name^="group_"]').change(function () {
displayExpressCheckoutShortcut();
});
$('.color_pick').click(function () {
displayExpressCheckoutShortcut();
});
{/literal}
{if isset($paypal_authorization)}
{literal}
/* 1.5 One page checkout*/
var qty = $('.qty-field.cart_quantity_input').val();
$('.qty-field.cart_quantity_input').after(qty);
$('.qty-field.cart_quantity_input, .cart_total_bar, .cart_quantity_delete, #cart_voucher *').remove();
var br = $('.cart > a').prev();
br.prev().remove();
br.remove();
$('.cart.ui-content > a').remove();
var gift_fieldset = $('#gift_div').prev();
var gift_title = gift_fieldset.prev();
$('#gift_div, #gift_mobile_div').remove();
gift_fieldset.remove();
gift_title.remove();
{/literal}
{/if}
{if isset($paypal_confirmation)}
{literal}
$('#container_express_checkout').hide();
$('#cgv').live('click', function() {
if ($('#cgv:checked').length != 0)
$(location).attr('href', '{/literal}{$paypal_confirmation}{literal}');
});
// old jQuery compatibility
$('#cgv').click(function() {
if ($('#cgv:checked').length != 0)
$(location).attr('href', '{/literal}{$paypal_confirmation}{literal}');
});
{/literal}
{else if isset($paypal_order_opc)}
{literal}
$('#cgv').live('click', function() {
if ($('#cgv:checked').length != 0)
checkOrder();
});
// old jQuery compatibility
$('#cgv').click(function() {
if ($('#cgv:checked').length != 0)
checkOrder();
});
{/literal}
{/if}
{literal}
var modulePath = 'modules/paypal';
var subFolder = '/integral_evolution';
var fullPath = baseDir + modulePath + subFolder;
var confirmTimer = false;
if ($('form[target="hss_iframe"]').length == 0) {
if ($('select[name^="group_"]').length > 0)
displayExpressCheckoutShortcut();
return false;
} else {
checkOrder();
}
function checkOrder() {
confirmTimer = setInterval(getOrdersCount, 1000);
}
{/literal}{if isset($id_cart)}{literal}
function getOrdersCount() {
$.get(
fullPath + '/confirm.php',
{ id_cart: '{/literal}{$id_cart}{literal}' },
function (data) {
if ((typeof(data) != 'undefined') && (data > 0)) {
clearInterval(confirmTimer);
window.location.replace(fullPath + '/submit.php?id_cart={/literal}{$id_cart}{literal}');
$('p.payment_module, p.cart_navigation').hide();
}
}
);
}
{/literal}{/if}{literal}
});
{/literal}
Edit: found some part of the HTML as well, figured it'd be easy to do there, but it doesnt actually seem to work. Perhaps because of the void(0)?
<a href="javascript:void(0)" target="_top" onclick="$('#paypal_payment_form').submit();" id="paypal_process_payment" mod='paypal'}">
Perhaps someone here can help me out. Thanks in advance!
Best,
Dave
This is some JavaScript that will redirect the user out of the iframe to the website if the website is being 'iframed':
<script>if (top !== self) top.location.href = self.location.href;</script>
I do not see a portion of the code for your form, but since you are using submit() you can set the target of the form to _top:
<form target="_top" action="yoururl.php" id="paypal_payment_form">
Then once you use submit, it will break the frames and continue to the new page.
<a href="#" onclick="$('#paypal_payment_form').submit();" id="paypal_process_payment" mod='paypal'>

Categories