JQuery ajax call in a JS function fails on iOS but works great on Windows 10 pc - ios

Wracking my brain for quite some time on this - thought I'd ask the experts for an assist...
The gist of my code below is to call a php function (via ajax POST) that updates a MySQL table when a registration request is rejected by an administrator.
When executing in Windows 10, all works as expected. But on iOS, it throws the error alert found in the .fail function of the ajax call (alert("A problem has occurred with your rejection at tec_regadmin. " + teststat2 + " Please copy this error and contact your abc administrator for details.");). Also, teststat2 is displayed as [object Object] on iOS.
An additional twist - the MySQL table successfully UPDATEs to show that the request was rejected. Code snippets are below:
JS function with embedded ajax call to ../services/ajax_reject_registrant.php:
function regreject(Select, Directory_ID, Log_In, Gender_sex, First_Name, Last_Name) {
console.log("Made it into the regreject function");
var jQ13 = jQuery.noConflict();
jQ13(document).ready(function () {
jQ13.ajax({
cache: false,
headers: { "cache-control": "no-cache" },
url: '../services/ajax_reject_registrant.php',
type: 'POST',
dataType: 'json',
data: { Selected: Select, Directory: Directory_ID, Login: Log_In, Gender: Gender_sex, FirstName: First_Name, LastName: Last_Name }
})
.done(function (jqXHR, textStatus) {
// Get the result
var teststat = textStatus;
var teststat2 = jqXHR;
console.log("ajax reject success response data = " + teststat);
console.log("ajax reject success response text = " + teststat2);
alert("Registrant has been disabled in the database.");
location.reload();
return;
})
.fail(function (jqXHR, textStatus) {
// Get the result
var teststat = textStatus;
var teststat2 = jqXHR;
console.log("ajax reject failure response data = " + teststat);
console.log("ajax reject failure response text = " + teststat2);
alert("A problem has occurred with your rejection at tec_regadmin. " + teststat2 + " Please copy this error and contact your abc administrator for details.");
location.reload();
return;
});
});
};
PHP script (../services/ajax_reject_registrant.php) called from ajax:
<?php
//New Registrant Reject script
//Called from tec_regadmin.php
//Last Updated 2020/12/09
if ( isset($_POST['Selected']) ) {
require('../tec_dbconnect.php');
include('../includes/event_logs_update.php');
include('tec_sendmail.php');
$Selected2 = $_POST['Selected'];
$Directory2 = $_POST['Directory'];
$Login2 = $_POST['Login'];
$Gender2 = $_POST['Gender'];
$FirstName2 = $_POST['FirstName'];
$LastName2 = $_POST['LastName'];
$text = array();
$regrejectloginquery = "UPDATE " . $_SESSION['logintablename'] . " SET active = '2'" . " WHERE login_ID = '". $Login2 . "'";
$regrejectlogin = $mysql->query($regrejectloginquery) or die("A database error occurred when trying to reject new Registrant info into Login table. See ajax_reject_registrant.php. Error:" . $mysql->errno . " : " . $mysql->error);
eventLogUpdate('admin_update', "Admin ID: " . $_SESSION['user_id'], "Registrant Reject", "LoginID: " . $Login2 . " - Directory entry: " . $Directory2);
$success = 'Reject Success';
header('Content-type: application/json');
echo json_encode($success);
}
else{
$failed = 'Reject Failed';
header('Content-type: application/json');
echo json_encode($failed);
}
?>
Let me know if you have any questions. Any suggestions would be GREAT!
Thank you!!!

[SOLVED]
A PHP form is used to call the above function (regreject) and was missing an action statement (was displayed as action=''). By modifying the action to include javascript:void(0); the issue resolved itself. All I needed to do was change the action to action="javascript:void(0);" in the original PHP form, and now iOS is a happy camper!
The final question I will have to ponder is "WHY was this a problem with iOS??" Wonder if I'll ever find out.

Related

PhoneGap check if file exists

I want to check if file exists, and if it does not, download it. I have tried suggested solutions in this SO question and this blog post
But none of those solution worked for me. Here is my code based on SO question:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
console.log("gotFS");
getFolder(fileSystem, video.folderName, function(folder) {
console.log("Got folder");
var filePath = folder.toURL() + "\/" + "videotest.mp4";
fileSystem.root.getFile(filePath, { create: false }, playVideo(filePath, true), transferFile(video.uri, filePath));
}, function() {
console.log("failed to get folder");
});
},
function() {
console.log("failed to get filesystem");
});
Play video function looks like this:
function playVideo(uri, hasBeenDownloaded) {
console.log("was video dowloaded already", hasBeenDownloaded);
var player = document.getElementById("videoPlayer");
var source = document.createElement("source");
source.src = uri;
source.type = "video/mp4";
player.appendChild(source);
player.load();
}
And here is transferFile function:
function transferFile(uri, filePath) {
var transfer = new FileTransfer();
transfer.download(
uri,
filePath,
function (entry) {
var targetPath = entry.toURL();
console.log("target path je", targetPath);
document.getElementById("result").innerHTML = "File saved to: " + targetPath;
playVideo(targetPath, false);
},
function (error) {
document.getElementById("result").innerHTML = "An error has occurred: Code = " + error.code;
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
}
);
}
What happens is that both playVideo and transferFile are allays called, no matter if file exists or not.
For example if file already exists, firstly only playVideo will be called and in console it will be logged:
was video dowloaded already: true
And after sometime I see that transferFile function was called, and when file is downloaded it will call playVideo and in console i can see:
was video dowloaded already: false
So why is this happening ?
P.S.
With code suggested in blog post problem is completely same, i.e. both functions are called.
Your code is passing the called function as the callback, not the function itself. Let me give an example. Imagine you have function Foo. It asks you to pass 2 callback functions - one for success, one for failure. You could do this:
function good() { alert('good'); };
function bad() { alert('bad'); };
foo(good, bad);
However, this is what you did:
foo(good(), bad());
This is why you have both being called. You need to change:
fileSystem.root.getFile(filePath, { create: false }, playVideo(filePath, true), transferFile(video.uri, filePath));
to
fileSystem.root.getFile(filePath, { create: false }, playVideo, transferFile);
which means you'll need to access the values you need not as arguments but as regular variables.

Parsing rss feed. Some fields undefined

I am attempting to parse this rss feed - http://www.spiegel.de/international/germany/index.rss
I am using the following code to parse it:
$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' +
encodeURIComponent('http://www.spiegel.de/international/germany/index.rss'),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("link : " + e.link);
console.log("pubDate : " + e.pubDate);
console.log("description : " + e.description);
console.log("pubDate : " + e.pubDate);
console.log("guid: " + e.guid);
});
}
}
});
In the console.log only the title and the link appear. The description, pubDate and guid are all undefined.
Could someone be so kind as to explain what I am doing wrong?
You can check the whole "schema" of the response given by Google using this gist.
You'll see that each entry has the following items:
title
link
author
publishedDate
contentSnippet
content
categories
So, unfortuately for you the guid is missing. You'll have to use content (or contentSnippet) instead of description and publishedDate instead of pubDate. If you really need the guidcheck out the alternative offred by Superfeedr (I created Superfeedr!).

Titanium Studio to Grails imge post

I am trying to POST an image to my grails application and I'm not having much luck.
My titanium code is:
function upload(){
var xhr = Titanium.Network.createHTTPClient();
xhr.onerror = function(e){
Ti.API.info(picMedia + " : " +message.value);
Ti.API.info('IN ERROR ' + e.error);
alert('Sorry, we could not upload your photo! Please try again.');
};
xhr.onload = function(){
Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
};
xhr.onsendstream = function(e){
Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress);
};
// open the client
xhr.open('POST', 'http://localhost:8080/FYP/Profile/appUploader');
// send the data
xhr.send({
media: picMedia,
message: message.value,
});
}
My grails code is as follows:
def appUploader(){
println "MEDAI PARAMS: " + params.media
def f = request.getFile('media') ;
println "HERE: " + f
if (request.getFile(params.media).getOriginalFilename()) {
println "FROM APP: " + request.getFile('myFile').getOriginalFilename()
return
}
}
Im getting error from the mobile app and error on the "if" line in the web app.
What am i doing wrong?
we had the same problem in one of our apps. The difficulty is that titanium is not really able to handle binary files in that case.
We did the following:
create base64 encoded string of the image on client side
post this string to the backend
decode base64 to image again
We analyzed a lot of network traffic and in most cases titanium tries to send the file but due to javascript its alway converted into some kind of ascii and this is not usable by the server side.

Phonegap MobileJQuery AJAX Posts Twice while debugging

Hope there is some out there that can help!,
While debugging a WCF service that a phonegap application connects to it seems to post twice.
When the application runs normally no Break points etc it all works fine and i only receive 1.
It appears to me that ajax reposts itself if no response is returned from the server after a few seconds.
I will need to confirm this threw wireshark but just wanted to know if anyone else has come accross this before.
$.ajax({
type: "POST",
url: ServicePATH ,
data: JSON.stringify({ objs: arrayobj, parm2: var2, parm3: var3, parm4: 1 }),
contentType: "application/json",
dataType: "json",
success: function (data, textStatus, jqXHR) {
CallonSuccess(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error ' + textStatus);
console.log('XMLHttpRequest ' + XMLHttpRequest);
var str = '';
for (prop in XMLHttpRequest) {
str += "prop " + prop + " value :" + XMLHttpRequest[prop] + "\n"; //Concate prop and its value from object
}
console.log(str);
console.log('errorThrown ' + errorThrown);
console.log('passing ' + JSON.stringify({ objs: arrayobj, parm2: var2, parm3: var3, parm4: 1 }));
}
}).done(function () { console.log('Finished ajax'); });
Thanks Lmac
Perhaps no solution (see update below) for you but the same behaviour here.
Without the jquery Mobile framework everything works okay, with the framework embedded it fetches my json file a second time. In Chrome's Console you can see it under Network: GET status 200 and GET status 304 (not modified).
I have the option to throw out jQuery Mobile and I surely will. But would be also interested in knowing what's happening there.
UPDATE:
I had the xmlhttprequest within the $(document).ready(function() { }); It seems as if both jQuery and jQuery Mobile react to that.
If I put the script at the end of the site and make my xmlhttprequest outside the ready-method it fetches my json file only once.

Ajax In Firefox Plugin

Is there any way to send Ajax requests to server from a Firefox plugin? If yes, how? If no, how do we have client server communication in Firefox plugins?
I want to get some JSON data from server and manipulate the DOM object according to the client input.
I am pretty a beginner in plugin programming.
You can send ajax requests from firefox extension using xmlHTTPRequest, like in any other web application.
From a contentscript you should add the permissions to access cross-domain content, URLs you want to:
"permissions": {
"cross-domain-content": ["http://example.org/", "http://example.com/"]
}
More info in the documentation.
Here's a simple snippet that does XHR request, WITHOUT cookies (due to flag Ci.nsIRequest.LOAD_ANONYMOUS can remove to send with cookies) (MDN :: Info on flags]. Copy this first code block in, then see usage examples below.
var {Cu: utils, Cc: classes, Ci: instances} = Components;
Cu.import('resource://gre/modules/Services.jsm');
function xhrGetPost(url, post_data, cb) {
let xhr = Cc["#mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
let handler = ev => {
evf(m => xhr.removeEventListener(m, handler, !1));
switch (ev.type) {
case 'load':
if (xhr.status == 200) {
cb(xhr.response);
break;
}
default:
Services.prompt.alert(null, 'XHR Error', 'Error Fetching Package: ' + xhr.statusText + ' [' + ev.type + ':' + xhr.status + ']');
break;
}
};
let evf = f => ['load', 'error', 'abort'].forEach(f);
evf(m => xhr.addEventListener(m, handler, false));
xhr.mozBackgroundRequest = true;
if (post_data == undefined) {
post_data = null;
}
if (post_data) {
xhr.open('POST', url, true);
} else {
xhr.open('GET', url, true);
}
xhr.channel.loadFlags |= Ci.nsIRequest.LOAD_ANONYMOUS | Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_PERSISTENT_CACHING;
//xhr.responseType = "arraybuffer"; //dont set it, so it returns string, you dont want arraybuffer. you only want this if your url is to a zip file or some file you want to download and make a nsIArrayBufferInputStream out of it or something
xhr.send(post_data);
}
Example usage of for POST:
var href = 'http://www.bing.com/'
xhrGetPost(href, 'post_data1=blah&post_data2=blah_blah', data => {
Services.prompt.alert(null, 'XHR Success', data);
});
Example usage of for GET:
var href = 'http://www.bing.com/'
xhrGetPost(href, null, data => {
Services.prompt.alert(null, 'XHR Success', data);
});

Resources