JQuery ajax form submit works when debugging but not without - forms

I've got a form that is loaded on to a page using ajax. The form is then submitted using the malsup jquery form plugin.
Strangely the form works when I add a firebug breakpoint line or an alert into this method, but when I remove the alert or debug, the submit code never runs.
function addAttachment(attachmentType, path){
var typeSplit = attachmentType.split(":");
if(path == null){
path = "";
}
var url = "/add/" + typeSplit[0] + "/" + typeSplit[1];
addOverlayDivs(); //adds div to load the form into
// load the form
var snippet = $('#overlay').load(url, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#overlay").html(msg + xhr.status + " " + xhr.statusText);
}
});
var prefix = typeSplit[0];
var type = typeSplit[1];
//this alert will cause the submit form to work
alert("bind overlay called");//if I comment this out the formsubmit doesn't work
var options = {
target: null, // target element(s) to be updated with server response
beforeSubmit: showRequest,
success: showResponse,
url: "/add/" + prefix + "/" + type,
type: "POST",
dataType: "json"
};
$('#overlayForm').submit(function() {
$(this).ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});}
I've tried with and without using $(document).ready and that doesn't make a difference.
Any ideas?

May be you need to call later part of your function after load completed,Try this
$(document).ready(function(){
function addAttachment(attachmentType, path){
var typeSplit = attachmentType.split(":");
if(path == null){
path = "";
}
var url = "/add/" + typeSplit[0] + "/" + typeSplit[1];
addOverlayDivs(); //adds div to load the form into
// load the form
var snippet = $('#overlay').load(url, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#overlay").html(msg + xhr.status + " " + xhr.statusText);
}
Dowork();//function call after load complete
});
}
function Dowork(){
var prefix = typeSplit[0];
var type = typeSplit[1];
//this alert will cause the submit form to work
var options = {
target: null, // target element(s) to be updated with server response
beforeSubmit: showRequest,
success: showResponse,
url: "/add/" + prefix + "/" + type,
type: "POST",
dataType: "json"
};
$('#overlayForm').submit(function() {
$(this).ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});
}
});

Related

Intercepting AJAX in Flutter webview works on iOS but not Android

I am trying to intercept the ajax requests in webview using XMLHttpRequest. In iOS it is always working fine with flutter webview plugin but the same script injection code is not working on Android. Strange thing is it is not throwing any particular error even.
Some help on this will be really appreciable as this seems to be an elementary functional issue for webview.
Minimal example:
I am using the following Javascript code for intercepting Ajax request:
var open = window.XMLHttpRequest.prototype.open,
send = window.XMLHttpRequest.prototype.send,
onReadyStateChange;
function openReplacement(method, url, async, user, password) {
console.log('new data22');
var syncMode = async !== false ? 'async' : 'sync';
if (url === '/api/fakeCall') {
console.log('Preparing ' + syncMode + ' HTTP request : ' + method + ' ' + url);
}
return open.apply(this, arguments);
}
function sendReplacement(data) {
console.log('Sending HTTP request data : ', data);
if(this.onreadystatechange) {
this._onreadystatechange = this.onreadystatechange;
}
this.onreadystatechange = onReadyStateChangeReplacement;
return send.apply(this, arguments);
}
function onReadyStateChangeReplacement() {
console.log('HTTP request ready state changed : ' + this.readyState + ' ' + this.readyState + ' ' + XMLHttpRequest.DONE);
if (this.readyState === XMLHttpRequest.DONE) {
if (this.responseText !== "" && this.responseText !== null) {
if (this.responseText.indexOf('fareSessionUUID') !== -1) {
console.log('________________response____________');
var oData = JSON.stringify({'data': this.responseText});
console.log('new data');
console.log(oData);
window.flutter_inappbrowser.callHandler('myHandler', {foo: oData}).then(function(result) {
console.log(result, typeof result);
console.log(JSON.stringify(result));
})
}
}
}
if (this._onreadystatechange) {
return this._onreadystatechange.apply(this, arguments);
}
}
console.log(openReplacement.toString());
window.XMLHttpRequest.prototype.open = openReplacement;
window.XMLHttpRequest.prototype.send = sendReplacement;

Cannot get FileLeafRef property in SharePoint Rest API

Hi we are trying to retrieve the link URL of page in Site Pages using REST API the problem is that we cannot find the Name FileLeafRef property value.FileLeafReaf = null.
function fn_getListItems(webUrl,listTitle, queryText)
{
var viewXml = '<View><Query>' + queryText + '</Query></View>';
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
var queryPayload = {
'query' : {
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml' : viewXml
}
};
return fn_executeJson(url,"POST",null,queryPayload);
}
function fn_getListViewItems(webUrl,listTitle,viewTitle)
{
var url = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
return fn_executeJson(url).then(
function(data){
var viewQuery = data.d.ViewQuery;
return fn_getListItems(webUrl,listTitle,viewQuery);
});
}
function fn_executeJson(url,method,headers,payload)
{
method = method || 'GET';
headers = headers || {};
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if (typeof payload != 'undefined') {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}
Thanks.
SharePoint stores the full URL of a file in a hidden column EncodedAbsUrl.
So, you can request it explicitly as:
/_api/web/lists/getbytitle('Site Pages')/items?$select=*,EncodedAbsUrl
After that, you can directly use it somewhat as below, watch out for the quotes :
var items = data.d.results;
$.each(items, function(index, value) {
//Append results to DIV
$("#lstGlobalNews").append("<tr><td class='ms-vb2'><a href="+value.EncodedAbsUrl+" target='_blank'>"+value.Title+"</a></td><td class='ms-vb2' style='text-align: right;'>"+fn_FormatDate(value.Date_x0020_Posted)+"</td></tr>");
});
To retrieve FileLeafRef property, it needs to be explicitly specified in $select query option, for example:
/_api/web/lists/getbytitle('Site Pages')/items?$select=FileLeafRef
As alternative option it could also be retrieved via File resource, for example:
/_api/web/lists/getbytitle('Site Pages')/items?$select=File/Name&$expand=File
The FileLeafRef property only get the file name. If you want to get the file url, we need use ServerRelativeUrl property of file.
The REST API using this.
/_api/web/lists/getbytitle('Site%20Pages')/items?$select=File/ServerRelativeUrl&$expand=File

Post reply on SharePoint online discussion board using REST API

I am trying to post reply on a particular discussion of SharePoint online discussion board through REST API but unable to do it. I don't want to use SP.utilities as this REST API will be called from Android App.
Below is the code which I am implementing:
$.ajax({
url:"../_api/web/Lists/getbytitle(listname)/items?$filter=ParentItemID eq 40",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*"
},
success: function (data) {
alert("Successfully posted!!");
},
error: function (error) {
alert("error");
console.log(JSON.stringify(error));
}
});
Instead of creating reply inside discussion, it is creating a new discussion item.
Any help will be highly appreciated.
For creating a message item (reply) in Discussion Board the following properties needs to be specified:
FileSystemObjectType for a message items needs to be set to 0
ContentTypeId- content type Id of message item
ParentItemID - discussion item (container for messages) id
Regarding ParentItemID property
ParentItemID property could not be specified via message payload since it is a read only property, it means the following query for creating a message item fails:
Url /_api/web/lists/getbytitle('Discussions')/items
Method POST
Data {
'__metadata': { "type": "SP.Data.DiscussionsListItem" },
'Body': "Message text goes here",
'FileSystemObjectType': 0,
'ContentTypeId': '<MessageContentTypeId>',
'ParentItemID': <DiscussionItemId>
}
Solution
The following example demonstrates how to to create a message (reply) in Discussion Board via SharePoint REST API.
For creating a message under a discussion item (folder) the following
approach is used: once message item is created, it's getting moved
under a discussion item
var listTitle = "Discussions"; //Discussions Board title
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var messagePayload = {
'__metadata': { "type": "SP.Data.DiscussionsListItem" }, //set DiscussionBoard entity type name
'Body': "Message text goes here", //message Body
'FileSystemObjectType': 0, //set to 0 to make sure Message Item is created
'ContentTypeId': '0x0107008822E9328717EB48B3B665EE2266388E', //set Message content type
'ParentItemID': 123 //set Discussion item (topic) Id
};
createNewDiscussionReply(webUrl,listTitle,messagePayload)
.done(function(item)
{
console.log('Message(reply) has been sent');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
where
function executeJson(options)
{
var headers = options.headers || {};
var method = options.method || "GET";
headers["Accept"] = "application/json;odata=verbose";
if(options.method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if("data" in options) {
ajaxOptions.data = JSON.stringify(options.data);
}
return $.ajax(ajaxOptions);
}
function createListItem(webUrl,listTitle,payload){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
return executeJson({
"url" :url,
"method": 'POST',
"data": payload
});
}
function moveListItem(webUrl,listTitle,itemId,folderUrl){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")?$select=FileDirRef,FileRef";
return executeJson({
"url" :url
})
.then(function(result){
var fileUrl = result.d.FileRef;
var fileDirRef = result.d.FileDirRef;
var moveFileUrl = fileUrl.replace(fileDirRef,folderUrl);
var url = webUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
return executeJson({
"url" :url,
"method": 'POST'
});
});
}
function getParentTopic(webUrl,listTitle,itemId){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")/Folder";
return executeJson({
"url" :url,
});
}
function createNewDiscussionReply(webUrl,listTitle, messagePayload){
var topicUrl = null;
return getParentTopic(webUrl,listTitle,messagePayload.ParentItemID)
.then(function(result){
topicUrl = result.d.ServerRelativeUrl;
return createListItem(webUrl,listTitle,messagePayload);
})
.then(function(result){
var itemId = result.d.Id;
return moveListItem(webUrl,listTitle,itemId,topicUrl);
});
}

Facebook Canvas: Can't redirect in javascript

I am working on this seemingly trivial problem since three days and ran completely out of ideas why my code doesn't work.
In a nutshell, when the user receives a facebook request and clicks on it, it should be process the invitation.
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
if (window.location.href.indexOf('app_invite') !== -1 || window.location.href.indexOf('app_request') !== -1) {
var inviteeID = response.authResponse.userID;
processIncomingInvitation(inviteeID);
}
});
The problem occurs in the following function. Upon the successful $.post() request I am expecting a simple redirect:
$.post(url, function (result) {
window.location.replace('/True?fbapp=fbapp');
});
But the redirect is ignored and I don't understand why. I even put an alert('hello'); in there instead and I can clearly see it is hitting that bit of code. Why is the redirect ignored instead?
function processIncomingInvitation(inviteeID) {
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) {
return decodeURIComponent(s.replace(pl, " "));
},
query = window.location.search.substring(1);
while (match = search.exec(query)) {
urlParams[decode(match[1])] = decode(match[2]);
}
})();
var requestType = urlParams.app_request_type;
if (requestType === "user_to_user") {
var reqIDlist = urlParams.request_ids.split(',');
var requestID = reqIDlist[0];
FB.api(requestID, function (response) {
if (response.from !== undefined && response.from !== 'undefined') {
var inviterID = response.from.id;
var inviterName = response.from.name.split(" ")[0];
var url = '/friend/' + inviteeID + '/accept/' + inviterID + '/?fbapp=fbapp';
$.post(url, function (result) {
window.location.replace('/True?fbapp=fbapp');
});
deleteRequest(requestID);
}
});
}
}
I finally found the problem. The redirect was overridden by another redirect when you login the FB.
FB.Event.subscribe('auth.login', function (response) {
if (window.location.href.indexOf('notif_t=app_request') !== -1) {
alert('app_request: ' + window.location.href);
} else if (window.location.href.indexOf('notif_t=app_invite') !== -1) {
alert('app_invite: ' + window.location.href);
} else if (window.location.href.indexOf('fbapp') !== -1) {
alert('fbapp: ' + window.location.href);
window.location.replace('/?fbapp=fbapp');
}
});
You should redirect after the invite has been handled, which happens in FB.Event.subscribe('auth.authResponseChange', function (response) { ... } as described in the question.
Hence upon user login you should not redirect or the two redirects will collide. But you still want to redirect if its not an invite or request. Otherwise a returning user is stuck on login page.
The code above, now does exactly do that. I hope this helps.

Twitter OAuth with WinJS

Trying to authenticate with Twitter since over a week trough my Windows 8 app, but no success.
My app is registered at Twitter and it should be able to read, write and sign in.
I think I've tried all the descriptions at Twitter documentation, but nothing works. Guess the problem is at me, but can't find it.
I get always the 403 forbidden response.
My code:
function getTwitterCredentials() {
WinJS.xhr({
type:"get",
url: "https://api.twitter.com/oauth/authenticate",
headers: {
consumerKey: "ZSNRXXXXXXXXX",
userKey: "GVknHzXXXXXXXXXXXXXXXXXXX",
Authorization: "OAuth",
oauth_consumer_key: "ZSNRtXXXXXXXXXXXXX",
oauth_nonce: "b7efbXXXXXXXXXXXXXXXx",
oauth_signature: "23zb0XXXXXXXXXXXXXXx",
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: "1368555677",
oauth_token: "1408XXXXXXXXXXXXXXXXXXXXXXXXXXXXx",
oauth_version: "1.0"
}
}).done(function (response) {
//it it works here some will be some action
}, function error(response) {
console.log(response.status);
});
}
Someone has experience whit this issue?
Thanks Marlowe
Here's some demo JS code I slightly modified from an existing sample on our site from the oAuth Web Authentication Broker for Win8 demo. Search 'oob' for my changes, they are minor.
In addition, the Linq to Twitter project is pretty awesome so may want to consider checking that out as well and would prob be a bit easier. It handles the auth fairly automatically and doesn't require having to enter in the token response.
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved
(function () {
"use strict";
var page = WinJS.UI.Pages.define("/html/oAuthTwitter.html", {
ready: function (element, options) {
document.getElementById("oAuthTwitterLaunch").addEventListener("click", launchTwitterWebAuth, false);
//did read that this is required for oAuth in a win8 app, however twitter uses 'oob' for a desktop app's callback url.
//in fact your app will show it.
//var endURI = Windows.Security.Authentication.Web.WebAuthenticationBroker.getCurrentApplicationCallbackUri();
//document.getElementById("TwitterCallbackURL").innerText = endURI.displayUri;
}
});
function sendRequest(url) {
try {
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);
return request.responseText;
} catch (err) {
WinJS.log("Error sending request: " + err, "Web Authentication SDK Sample", "error");
}
}
function sendPostRequest(url, authzheader) {
try {
var request = new XMLHttpRequest();
request.open("POST", url, false);
request.setRequestHeader("Authorization", authzheader);
request.send(null);
if (request.status != "200") {
console.log(request);
}
return request.responseText;
} catch (err) {
WinJS.log("Error sending request: " + err, "Web Authentication SDK Sample", "error");
}
}
function isValidUriString(uriString) {
var uri = null;
try {
uri = new Windows.Foundation.Uri(uriString);
}
catch (err) {
}
return uri !== null;
}
var authzInProgress = false;
function launchTwitterWebAuth() {
var twitterURL = "https://api.twitter.com/oauth/request_token";
// Get all the parameters from the user
var clientID = document.getElementById("TwitterClientID").value;
if (clientID === null || clientID === "") {
WinJS.log("Please enter a ClientID for Twitter App", "Web Authentication SDK Sample", "error");
return;
}
var clientSecret = document.getElementById("TwitterSecret").value;
if (clientSecret === null || clientSecret === "") {
WinJS.log("Please enter a Secret for Twitter App", "Web Authentication SDK Sample", "error");
return;
}
var callbackURL = document.getElementById("TwitterCallbackURL").value;
//if (!isValidUriString(callbackURL)) {
// WinJS.log("Please enter a Callback URL for Twitter", "Web Authentication SDK Sample", "error");
// return;
//}
if (authzInProgress) {
document.getElementById("TwitterDebugArea").value += "\r\nAuthorization already in Progress ...";
return;
}
// Acquiring a request token
var timestamp = Math.round(new Date().getTime() / 1000.0);
var nonce = Math.random();
nonce = Math.floor(nonce * 1000000000);
// Compute base signature string and sign it.
// This is a common operation that is required for all requests even after the token is obtained.
// Parameters need to be sorted in alphabetical order
// Keys and values should be URL Encoded.
var sigBaseStringParams = "oauth_callback=" + encodeURIComponent(callbackURL);
sigBaseStringParams += "&" + "oauth_consumer_key=" + clientID;
sigBaseStringParams += "&" + "oauth_nonce=" + nonce;
sigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
sigBaseStringParams += "&" + "oauth_timestamp=" + timestamp;
sigBaseStringParams += "&" + "oauth_version=1.0";
var sigBaseString = "POST&";
sigBaseString += encodeURIComponent(twitterURL) + "&" + encodeURIComponent(sigBaseStringParams);
var keyText = clientSecret + "&";
var keyMaterial = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(keyText, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
var macAlgorithmProvider = Windows.Security.Cryptography.Core.MacAlgorithmProvider.openAlgorithm("HMAC_SHA1");
var key = macAlgorithmProvider.createKey(keyMaterial);
var tbs = Windows.Security.Cryptography.CryptographicBuffer.convertStringToBinary(sigBaseString, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
var signatureBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.sign(key, tbs);
var signature = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(signatureBuffer);
var dataToPost = "OAuth oauth_callback=\"" + encodeURIComponent(callbackURL) + "\", oauth_consumer_key=\"" + clientID + "\", oauth_nonce=\"" + nonce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"" + timestamp + "\", oauth_version=\"1.0\", oauth_signature=\"" + encodeURIComponent(signature) + "\"";
var response = sendPostRequest(twitterURL, dataToPost);
var oauth_token;
var oauth_token_secret;
var keyValPairs = response.split("&");
for (var i = 0; i < keyValPairs.length; i++) {
var splits = keyValPairs[i].split("=");
switch (splits[0]) {
case "oauth_token":
oauth_token = splits[1];
break;
case "oauth_token_secret":
oauth_token_secret = splits[1];
break;
}
}
document.getElementById("TwitterDebugArea").value += "\r\nOAuth Token = " + oauth_token;
document.getElementById("TwitterDebugArea").value += "\r\nOAuth Token Secret = " + oauth_token_secret;
// Send the user to authorization
twitterURL = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth_token;
document.getElementById("TwitterDebugArea").value += "\r\nNavigating to: " + twitterURL + "\r\n";
var startURI = new Windows.Foundation.Uri(twitterURL);
//var endURI = new Windows.Foundation.Uri(callbackURL);
//we use 'oob' in the request_auth, but now for authorize, we use the apps URI.
var endURI = Windows.Security.Authentication.Web.WebAuthenticationBroker.getCurrentApplicationCallbackUri();
authzInProgress = true;
Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
Windows.Security.Authentication.Web.WebAuthenticationOptions.none, startURI, endURI)
.done(function (result) {
document.getElementById("TwitterReturnedToken").value = result.responseData;
document.getElementById("TwitterDebugArea").value += "Status returned by WebAuth broker: " + result.responseStatus + "\r\n";
if (result.responseStatus === Windows.Security.Authentication.Web.WebAuthenticationStatus.errorHttp) {
document.getElementById("TwitterDebugArea").value += "Error returned: " + result.responseErrorDetail + "\r\n";
}
authzInProgress = false;
}, function (err) {
WinJS.log("Error returned by WebAuth broker: " + err, "Web Authentication SDK Sample", "error");
document.getElementById("TwitterDebugArea").value += " Error Message: " + err.message + "\r\n";
authzInProgress = false;
});
}
})();