statusTxt, jqXHR not working in Iframe jQuery - javascript

I am trying to get the responseTxt, statusTxt, jqXHR output but it is not working in the iframe instead it only working in the load function. I have seen the related threads but it was not helpful.
I am trying after load iframe it will show an alert as LOADED as in my code but it not working.
Could you please help me to create this function how I get responseTxt, statusTxt, jqXHR response while iframe src change?
$(document).ready(function() {
$(document).on("click", "li> a[target='iframeload']", function(e) {
e.preventDefault();
var designation = $(this).attr("href");
if (!window.navigator.onLine) {
alert("Net Lost");
return false;
} else {
$("iframe#iframeID").attr("src", designation, function(responseTxt, statusTxt, jqXHR) {
if (statusTxt == "success") {
alert("LOADED");
} else {
if (statusTxt == "error") {
alert("Error : " + jqXHR.status + " " + jqXHR.statusText);
return false;
}
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

document.querySelector().getAttribute() didn't get fresh content meta name

I tried to implement codeigniter with $config['csrf_regenerate'] = TRUE;
I create code with combining javascript XMLHttpRequest & Jquery $.ajaxPrefilter.
I make a function for getting new csrf_hash from Codeigniter and append to meta name on HTML head.
At first request everything seems working.
But next request a got message 403 Forbidden because ajax send an old csrf hash.
Please fix my code.
I want before sending a POST request, ajax get new csrf hash form meta name on HTML head.
Sorry for my bad English.
Best Regards,
This is my code
$.ajaxPrefilter(function( options, originalOptions, jqXHR )
{
get_csrf_hash(callback => document.querySelector('meta[name="csrf_hash"]').setAttribute("content", callback) ); // It Work!!.. Get new csrf_hash and update content meta name.
if (options.type.toLowerCase() === "post")
{
options.data = $.param($.extend(originalOptions.data, { csrf_simpeg_v2 : document.querySelector('meta[name="csrf_hash"]').getAttribute("content")})); // Not Work didn't send fresh csrf hash
}
var originalSuccess = options.success;
options.success = function(data)
{
if (originalSuccess != null)
{
originalSuccess(data);
}
}
var originalError = options.error;
options.error = function (jqXHR, textStatus, errorThrown)
{
console.log(jqXHR.status + ' ' + jqXHR.statusText);
if(jqXHR.status == 401 || jqXHR.status == 403)
{
alert(jqXHR.status + ' ' + jqXHR.statusText);
}
else
{
if(originalError != null)
{
originalError();
}
}
};
});
function get_csrf_hash(callback)
{
var url = baseURL + 'login/get_csrf_token';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState == XMLHttpRequest.DONE)
{
console.log(xhr.responseText);
return callback(xhr.responseText);
}
}
xhr.open('GET', url, true);
xhr.send(null);
}
$(function () {
});
get_csrf_hash is an asynchronous function, meaning that the JavaScript runtime will not wait for it to finish its task before moving on to executing the next lines. You need to put all the code that depends on the first AJAX request inside the callback:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
get_csrf_hash(callback => {
document.querySelector('meta[name="csrf_hash"]').setAttribute('content', callback);
if (options.type.toLowerCase() === 'post') {
options.data = $.param(
$.extend(originalOptions.data, {
csrf_simpeg_v2: document.querySelector('meta[name="csrf_hash"]').getAttribute('content')
})
);
}
var originalSuccess = options.success;
options.success = function(data) {
if (originalSuccess != null) {
originalSuccess(data);
}
};
var originalError = options.error;
options.error = function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR.status + ' ' + jqXHR.statusText);
if (jqXHR.status == 401 || jqXHR.status == 403) {
alert(jqXHR.status + ' ' + jqXHR.statusText);
} else {
if (originalError != null) {
originalError();
}
}
};
});
});
You should look into the Fetch API and Promises. They will greatly simplify writing code like this. Here is the get_csrf_hash re-written using those tools:
function get_csrf_hash(callback) {
fetch('login/get_csrf_token')
.then(res => res.text())
.then(text => callback(text));
}

jQuery redirect is not working in Firefox

I'm trying to achieve redirection after values has been sent to my php script.
Value sent to the script correctly but redirect is not working in Firefox, in chrome it's also working fine.
This is piece of code where i put redirect.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseText;
// Show a thank you message
var theLanguage = $('html').attr("lang");
if (theLanguage == "nl-NL") {
url = "/Thanks/";
$(location).attr("href", url);
}
else if (theLanguage == "fr-FR") {
url = "/fr/merci/";
$(location).attr("href", url);
}
else {
url = "/en/thanks/";
$(location).attr("href", url);
}
}
Can anyone tell me what is the better way to do that which is cross browser compatible?
Thanks
Why not just submit the form and redirect from the server?
If you cannot just do that, then
Use jQuery since you have it
preventDefault on the submit event to not submit the form
You likely need this instead of your xmlhttprequest. Note the preventDefault
$(function() {
$("#yourFormId").on("submit", function(e) {
e.preventDefault(); // stop the submission
$.ajax({
type: 'post',
url: 'yourserverproces.php', // this.action will work if the form has an action
data: $(this).serialize(),
success: function(response) {
// Show a thank you message
var theLanguage = $('html').attr("lang"),
url = "/en/thanks/";
if (theLanguage == "nl-NL") {
url = "/Thanks/";
} else if (theLanguage == "fr-FR") {
url = "/fr/merci/";
}
location.href = url;
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
});
The location.href = "url" should work but if that gives you too many issues you can also try and use window.location.assign("url")

Why do I have to constantly trigger a GET request in this chat application?

I am new to AJAX and PHP, and I don't quite understand this code:
https://github.com/Artifx/PHP-and-MySQL-Web-Development-5th-Edition/blob/master/Chapter23/client.js
var pollServer = function() {
$.get('chat.php', function(result) {
if(!result.success) {
console.log("Error polling server for new messages!");
return;
}
$.each(result.messages, function(idx) {
var chatBubble;
if(this.sent_by == 'self') {
chatBubble = $('<div class="row bubble-sent pull-right">' +
this.message +
'</div><div class="clearfix"></div>');
} else {
chatBubble = $('<div class="row bubble-recv">' +
this.message +
'</div><div class="clearfix"></div>');
}
$('#chatPanel').append(chatBubble);
});
setTimeout(pollServer, 5000);
});
}
$(document).on('ready', function() {
pollServer();
$('button').click(function() {
$(this).toggleClass('active');
});
});
$('#sendMessageBtn').on('click', function(event) {
event.preventDefault();
var message = $('#chatMessage').val();
$.post('chat.php', {
'message' : message
}, function(result) {
$('#sendMessageBtn').toggleClass('active');
if(!result.success) {
alert("There was an error sending your message");
} else {
console.log("Message sent!");
$('#chatMessage').val('');
}
});
});
Is it not possible to trigger a GET request only after a POST request has been made? What is wrong with this logic, that makes it necessary to run the pollServer function every 5 seconds?

Javascript load file fails without error

When I run this:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
try {
$("#div1").load("demoddd.txt"); //there is no demoddd.txt
}
catch (err)
{
alert("Error: " + err); //this never runs
}
finally {
alert("Finally");
}
});
});
</script></head>
<body>
<button id="btn">Load file</button>
<div id="div1"></div>
</body>
</html>
I get "Finally" but no error. In the debug console, I see the 404. Can I trap 404 errors when using the load() function?
Use the complete function as shown in the documentation:
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
You need to get the httprequest status, you can't catch an 404 with that catch.
Use this:
$("#div1").load("/demoddd.txt", function(responseText, statusText, xhr){
if(statusText == "success")
alert("Successfully loaded!");
if(statusText == "error")
alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
});
The first thing I would try is to set the full URL, and not a relative one. See if that works first.

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