window.Open Open popup Instead of new window - javascript

I have a, ajax function in jQuery and I want in complete function to open a url in a new window or tab.
Link
And :
function Add(ID, url)
{
var data = "{'ID' : '" + ID + "'}";
$.ajax({
type: "POST",
url: "Function.ashx/Add",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function ()
{
window.open(url);
}
});
}
window.open function works as popup but I want to open the link in a new window. w3School Example works prefect.
But my browser detects it as a popup and blocks it.
What's wrong with my code?

Why do you specifically wait till the AJAX call completes to load the URL?
Why not simply trigger the AJAX call and open the new window directly after.
Example:
Link
function Add(ID, url)
{
var data = "{'ID' : '" + ID + "'}";
$.ajax({
type: "POST",
url: "Function.ashx/Add",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
window.open(url);
}

I'm guessing w3cschool.com probably gets the popup previlige for being an authorised tutoring site.
AFAIK, any means to open an extra window without direct user interaction (e.g. a click) is considered a "popup" and would be blocked by most of the browsers with popup blocker enabled. Your best bet is probably open the link upon a click and inject whatever you want upon the AJAX completion:
Link
function Add(ID, url)
{
var newWindow = window.open(url);
var data = "{'ID' : '" + ID + "'}";
$.ajax({
type: "POST",
url: "Function.ashx/Add",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (data)
{
// do whatever you want with newWindow
}
});
}

Related

Lock state multiple ajax calls

I have multiple rich text editors on single page.
There is autosaving of both done by ajax calls that are separate.
Each text editor is saved on focus lost or when focus is inside of editor every 20 seconds.
When editor is not saved and user navigates away I am showing "navigate away warning".
Now I need to manage warning that when one editor is in the middle of saving and the other one finishes earlier warning will not be removed.
What I have now:
editorOneIsSaving=true;
SetNavigateAwayNotification();
$.ajax({ type: "POST", contentType: "application/json",
dataType: 'json', url: "/SaveEditorOne",
data: mypostdata1,
success: function (msg) {
editorOneIsSaving = false;
if (!editorTwoIsSaving) {
RemoveNavigatingAwayNotification();
}
updateSavedInfo();
},
});
For second editor:
editroTwoIsSaving=true;
SetNavigateAwayNotification();
$.ajax({ type: "POST", contentType: "application/json",
dataType: 'json', url: "/SaveEditorTwo",
data: mypostdata2,
success: function (msg) {
editorTwoIsSaving = false;
if (!editorOneIsSaving) {
RemoveNavigatingAwayNotification();
}
updateSavedInfo();
}
});
I was looking into adding object to array or list but it is not really nice in javascript. This way I would know who is the owner of lock or if there would be more editors I could make sure that same editor is not taking lock multiple times.
Maybe I am just overthinking and I should go with simply counter which if is 0 then remove navigate away.
One way to do this would be to add a counter to each ajax call to save.
You increment the counter before sending the data to the server and decrement it in the promise.
something like the following
function showSavingMessage(){
//code to show message
}
function removeSavingMessage(){
// code to remove message
}
var ctr = 0;
function saveData(){
showSavingMessage();
ctr++;
$.ajax({ type: "POST", contentType: "application/json",
dataType: 'json', url: "/SaveEditorXXX",
data: mypostdata2,
success: function (msg) {
if (ctr > 0){
ctr--;
} else {
removeSavingMessage();
}
}
});
}
You can handle errors any way you like. may be change the "saving" message to error message.
You can also pass the url and the data to the saveData function to make it reusable, so you have a single function with the Ajax code.

AJAX Only Runs On First Page Load

I have a webpage that dynamically creates URLs on page load. The first time these links are clicked, they call a ajax query to load page data and it works perfectly. However, the second time the query is not executed and the data remains the same from the previous load.
Here is HTML code in activitylog.aspx where the URL items are added:
<ul class="ver-inline-menu tabbable margin-bottom-10 incidentlist"></ul>
Here is the jQuery Code in activitylog.aspx that is run on startup:
$(document).ready(function () {
// Get Parameter Values
var paramShiftId = getURLParameter('shift_id');
var paramIncidentId = getURLParameter('incident_id');
// Run Data Handler Query
$.ajax({
url: "queries/dataHandler_getShiftInfo.ashx",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { shift_id: paramShiftId, incident_id: paramIncidentId },
responseType: "json",
success: OnViewComplete,
error: OnViewFail
});
return false;
function OnViewComplete(result) {
//Cycle Through JSON Rows
$.each(result.aaData, function (i, row) {
$(".incidentlist").append("<li>" + row.INC_NUMBER + " </li>");
}
}
});
How do I create dynamic URLs that will load a refreshed page each time?
Ajax is something about no need to reload a page...
$(function(){
var paramShiftId = getURLParameter('shift_id');
var paramIncidentId = getURLParameter('incident_id');
loadData(paramShiftId, paramIncidentId);
})();
function loadData(paramShiftId, paramIncidentId) {
// Run Data Handler Query
$.ajax({
url: "queries/dataHandler_getShiftInfo.ashx",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { shift_id: paramShiftId, incident_id: paramIncidentId},
responseType: "json",
success: OnViewComplete,
error: OnViewFail
});
}
function OnViewComplete(result) {
$.each(result.aaData, function (i, row) {
$(".incidentlist").append("<li>" + row.INC_NUMBER + " </li>");
});
}
function OnViewFail(err){console.error(err);}

Outlook Office Addin not showing HTML page in div

This is my div:
<body>
<div id="content"></div>
</body>
and this is my code behind in js:
function jsonParser(sender) {
$.ajax({
type: "GET",
url: "http://MYURL/customers/outlook?email=" + sender + "&jsonp=true",
dataType: "jsonp",
success: function (htmlPage) {
document.getElementById("content").innerHTML = htmlPage.htmlText;
}
});
}
And this is the code that calls it:
function detectActionsForMe() {
var item = Office.cast.item.toItemRead(Office.context.mailbox.item);
var sender = item.sender.emailAddress;
jsonParser(sender);
}
I can't actually get the downloaded html page to show up in the Outlook (2016) addin window. I already tried using an iframe but I was obtaining nothing, neither.
I am sure about the page I am getting, I find just weird that it won't show up in the outlook box.
I found out what was missing, thanks to http://www.sitepoint.com/jsonp-examples/
Basically, I just added the following, to the ajax call:
contentType: "application/json",
dataType: "jsonp",
and it all worked! :)

How to make jQuery JSON request and use response data to change html element values?

I'm not good at JQuery at all, in fact this is my first encounter due to Shopify. In other words I'm completely lost.
This is what I was able to do so far.
function FindPlayer()
{
var playerid = $('input[id=playerId]').val();
var clubname = $('input[id=teamname]').val();
$("#searchBar").attr('data-user-input', value);
$.ajax({
url: "http://website.com/index.php?player=" + playerid + "&club=" + clubname,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response(data);
}
});
}
The json response is going to look like this:
[{"playerFound":"true","tradeid":"123456"}]
I want to then check if playerFound is true or false before setting this element:
<input id="tradeId" type="hidden" name="attributes[tradeid]" />
This is probably pretty basic for JQuery users but not for me any help would be appericiated.
Try This:-
$.ajax({
url: "http://website.com/index.php?player=" + playerid + "&club=" + clubname,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if(data[0].playerFound == "true")
{
$('#tradeId').val(data[0].tradeid);
}
}
});
Since content type is JSON you can simply use like this
success: function (data) {
if(data.playerFound == "true"){
$('#tradeId').attr('name',data.tradeid) // if you want to change name
$('#tradeId').val(data.tradeid)// if you want to change value
}
}

AJAX jQuery Freezing IE/Safari

At my wits end here.
Im running this script
<script type="text/javascript" charset="utf-8">
jQuery(window).ready(function(){
//alert('running');
var sold = false;
var leads = [
["one", 120],
["two", 0]
];
jQuery.each(leads, function(index, value) {
var _data = "";
jQuery.ajax({
url: "/wp-content/plugins/cUrl/submit_lead.php?lead=" + value[0],
dataType: "json",
//contentType: "application/json; charset=utf-8",
timeout: value[1] * 1000, //Yes i need to wait 120 seconds for "one"
async: false,
cache: false
}).success(function(data) {
_data = data;
console.log(data.status + " Lead: "+ value[0]);
if (data.status == "sold") {
sold = true;
jQuery.ajax({
url: "/wp-content/plugins/cUrl/submit_lead.php?resetSession",
dataType: "json",
//contentType: "application/json; charset=utf-8",
async: false,
cache: false
}).success(function() {
//Silence is golden.
});
window.location.href = data.link;
}
}).error(function(jqXHR, textStatus){
console.log("ERROR: " + textStatus + " Lead: " + value[0]);
});
if (_data.status == "sold") {
return false;
}
});
if (!sold) {
//If we get here, None of the leads were sold.
jQuery.ajax({
url: "/wp-content/plugins/cUrl/submit_lead.php?resetSession",
//contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false
}).success(function(data) {
//Silence is golden.
});
window.location.href = '/thank-you.php';
}
});
</script>
The script takes some info submits it to submit_lead.php which will return a json response with a status, a message and a link. Once it has this link it needs to call the same script with ?resetSession and the redirect the user to the link received.
I have a sync turned off because I need to wait until I get a response from "one" before trying "two", because if I receive a link there's no point trying the next one.
When the script runs on FF or Chrome, it runs fine. There is a little animation that plays while the requests are going through and once a link is returned it redirects accordingly.
When the script runs in <= IE8 or Safari, the page sorta loads half then waits (The animation loads but does not animate.). Once the ajax response has returned the page suddenly springs to life and then you get redirected.
I have tried window ready and document ready and nothing seems to work.
Any suggestions would be appreciated.
Thanks for reading.
Like i said in the comments, turn async back on.
Add your redirect or whatever operations you want to perform in the callback from the ajax function. Thats most likely the reason you are getting locking.

Categories

Resources