The following code inside the tags gives error: "Object Expected".
<!-- JQuery/AJAX-->
<script type="text/javascript">
try {
$(document).ready(function(){
$("p").load(function(){
MakeRequest('divElectionCategory','ulElectionCategory','SELECT * FROM electioncategorymaster', 'UnOrderedList');
});
});
}
catch(e)
{
alert(e.message);
}
</script>
The MakeRequest function resides in a separate .js file and I have included that file before the above given code.
Which object it is referring to?
Edited:
The MakeRequest function
function MakeRequest(DivName, ControlName, SqlQuery, ControlType)
{
var xmlHttp = getXMLHttp();
var strUrl = "";
if (ControlType = 'DropDown')
strUrl = "../phplibraries/filldropdown.php?DivName=" + DivName + "&DropDownControlName=" + ControlName + "&SqlQuery=" + SqlQuery;
else
strUrl = "../phplibraries/createelectioncategorymenu.php?DivName=" + DivName + "&ulName=" + ControlName + "&SqlQuery=" + SqlQuery;
alert(strUrl);
try
{
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText, DivName);
}
}
xmlHttp.open("GET", strUrl, true);
xmlHttp.send(null);
}
catch(err)
{
alert(err);
}
}
I know there is a big security issue above but please ignore it at this point of time.
You cannot call load() that way.
The first parameter of load takes a URL not a function. Perhaps you meant this:
$("p").load( MakeRequest('divElectionCategory','ulElectionCategory','SELECT * FROM electioncategorymaster', 'UnOrderedList') );
That assumes that MakeRequest returns a formatted URL.
EDIT
.load() when used against a DOM element and the first parameter is a function, jQuery assumes you are attaching an event handler. However, p does not have a load event. If you want to wait for everything to load, try this (It doesn't have to be in DOM ready):
$(window).load( function(){
MakeRequest('divElectionCategory','ulElectionCategory','SELECT * FROM electioncategorymaster', 'UnOrderedList')
});
MakeRequest rewrite
function MakeRequest(DivName, ControlName, SqlQuery, ControlType)
{
var strUrl = "", params = {};
if (ControlType = 'DropDown'){
strUrl = "../phplibraries/filldropdown.php";
params = {
DivName: DivName,
DropDownControlName: ControlName,
SqlQuery: SqlQuery
}
} else {
strUrl = "../phplibraries/createelectioncategorymenu.php";
params = {
DivName: DivName,
ulName: ControlName,
SqlQuery: SqlQuery
}
}
alert(strUrl);
$.get(strUrl, params, function(data){
HandleResponse(data, DivName);
});
}
Related
I have a div called totalvalue.
<div id="totalvalue"></div>
I wrote a function to get value from my PHP script (on the same server).
function totalvalue() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
totalvalue = (ajax5.responseText);
console.log(totalvalue);
document.getElementById("totalvalue").innerHTML = ajax5.responseText;
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
The php script does output a value.
Neither my console nor the div display the output.
This worked for me.
function test5() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
xxx5 = (ajax5.responseText);
console.log("this is the total value: "+xxx5);
if (xxx5 == 0) {
document.getElementById("totalvalue").innerHTML="Loading...";
} else {
document.getElementById("totalvalue").innerHTML="Total: "+xxx5;
}
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
I presume that where I write the div matter + there could have been an issue with the cache. I cannot tell for sure why the above just started working.
For simpler code, and better cross browser support, i would use jQuery.ajax like so:
$.ajax({
url: 'totalvalue.php',
success: function(data){
$('#totalvalue').html(data);
}
});
Read more about it in the documentation
I'm using jquery-bitly-plugin for shorten some URLs and I'm doing in this way:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
shorten = bitly.shorten(url, {
onSuccess: function (shortUrl) {
console.info(shortUrl); // this works fine
// I got something like http://bit.ly/1DfLzsF
return shortUrl;
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
Then I tried this:
console.log(shorten);
But got Undefined, why? How do I assign the var in order to use in other places?
EDIT: adding extra information around the problem
This info will clarify a bit what I'm trying to do with my question so I have this code which allow to share some content in social networks on click event:
$('.share-item').click(function () {
var href = '',
url = base_url + 'main/show/' + imgUrl.split("/")[2].split(".")[0];
if ($(this).data('category') == 'share-facebook') {
href = 'https://www.facebook.com/sharer/sharer.php?u=' + url;
}
else if ($(this).data('category') == 'share-twitter') {
text = 'SomeText';
via = 'SomeText2';
href = 'http://www.twitter.com/share/?text=' + text + '&via=' + via + '&url=' + url;
}
else if ($(this).data('category') == 'share-mail') {
$('#finalImgModal').attr('src', imgUrl);
$('#image').val(imgUrl);
$('#mailModal').modal('show');
return false;
}
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
return false;
});
As you may notice url is common to share-facebook and share-twitter. I need to shorten that URL and pass back to the href on each possible choice. For shorten the URL I'm using jquery-bitly-plugin as follow:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
console.info(shortUrl); // this works fine I got
// something like http://bit.ly/1DfLzsF
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
How I can use shortUrl in href parameter? Do I need to repeat the code on each condition in order to use execute the action at onSuccess event from shorten() method? How do you deal with this?
To assign to a variable:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
shorten = shortUrl;
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
The method shorten doesn't have a return on source code of plugin.
IMPROVED ANSWER
Based on your edite post, this is the correct answer on how to use it the shortUrl:
$('.share-item').click(function () {
var href = '',
url = base_url + 'main/show/' + imgUrl.split("/")[2].split(".")[0],
opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
if ($(this).data('category') == 'share-facebook') {
href = 'https://www.facebook.com/sharer/sharer.php?u=' + shortUrl;
} else if ($(this).data('category') == 'share-twitter') {
text = 'SomeText';
via = 'SomeText2';
href = 'http://www.twitter.com/share/?text=' + text + '&via=' + via + '&url=' + shortUrl;
} else if ($(this).data('category') == 'share-mail') {
$('#finalImgModal').attr('src', imgUrl);
$('#image').val(imgUrl);
$('#mailModal').modal('show');
}
if ($(this).data('category') != 'share-mail')
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
return false;
});
As I said in a comment, you need to figure out a future for the shortened URL. This future here is "open a window with this URL". Here is a quick pseudocode:
function openWindow(shortUrl) {
window.open(shortUrl, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
}
$('.share-item').click(function () {
if ($(this).data('category') == 'share-mail') {
...
return;
}
if (....twitter...) {
href = ...
} else if (....facebook....) {
href = ...
}
bitly.shorten(url, {
onSuccess: openWindow,
onError: function(err) {
...
}
});
}
(I made the openWindow future into a separate function to make it obvious, but it could just as well have been left inline.)
So i have this code, with should connect to google api and get some info of the user. The problem however is that the link which starts the login function doesn't work.
This is a java RESTful project so its built via maven and deployed on a tomcat server if that helps.
<!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type='text/javascipt'>
$(document).ready(function(){
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = 'sercret';
var REDIRECT = 'myredirect';
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var url1 = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login(){
var win = window.open(url1, 'windowname1', 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
});
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: 'jsonp'
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: 'jsonp'
});
}
/*credits: http://www.netlobo.com/url_query_string_javascript.html*/
function gup(url, name) {
name = name.replace(/[\\\\[]/,'\\\[').replace(/[\]]/,'\\\]');
var regexS = '[\\#&]'+name+'=([^&#]*)';
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results === null )
return ;
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
});
</script>
</head>
<body>
<a href="#" onclick='login()' id='loginText'> Click here to login </a>
Click here to logout
<iframe name='myIFrame' id='myIFrame' style='display:none'></iframe>
<div id='uName'></div>
<img src='' id='imgHolder'/>
</body>
</html>
A Small Error, big waste of time :)
<script type='text/javascript'>
You have missed the 'r' in javascipt
This is looking for a function called login:
onclick='login()'
However, no such function exists in the current scope. It was defined only within the scope of the document.ready handler:
$(document).ready(function () {
function login() {
//...
}
});
So it's not visible outside of the handler. In order to make it visible, define it outside:
function login() {
//...
}
$(document).ready(function () {
//...
});
You generally don't need to define your functions in document.ready, it's mainly for waiting until the DOM is loaded before evaluating selectors. You can define functions within it, if those functions don't need to exist outside its scope.
Another alternative would be to bind it within the scope that it's defined, rather than in-line in the markup. Something like this:
$(document.ready(function () {
function login() {
//...
}
$('#loginText').click(login);
});
When I am calling requestwidgets function under document.ready it is successfully getting called and call to handler is made.
But when the same function i am calling from some function it is not getting called
Note: This is only happening in IE11 browser
Below is the code
function CreateNewWidget() {
$elementName = $("#ux_widget_name").val();
$elementType = $("#ux_widget_type_dll").val();
$url = '?request=newelement&elementtype=' + $elementType + '&appguid=' + appguid + '&elementname=' + $elementName;
$.get($url, function (data) {
if (data == "True") {
RequestWidgets();
}
setTimeout("$.fn.slickBox.close()", 3000);
});
}
var elements = Array();
function RequestWidgets() {
$.get('/shared/test2.ashx?request=getelements&appguid=' + appguid, function (data) {
xmlDoc = $.parseXML(data);
elements = Array();
RenderElements(elements);
});
}
I am working on a function to track anytime there is a js error on a page. I have 4/6 error types working but can't seem to figure out a function for syntax errors, or do they just stop script execution to the point it doesn't function? Also, I am not sure how to test for internal errors? Edit: InternalError is only in firefox, but need a test for EvalError, which I will post separately. Another Edit: it appears EvalError is legacy and not fully supported by modern browsers.
No libraries such as jQuery can be used, only native js.
Here is the code with the answer added:
errorTracking = function errorCaught( ev ) {
document.getElementById('error').innerHTML = '';
var errFile = '';
var errLine = '';
if(ev.filename) { errFile = ev.filename; }
if(ev.lineno) { errLine = ev.lineno; }
var errStr = 'ERROR: ' + ev.error + ', LOCATION: ' + errFile + ', LINE NUMBER:' + errLine;
document.getElementById('error').innerHTML = '<strong>Message:</strong> ' + ev.error + '<br /><strong>Location:</strong> ' + errFile + '<br /><strong>Line Number:</strong> ' + errLine;
// Omniture Error Tracking.
//_satellite.setVar('jsError', errStr);
ev.preventDefault();
};
if(window.addEventListener) {
window.addEventListener( "error", errorTracking, false );
document.getElementById('errRef').addEventListener('click', function() {
var refErr = asdf.asdf.length;
});
document.getElementById('errTyp').addEventListener('click', function() {
var typeErrVar = null;
var typeErr = typeErrVar();
});
document.getElementById('errRan').addEventListener('click', function() {
Array.apply(null, new Array(1000000)).map(Math.random);
});
document.getElementById('errURI').addEventListener('click', function() {
decodeURIComponent("%");
});
document.getElementById('errSyn').addEventListener('click', function() {
var script = document.createElement('script');
script.text = document.getElementById('error');
document.getElementsByTagName('head')[0].appendChild(script);
});
document.getElementById('errEva').addEventListener('click', function() {
});
}
http://jsfiddle.net/swv55c35/17/
<script/>'s will be parsed completely, when a script contains a syntax-error, the entire script will be discarded. Create the syntax-error outside of the script that handles the errors, and it will work.
http://jsfiddle.net/swv55c35/3/