I'm opening a new window to display a report using javascript and jquery in an MVC 4 application. The code is as follows.
window.open method:
$(document).ready(function () {
// validation stuff
submitHandler: function (form) {
var brewery = document.getElementById('BrewerySelect').value;
var line = document.getElementById('LineSelect').value;
var day = document.getElementById('datepicker').value;
var width = window.innerWidth * 0.66;
var height = width * window.innerHeight / window.innerWidth;
var urlStr = '/DashboardReport/Report?brewery=' + brewery + '&line=' + line.trim() + '&day=' + day;
alert(urlStr);
window.open(urlStr, 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
}
});
});
The controller does nothing, which I have tried as both PartialViewResult and ActionResult, the rest of the methods in the controller work fine for the ajax calls. The report works in a modal.:
public ActionResult Report()
{
return View();
}
The page that is opened:
#{
Layout = null;
}
<html>
<head>
<title>Report</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="reportBody" style="height: 100%;">
</div>
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/scripts.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var brewery = GetURLParameter('brewery');
var line = GetURLParameter('line');
var day = GetURLParameter('day');
alert('document hit');
SetReport(brewery, line, day);
});
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
function SetReport(brewery, line, day) {
var url = '#Url.Action("GetUrl")';
alert('SetReport Hit ( action url = ' + url + ')');
$.ajax({
url: url,
data: { breweryCode: brewery, packageLine: line, date: day },
dataType: 'json',
cache: false,
type: "POST",
success: function (data) {
alert('SetReport success. data = ' + data);
var url = '<iframe src="' + data + '" height="100%" width="100%" scrolling="auto"></iframe>';
$('#reportBody').html(url).show();
},
error: function (response) {
alert('document.ready() dashboardReportForm SetForm() method failed');
}
});
}
</script>
</body>
</html>
I've set alerts throughout the javascript to let me know what is getting hit, but none of the alerts are firing. The document.ready function is not being hit.
There's a U+200b character after the ending bracket of GetURLParameter function, which causes syntax error. Remove it and it should work.
See No visible cause for "Unexpected token ILLEGAL"
Related
We are using window.onbeforeunload mostly if user does a search for a text within the page in the search box, that is not retained any more. So we want to leverage fetch or sendBeacon for the same for all browsers except IE instead of window.onbeforeunload.
Code Snippet to search text in serach box:
<script type="text/javascript" charset="utf-8">
var unloadCatcher = function() {
var dateObjAjax = new Date();
var timestamp = dateObjAjax.getTime();
var sortColumnIndex = $('#example').dataTable().fnSettings().aaSorting[0][0];
var pageType = "EPPatientList";
var paginationSize = $("#example_length select option:selected").prop('value');
var sortDirection = $('#example').dataTable().fnSettings().aaSorting[0][1];
var searchText = "";
if ($('#search_input').is(':visible')) {
searchText = $('#search_input').val();
$("#hiddenSearchText").val(searchText);
}
else {
$("#hiddenSearchText").val("");
}
$.ajax({
url: "<%=userPreference%>&sortColumnIndex=" + sortColumnIndex
+ "&pageType=" + pageType
+ "&paginationSize=" + paginationSize
+ "&sortDirection=" + sortDirection
+ "&time="+timestamp,
type: "post",
data: $("#hiddenSearchForm").serialize(),
cache: false,
async: false,
success: function(data){
}
});
var otable = $('#example').DataTable();
var pageSize = otable.page.info().length;
var expdate = new Date();
expdate.setTime(expdate.getTime() + (60 * 60 * 1000 * 24 * 365 * 20));
$.cookie('SJM_PT_'+userLogonCookieName+'_PageSize',pageSize,{ expires: expdate });
}
window.onbeforeunload = unloadCatcher;
</script>
so I've built a little game (with p5.js library) and wanted to implement a Leaderboard loaded from a JSON file, used as a kind of DB to store Username/score, all of this using a Node.js server, with express installed to make things easier. So here is the html (with ajax code) :
<html>
<head>
<title>KassBric - Mouetto</title>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.sound.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="sketch.js"></script>
<script language="javascript" type="text/javascript" src="Paddle.js"></script>
<script language="javascript" type="text/javascript" src="Ball.js"></script>
<script language="javascript" type="text/javascript" src="Brick.js"></script>
<script language="javascript" type="text/javascript" src="Grid.js"></script>
<script language="javascript" type="text/javascript" src="Attractor.js"></script>
<script language="javascript" type="text/javascript" src="methods.js"></script>
<script language="javascript" type="text/javascript" src="Bonus.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
$.ajax({
url: '/scores.json',
dataType: 'json',
success: function(data) {
var keys = Object.keys(data);
for(var i = 0; i < keys.length; i++) {
var username = keys[i];
var score = data[username];
var row = $('<tr><td>' + username + '</td><td>' + score + '</td></tr>');
$('#Leaderboard').append(row);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
</script>
</head>
<body>
<div>
<p id="LeaderboardHolder" style = "background-color : rgb(51, 51, 51); color: rgb(150, 150, 150); padding: 15px;">
<table id="Leaderboard">
<tr>
<th>Username</th>
<th>Best Score</th>
</tr>
</table>
</p>
</div>
</body>
</html>
this is my server.js :
console.log("server is starting");
var express = require('express');
var fs = require('fs');
var app = express();
var server = app.listen(3000, listen);
function listen() {
console.log("Listening...");
};
app.use(express.static('public'));
var data = fs.readFileSync('scores.json');
var scores = JSON.parse(data);
console.log(scores);
app.get('/leaderboard', showLeaderboard);
function showLeaderboard(request, response){
response.send(scores);
};
app.get('/leaderboard/add/:username/:score?', addPlayer);
function addPlayer(request, response){
var data = request.params;
var username = data.username;
var score = Number(data.score);
var type = typeof score;
if(!score || type !== 'number'){
var reply = "Score is required, and must be a number.";
}else{
scores[username] = score;
var data = JSON.stringify(scores, null, 2);
fs.writeFile('scores.json', data, finished);
function finished(err){
console.log("Updated the database.");
var reply = {
request: "Submitted",
username: username,
score: score
};
};
};
response.send(reply);
};
app.get('/leaderboard/:username', showPlayer);
function showPlayer(request, response){
var word = request.params.username;
if(scores[word]){
var reply = {
username: word,
score: scores[word]
};
}else{
var reply = {
msg: "Username not found"
};
};
response.send(reply);
};
and my directory looks like :
-Project:
-node_modules
-public:
-index.html (code above)
-all my game files & folders
-packages.json
-scores.json
-server.js
and so, with this running with Node/Express, I get an error:
"GET http://localhost:3000/scores.json 404 (Not Found)"
and by doing more tests, I tried to run a "basic" python SimpleHTTPServer in my project directory (in the public folder) and I get no errors, ajax gets the data and parses it into the html table. I can't find why this does work with python's server and not my node one ...
Your Ajax url /scores.json but you don't have the route to /scores.json in server.js
In this case my solution is:
$.ajax({
url: '/handler',
dataType: 'json',
success: function(data) {
var keys = Object.keys(data);
for(var i = 0; i < keys.length; i++) {
var username = keys[i];
var score = data[username];
var row = $('<tr><td>' + username + '</td><td>' + score + '</td></tr>');
$('#Leaderboard').append(row);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
and in server.js:
app.get('/handler', function(req, res) {
var filePath = path.join(__dirname, '/scores.json');
var file = fs.readFileSync(filePath, 'utf8');
var result = JSON.parse(file);
res.send(result);
}
Sorry for my English.
This question already has answers here:
jQuery Deferred - waiting for multiple AJAX requests to finish [duplicate]
(3 answers)
Closed 6 years ago.
I'm trying to execute a callback after multiple jQuery Ajax have completed.
In my code both Ajax requests call another function and when I try to use these functions I get undefined.
I think the problem has to do with using deferred/promise, but I don't know how to use them.
Here is my code:
<link rel="stylesheet" type="text/css" href="https://tag/sites/ocean1/maker/captions/shared%20documents/Web_ComplianceCSS.txt">
<div id = "cabbage" style="font-size:10px">
<p>Web Compliance Stats</p>
</div>
<script type = "text/javascript">
var WebComplianceReportApp = {} || WebComplianceReportApp;
WebComplianceReportApp.GetStatuses = (function() {
var pub = {},
_userId,
_ultimateObjectHolderArr = [],
_items = [],
_options = {
listName: "M_Web_Compliance",
container: "#cabbage",
};
pub.init = function() {
var clientContext = new SP.ClientContext.get_current();
_userId = clientContext.get_web().get_currentUser();
clientContext.load(_userId);
clientContext.executeQueryAsync(getUserInfo, _onQueryFailed);
};
function getUserInfo() {
_userId = _userId.get_id();
getSpecifiedList(_options.listName, _userId);
}
function buildObject(results, listName) {
_items = results.d.results;
$.each(_items, function(index, item) {
_ultimateObjectHolderArr.push({
"Division": item.ParentOrg,
"ORG": item.ORG,
"URL": item.URL,
"Status": item.Site_Status
});
});
//createStatusView2(_ultimateObjectHolderArr);
}
function getSpecifiedList(listName, userId) {
var counter = 0;
var baseUrl = SP.PageContextInfo.get_webServerRelativeUrl() + "/_vti_bin/listdata.svc/" + listName;
var url1 = baseUrl + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages";
var call1 = $.ajax({
url: url1,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
}).done(function(results) {
buildObject(results, listName);
}).fail(function(error) {
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " + SP.PageContextInfo.get_webServerRelativeUrl());
});
var url2 = baseUrl + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages&$skiptoken=1000";
var call2 = $.ajax({
url: url2,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
}).done(function(results) {
buildObject(results, listName);
}).fail(function(error) {
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " + SP.PageContextInfo.get_webServerRelativeUrl());
});
}
function createStatusView2(Arr) {
var divisionArr = [];
var oRGArr = [];
var divisionCount = 0;
var oRGCount = 0;
for (var i = 0; i < Arr.length; i++) {
if ($.inArray(Arr[i].Division, divisionArr) === -1) {
divisionArr.push(Arr[i].Division);
var divisionHolderElement = $("<div id='p_" + Arr[i].Division + "' class='division_row_holder'></div>");
var divisionElement = $("<div id='" + Arr[i].Division + "' class='division_div ORG'></div>").text(Arr[i].Division);
$("#cabbage").append(divisionHolderElement);
$(divisionHolderElement).append(divisionElement);
}
if ($.inArray(Arr[i].ORG, oRGArr) === -1) {
oRGArr.push(Arr[i].ORG);
var orgElement = $("<div class='org_div ORG' id='" + Arr[i].ORG + "' style='font-size:10px;'></div>").text(Arr[i].ORG);
$("#p_" + Arr[i].Division).append(orgElement);
}
}
}
//automatically fired by init
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return pub
}());
$(document).ready(function() {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
//After the SP scripts are run, we access the WebComplianceReportApp.GetStatuses
WebComplianceReportApp.GetStatuses.init();
});
});
</script>
I dont know if this will make your code dirty, but I would use a flag in this case
ex:
var ajaxCalls = 0;
function checkAjaxCalls()
{
if (ajaxCalls == 2)
{
//do your thing...
//and maybe you want to reset ajaxCalls value to zero if needed...
}
}
And from each Ajax response completes, increment ajaxCalls variable by one, and call the checkAjaxCalls function from both your Ajax responses.
Method One:
This time we'll have waited for the request to complete instead of waiting for the request to succeed
$(".ajax-form-button-thingy").on("click", function() {
$.ajax({
url: $(this).attr("href"),
type: 'GET',
error: function() {
throw new Error("Oh no, something went wrong :(");
},
complete: function(response) {
$(".ajax-form-response-place").html(response);
}
});
});
Method Two:
If you want to wait for ALL Ajax requests to complete without changing the async option to false then you might be looking for jQuery.ajaxComplete();
In jQuery every time an Ajax request completes the jQuery.ajaxComplete(); event is triggered.
Here is a simple example but there is more info on jQuery.ajaxComplete(); over here.
$(document).ajaxComplete(function(event, request, settings) {
$(".message").html("<div class='alert alert-info'>Request Complete.</div>");
});
Also you can take a look at the Ajax response by using request.responseText this might be useful in case you want to double check the response.
For more information about jQuery.ajax you can read the docs here
You could call createStatusView(); and then call createStatusView2(); after all of your Ajax requests are done
$(document).ready(function(){
createStatusView();
$(this).ajaxStop(function() {
// NOTE: I did not see you use createStatusView(); in your code
createStatusView2();
});
});
I am trying to implement disqus commments in my ionic app. I know I have to host it on the domain its setup for which I believe I have configured correctly. Any assistance will be welcomed
Here is the code in my app.js for the ionic app
$scope.showComments = function () {
$scope.currentView = "comments";
//loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
//
var disqus_title = "Venue 1";
var disqus_identifier = '/venue/' + $stateParams.id;
var disqus_url = 'liverpool.li/venue/' + $stateParams.id;
var url = "http://liverpool.li/app/disqus.html?";
$scope.url = url + "shortname=liverpoolli&url=" + encodeURIComponent(disqus_url) +
"&title=" + encodeURIComponent(disqus_title) + "&identifier=" + encodeURIComponent(disqus_identifier);
$scope.url = $sce.trustAsResourceUrl($scope.url);
};
$scope.$on("$destroy", function () {
if ($scope.lastScriptElm && $scope.lastScriptElm.parentNode) {
$scope.lastScriptElm.parentNode.removeChild($scope.lastScriptElm);
$scope.lastScriptElm = null;
}
});
And the page it points to (disqus.html) located on my domain
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body>
<div id="disqus_thread"></div>
<script type="text/javascript">
var params;
var disqus_url;
var disqus_title;
var disqus_shortname;
var disqus_identifier;
window.onload = function () {
var match,
pattern = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pattern, " ")); },
query = window.location.search.substring(1);
params = {};
while (match = search.exec(query))
params[decode(match[1])] = decode(match[2]);
if (params["shortname"] === undefined || params["url"] === undefined || params["title"] === undefined) {
alert("Required arguments missing");
}
else {
loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
}
};
function loadComments(shortname, url, title, identifier) {
disqus_url = url;
disqus_title = title;
disqus_shortname = shortname;
if (identifier !== undefined)
disqus_identifier = identifier;
else
disqus_identifier = "";
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = false;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}
</script>
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
blog comments powered by <span class="logo-disqus">Disqus</span>
</body>
</html>
I get the following error
we were unable to load disqus. if you are a moderator please see our
troubleshooting guide.
It looks like you're almost there. The only issue I see is the disqus_url variable must also include the protocol to be valid. Try using this line instead:
var disqus_url = 'http://liverpool.li/venue/' + $stateParams.id;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need a hand with the below script, i am new at JSON and need to store some data to MYSQL database.
How can i do this? Or if you can assist with the script and a detailed explanation on how to store the user login with Facebook Javascript SDK to MYSQL database. To store they Name and ID
<?php
$sApplicationId = 'YOUR_APPLICATION_ID';
$sApplicationSecret = 'YOUR_APPLICATION_SECRET';
$iLimit = 99;
?>
<!DOCTYPE html>
<html lang="en" xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<meta charset="utf-8" />
<title>Facebook API - Get friends list</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<img src="facebook.png" class="facebook" alt="facebook" />
<center>
<h1>Authorization step:</h1>
<div id="user-info"></div>
<button id="fb-auth">Please login here</button>
</center>
<div id="result_friends"></div>
<div id="fb-root"></div>
<script>
function sortMethod(a, b) {
var x = a.name.toLowerCase();
var y = b.name.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
window.fbAsyncInit = function() {
FB.init({ appId: '<?= $sApplicationId ?>',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) { // in case if we are logged in
var userInfo = document.getElementById('user-info');
FB.api('/me', function(response) {
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + response.id + '/picture">' + response.name;
button.innerHTML = 'Logout';
});
// get friends
FB.api('/me/friends?limit=<?= $iLimit ?>', function(response) {
var result_holder = document.getElementById('result_friends');
var friend_data = response.data.sort(sortMethod);
var results = '';
for (var i = 0; i < friend_data.length; i++) {
results += '<div><img src="https://graph.facebook.com/' + friend_data[i].id + '/picture">' + friend_data[i].name + '</div>';
}
// and display them at our holder element
result_holder.innerHTML = '<h2>Result list of your friends:</h2>' + results;
});
button.onclick = function() {
FB.logout(function(response) {
window.location.reload();
});
};
} else { // otherwise - dispay login button
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
window.location.reload();
}
}, {scope:'email'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
Store your data in an array then use json_encode().
Have a look here.
In your for loop :
for (var i = 0; i < friend_data.length; i++) {
results += '<div><img src="https://graph.facebook.com/' + friend_data[i].id + '/picture">' + friend_data[i].name + '</div>';
$.ajax({
type: "POST",
url: "some.php",
data: { id : friend_data[i].id, name: friend_data[i].name }
});
}
in some.php :
$tmpArray = array('id' => $_POST['id'], 'name' => $_POST['name']);
$output = json_encode($tmpArray); // <-- save this in your db, if you want to store a JSON string, but it doesn't seem to be optimized. You'd better to save ID and name.