I have a facebook app that works in all other browsers but IE. Here is my javascript code:
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
window.fbAsyncInit = function() {
FB.init({
appId : '123456789', // App ID
channelUrl : 'http://test/channel.php', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true // turn on oauth
});
// Additional initialization code here
};
function start() {
//send initial AJAX request
var bike_var = $("select#bike").val();
var reason_var = $("textarea#reason").val();
var dataString = 'bike='+ bike_var + '&reason=' + reason_var;
$.ajax({
type: "POST",
url: "save.php",
data: dataString,
success: function(data) {
//set ID in the form
$("input#recordID").val(data);
doLogin();
}
});
}
function doLogin() {
//Do request to Facebook to get user details and then post to wall and the submit the form
FB.login(function(response) {
if (response.authResponse) {
getUserInfo();
} else {
alert("Sorry! We can't enter you into the competition unless you allow our Facebook app!");
}
}, {scope: 'email, publish_stream'});
}
function getUserInfo() {
FB.api('/me', function(info) {
$("input#name").val(info.name);
$("input#email").val(info.email);
$("input#FID").val(info.id);
var params = {};
params['message'] = $("textarea#reason").val();
params['name'] = 'Test';
params['description'] = '';
params['link'] = 'http://www.facebook.com/ChainReactionCycles';
params['picture'] = 'http://crc.test/img/logo.gif';
params['caption'] = 'Test';
postToWall(params);
});
}
function postToWall(param) {
FB.api('/me/feed', 'post', param, function(wall) {
if (!wall || wall.error) {
} else {
document.forms["comp-entry"].submit();
}
});
}
Here is code for my submit button that kicks off the code, currently working in all other browsers:
<input type="submit" name="submit_button" value="Enter Competition" onclick="start(); return false;">
In IE, this just goes to a blank page with the record ID of the new record, but in my database none of the required facebook fields are filled. The error in IE when i debug is 'SCRIPT5002: Function expected'. If anyone has any ideas i would be eternally grateful
I had the same error message on my script and googled for that error code, so I accidently stumbled across your question. your line of code, that kicks the error helped me, so I can help you now.
Obviously IE 9 does not like "start" as a function name. I had the same function in my code, and after I found that redundancy between my own code and yours, I replaced the function name, et voila, everything works fine now.
Related
EDIT
the code below seems to works as long as the form is valid.
but when it is not the case (clean method in django form) h1 text of form is removed (????) and the error messages are not displayed...
I guess that an empty popup.html is return via ajax and as there is no button to interact with nothing happen but why h1 text is removed...???
var prevent_edit = false;
var prevent = false;
// popup d'informations indiquant que la levée d'insue a déjà été faite
// pour ce patient
$("#form_unblind_edit").submit(function (event) {
console.log('form_unblind_edit click - first')
console.log('prevent_edit - first', prevent_edit)
if (!prevent_edit) {
event.preventDefault();
}
});
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
// affichage des informations sur le patient sélectionné pour la ré-allocation
$("#unblind_edit").on("click", function (event) {
console.log('click unblind edit');
var csrftoken = getCookie('csrftoken');
var patient = $("#id_pat").val();
$.ajax({
type: "POST",
url: '/unblind/already_unblind/',
data: {
csrfmiddlewaretoken: csrftoken,
'patient': patient,
},
dataType: 'html',
success: function (data) {
console.log('success');
// var prevent_edit = false;
$("#can_unblind").html(data);
$('#unblindconfirm').modal('show');
$('body').on('click', '#edit_button_OK', function (event) {
console.log('edit_button_OK')
$('#edit_button_OK').attr("disabled", "disabled");
prevent_edit = true;
console.log('prevent_edit', prevent_edit);
$("#form_unblind_edit").submit();
})
},
error: function (resultat, statut, erreur) {
console.log('error');
}
});
});
i need some help for popup with ajax
User complete the form and submit the form by clicking a button
I prevent submit with event.preventDefault(); to display a popup.
But I need to ask database for informations to display on popup, so I use an ajax query
when ajax success, popup is displayed with informations from database and I want the form t be submited by clicking on "OK" button of the popup
but it failed, I think, because event (submit) is attached to a button that is not present in DOM when page load...
JS
$(document).ready(function () {
var prevent_edit = false;
// prevent submission
$("#form_unblind_edit").submit(function (event) {
if (!prevent_edit) {
event.preventDefault();
}
});
// ajax query that display popup
$("#unblind_edit").on("click", function (event) {
var csrftoken = getCookie('csrftoken');
var patient = $("#id_pat").val();
$.ajax({
type: "POST",
url: '/unblind/already_unblind/',
data: {
csrfmiddlewaretoken: csrftoken,
'patient': patient,
},
dataType: 'html',
success: function (data) {
$("#can_unblind").html(data); //popup html attach to DOM
$('#unblindconfirm').modal('show'); //popup displayed
$('body').on('click', '#edit_button_OK', function (event) {
console.log('edit_button_OK'); // WORKING
prevent_edit = true;
$("#form_unblind_edit").trigger('submit'); //form submission = NOT WORKING
})
}
});
});
Maybe change the type of the submit button in the form to "button"
<button type="button">Submit</button>
This way the submit action is not executed when the user clicks submit and instead you display the popup. Then you should be able to submit the form using JQuery.
$("#form_unblind_edit").trigger('submit');
I am trying to set the message to "Data Loading.." whenever the data is loading in the grid. It is working fine if I don't make an Ajax call. But, when I try to make Ajax Request, It is not showing up the message "Loading data..", when it is taking time to load the data. Can someone please try to help me with this.. Thanks in Advance.
_loadData: function(x){
var that = this;
if(this.project!=undefined) {
this.setLoading("Loading data..");
this.projectObjectID = this.project.value.split("/project/");
var that = this;
this._ajaxCall().then( function(content) {
console.log("assigned then:",content,this.pendingProjects, content.data);
that._createGrid(content);
})
}
},
_ajaxCall: function(){
var deferred = Ext.create('Deft.Deferred');
console.log("the project object ID is:",this.projectObjectID[1]);
var that = this;
console.log("User Reference:",that.userref,this.curLen);
var userObjID = that.userref.split("/user/");
Ext.Ajax.request({
url: 'https://rally1.rallydev.com/slm/webservice/v2.0/project/'+this.projectObjectID[1]+'/projectusers?fetch=true&start=1&pagesize=2000',
method: 'GET',
async: false,
headers:
{
'Content-Type': 'application/json'
},
success: function (response) {
console.log("entered the response:",response);
var jsonData = Ext.decode(response.responseText);
console.log("jsonData:",jsonData);
var blankdata = '';
var resultMessage = jsonData.QueryResult.Results;
console.log("entered the response:",resultMessage.length);
this.CurrentLength = resultMessage.length;
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:resultMessage
});
this.pendingProjects = resultMessage.length
console.log("this testcase store:",resultMessage);
_.each(resultMessage, function (data) {
var objID = data.ObjectID;
var column1 = data.Permission;
console.log("this result message:",column1);
if(userObjID[1]==objID) {
console.log("obj id 1 is:",objID);
console.log("User Reference 2:",userObjID[1]);
if (data.Permission != 'Editor') {
deferred.resolve(this.testCaseStore);
}else{
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:blankdata
});
deferred.resolve(this.testCaseStore);
}
}
},this)
},
failure: function (response) {
deferred.reject(response.status);
Ext.Msg.alert('Status', 'Request Failed.');
}
});
return deferred;
},
The main issue comes from your Ajax request which is using
async:false
This is blocking the javascript (unique) thread.
Consider removing it if possible. Note that there is no guarantee XMLHttpRequest synchronous requests will be supported in the future.
You'll also have to add in your success and failure callbacks:
that.setLoading(false);
I am getting HTTP error 405 verb not allowed. As sometimes code works and sometimes throws http 405 error, I need to understand whether this is programming problem or server configuration problem. I am using ajax with jquery. I have gone through all related posts here and tried all recommended options related with the code. Please help.
my javascript code is as follows
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#name_error").show();
$("input#email").focus();
return false;
}
var textquery = $("textarea#textquery").val();
if (textquery == "") {
$("label#name_error").show();
$("textarea#textquery").focus();
return false;
}
var dataString = name + email + textquery;
// alert (dataString);return false;
$.ajax({
type: "POST",
url: "samplemail.aspx",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form <br> Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
Problem solved
the way Of passing parameter was wrong i.e.data : datastring .
The correct way is data : { name : name, email: email, textquery: textquery}
I cannot seem to find out why IE does not read my success on get after the post. I have tried cache: false, with no luck. This works in all other browsers, just not IE.
$.ajaxSetup({ cache: false });
num = $('#num').val();
phone = $('#phone').val();
$.post("post.php?"+$("#MYFORM").serialize(), {
}, function(response){
if(response==1 && codeVal == 1 && telVal == 1)
{
$("#after_submit").html('');
$("#Send").after('<label class="success" id="after_submit">Η αποστολή πραγματοποιήθηκε</label>');
change_captcha();
clear_form();
$.ajax({
type:'get',
cache: false,
url: "http://web.somesite/submit_code.php",
dataType: 'html',
data:{ user: "one", pass: "mtwo", source: "WEB", receipt: num, msisdn: phone},
success: function(data) {
var qsFull = "http://web.somesite.gr/submit_code.php?" + data;
var qs = URI(qsFull).query(true);
TINY.box.show({html:qs.message,animate:false,boxid:'error',top:5});
}
});
}
else
{
$("#after_submit").html('');
$("#Send").after('<label class="error" id="after_submit">Error! in CAPTCHA .</label>');
}
});
OK, I tried adding an error after the success and I see that I get my pop up as I should be, but the value of qs.message is 0. Why would I get error and not success, when it is successful in other browsers.
I found the answer, It has to do with IE not being flexible with cross domains and such, so I added a XDomainRequest like so
if (jQuery.browser.msie && window.XDomainRequest) {
var xdr = new XDomainRequest();
var my_request_data = { user: "M1web", pass: "m!", source: "WEB", receipt: num, msisdn: phone};
my_request_data = $.param(my_request_data);
if (xdr) {
xdr.onerror = function () {
alert('xdr onerror');
};
xdr.ontimeout = function () {
alert('xdr ontimeout');
};
xdr.onprogress = function () {
alert("XDR onprogress");
alert("Got: " + xdr.responseText);
};
xdr.onload = function() {
//alert('onload ' + xdr.responseText);
var qsFull = "http://web.web.gr/submit_code.php?" + xdr.responseText;
var qs = URI(qsFull).query(true);
TINY.box.show({html:qs.message,animate:false,boxid:'error',top:5});
callback(xdr.responseText);
};
xdr.timeout = 5000;
xdr.open("get", "http://web.web.gr/submit_code.php?" + my_request_data);
xdr.send();
} else {
}
}
I unfortunately had to do a crash course in legacy IE behavior, and this post was very helpful. Here are some other links to help those having to deal with these issues:
Microsoft's Documentation of their XDomainRequest object
An internal blog post covering some of XDomainRequest's idiosyncrasies
Here's a function I use as a fallback where necessary:
// This is necessary due to IE<10 having no support for CORS.
function fallbackXDR(callObj) {
if (window.XDomainRequest) {
var xdrObj = new XDomainRequest();
xdrObj.timeout = callObj.timeout;
xdrObj.onload = function() {
handleSuccess(xdrObj.responseText);
};
xdrObj.onerror = function() {
handleError(xdrObj);
};
xdrObj.ontimeout = function() {
callObj.xdrAttempts = callObj.xdrAttempts++ || 1;
if (callObj.xdrAttempts < callObj.maxAttempts) {
fallbackXDR(callObj);
}
};
xdrObj.onprogress = function() {
// Unfortunately this has to be included or it will not work in some cases.
};
// Use something other than $.param() to format the url if not using jQuery.
var callStr = callObj ? '?'+$.param(callObj.urlVars) : '';
xdrObj.open("get", callObj.url+callStr);
xdrObj.send();
} else {
handleError("No XDomainRequest available.", callObj);
}
}//fallbackXDR()
I want to display a message to the user saying, "you're logged out re-login please!" when session is timed-out, sending an ajax request each time. If session timer ends i want to send final ajax request displaying above message. But the problem here is i don't know where should i have to keep my ajax and jquery codes and since i don't have much knowledge about ajax request, can anyone explain this process with codes. In siple my requirement is like of what facebook shows on session time out, or when any one tab in case of multiople tabs are logged out. I'm working on grails project.
Do your ajax request like this
$.ajax({
url:url,
type:"POST", // or get
data:parameters,
success: function(data) {
// do procedure if success
}
error : function(xhr, type, error){
// do procedure if fail
// may be send a message to the server side to display a message that shows session timeout
}
});
Handle your session timeout in the error function
I did it myself and this is the js code for it "gracefulSession.js" and call this javascript at the page where you are going to embed your html code..
function checkSessionStatus() {
var lStorage = getLocalStorage();
if (lStorage) {
//lStorage.setItem('poleTime',new Date());
var poleTime = lStorage.getItem("poleTime");
var parsedTime;
try {
parsedTime = new Date(poleTime);
} catch (e) {}
//alert(new Date()-parsedTime)
//alert(new Date())
//alert(parsedTime)
//3900000 = 1H5M
if (parsedTime && (new Date() - parsedTime) < 3900000) {
//alert('NCATCH'+parsedTime);
} else {
//alert('POINT');
poleSessionStatus();
}
}
}
function setlatestPoleTIme() {
//alert("SETTING POLE TIME");
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.setItem('poleTime', new Date());
}
}
function setCheckSessionTimer() {
var lStorage = getLocalStorage();
var isLoggedOut = false;
if (lStorage) {
if (lStorage.getItem('isLoggedOut') == 'true') {
isLoggedOut = true;
}
}
//console.log('checkingIfLoggedOut');
if (!isLoggedOut) {
setTimeout("setCheckSessionTimer();", 5000);
//console.log("NOPT LO");
$('#LoggedoutMessage').hide();
checkSessionStatus();
} else {
setTimeout("setCheckSessionTimer();", 5000);
//console.log("KO");
//alert("You're Logged Out from other tab");
$('#LoggedoutMessage').show();
}
}
function logout() {
//alert("LOGGIN OUT")
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.setItem('isLoggedOut', 'true');
}
}
function resetLoggedOutFLag() {
var lStorage = getLocalStorage();
if (lStorage) {
lStorage.removeItem('isLoggedOut');
}
}
function getLocalStorage() {
var storage, fail, uid;
try {
uid = new Date;
(storage = window.localStorage).setItem(uid, uid);
fail = storage.getItem(uid) != uid;
storage.removeItem(uid);
fail && (storage = false);
} catch (e) {}
return storage
}
Now, HTML code to embed ,
<div id="LoggedoutMessage" style="display:none;position:absolute;background:black;height: 200%;width:100%;top: 0;z-index: 10000;opacity: 0.9;">
<div id="login_box" style="position:fixed;left:38%;top:30%; padding:10px; width: 365px;margin: 0 auto;border: 0px solid #CCC;margin-top: 35px;height: 150px;background: white; border-radius:3px;">
<div id="login_title">
<h1>You have been logged out.</h1>
</div>
<div id="reLogin">
<p>Please login to continue.</p>
<g:link controller="dashBoard" action="index" target="_blank" onclick="logout();">Login</g:link>
</div>
</div>
</div>
Finally where you keep your html,keep this javascript code at top of it embedding script tag:
function poleSessionStatus() {
jQuery.ajax({
type: 'POST',
data: '',
url: '<g:createLink action="ajaxCheckSession" controller="dashBoard"/>',
success: function (data, textStatus) {
//setTimeout ( "checkSession();", 5000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#LoggedoutMessage').show();
},
complete: function (XMLHttpRequest, textStatus) {
$.unblockUI();
}
});
}