Phonegap app works on emulator not on device - ajax

Im testing simple phonegap app for adding comment with remote server. ive tested in telerik icenium simulator and in browser and it works. But when I try to test in visual studio emulator and click the button it says "CordovaBrowser_NavigationFailed :: www/index.html?email=fgg#vv.com&comment=Gjjj". I`ve tested on device too, but there nothing happens.
Here is the code.
index.html - the main page
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;">
<title>jQuery form post</title>
<script src="cordova.js"></script>
<script src="js/index.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/post.js"></script>
<script src="js/jquery.mobile-1.4.3.js"></script>
<script>
function onBodyLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
</script>
<style>
label, b {
display: block;
}
</style>
</head>
<body onload="onBodyLoad()">
//content
<div id="landmark-1" data-landmark-id="1">
<form>
<label for="email">
<b>Email</b>
<input type="email" id="email" name="email">
</label>
<label for="comment">
<b>Comment</b>
<textarea id="comment" name="comment" cols="30" rows="10"></textarea>
</label>
<input type="submit" value="Save">
</form>
</div>
</body>
</html>
post.js
$(document).bind('deviceready', function () {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.mobile.pushStateEnabled = false;
$(function () {
$('form').submit(function () {
var landmarkID = $(this).parent().attr('data-landmark-id');
var postData = $(this).serialize();
$.ajax({
type: 'POST',
data: postData + '&lid=' + landmarkID,
//change the url for your project
url: "http://bgg.comxa.com/new.php",
crossDomain: true,
success: function (data) {
console.log(data);
alert('Your comment was successfully added');
},
error: function () {
console.log(data);
alert('There was an error adding your comment');
}
});
return false;
});
});
});

As I understand this error message does not state that there is anything wrong with your index.html file, it does not seem to be able to reach it at all.
Check out this thread: Navigation in phonegap application fails when I use GET variables
There might be something about the way you try to reach your index.html file. Maybe you are going straight to "index.html" and not "www/index.html", as it states in the post answer.
Hope this helps!

After a lot of reading, i think the problem is in webkit prowsers. I`ve read that there is issues with ajax requests in webkit based browsers. I will try the code at real mobile phone device and see...

Related

d3.xhr example or AJAX d3's way

I've been looking for an example of updating data with d3.xhr but have not seen anything obvious, or at least of my level of understanding. The following 2 links are close but no cigar:
from stackoverflow
from mbostock’s block
I look around more and found this example in jquery and php. I tried it and understand the code. I would appreciate if you give me an equivalent code in d3.xhr or d3.json. BTW, what is different between d3.xhr and d3.json, and when to use what? Thanks in advance.
<?php
// AJAX & PHP example
// http://iviewsource.com/codingtutorials/learning-how-to-use-jquery-ajax-with-php-video-tutorial/
if ($_GET['ip']) {
$ip = gethostbyname($_GET['ip']);
echo($ip);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Get Reverse IP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>
<body>
Please enter a domain name
<input type="text" id="searchip">
<div id="resultip"></div>
<script>
$(document).ready(function() {
$('#searchip').change(function(){
$.ajax({
type: "GET",
url: "ajax.php",
data: 'ip=' + $('#searchip').val(),
success: function(msg){
$('#resultip').html(msg);
}
}); // Ajax Call
}); //event handler
}); //document.ready
</script>
</body>
</html>
I found the solution. In fact it has less coding, :) I sincerely hope that the answer would be useful to someone.
<?php
// AJAX & PHP example
if ($_GET['ip']) {
$ip = gethostbyname($_GET['ip']);
echo($ip);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Get Reverse IP</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
Please enter a domain name
<input type="text" id="searchip">
<div id="resultip"></div>
<script>
d3.select('#searchip').on("change", function() {
d3.xhr('xhr.php?ip='+this.value, function(data) {
d3.select('#resultip').html(data.response);
})
});
</script>
</body>
</html>

JQuery Mobile Validate after changePage

I'm using JQuery Mobile with a form that changes server side. I need to reload the page so the most recent form is included on the page. The form also needs validation.
I'm able to get the validation to work once but once until a submit. The page successfully is refreshed and the form appears but the validation is gone and if I submit, a standard submit is done instead of a changePage.
The on pageinit seems to be firing every time. I've been pulling my hair out on this one. It seems like this should be so simple.
<?php //
session_start();
if (isset($_SESSION['mytest']))
$_SESSION['mytest']++;
else
$_SESSION['mytest'] = 1;
$s = $_SESSION['mytest'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>mytestout</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="//code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css">
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"> </script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
</head>
<body>
<div data-role="page" data-theme='b' id="testit" >
<div data-role="content" class="content" id="cart" style="margin-top: 25px; margin-left: 40px">
<p> counting session var = <?=$s?> </p>
<form id="myform">
<input type="text" name="myname">
<input type="submit">
</form>
</div>
</div>
<script>
function submitme(e) {
$.mobile.changePage( "#testit", { transition: "slideup", changeHash: false, reloadPage: true, allowSamePageTransition: true });
}
$(document).on('pageinit', function(){ //
$("#myform").validate( {
rules: {
myname: "required"
}
,submitHandler: function(e) { submitme(e);}
});
});
</script>
</body>
</html>
The problem here is the 'pageinit' event, which runs just once per page (its also deprecated). You'd have to use the pagecontainershow event, which runs each time the page is shown. That should initialize the form validation again, making it work for each time its rendered. Note that I haven't tested that solution, yet.

JQuery Validation plugin not working with minlength

I've been fighting with this for a while now and have searched extensively to no avail. I grabbed a link someone posted here in response to my same question. enter link description here I've copied the code to my editor, placed the stylesheet inline, linked all the scripts correctly I think...
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"</script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"</script>
<style> #docs{
display:block;
postion:fixed;
bottom:0;
right:0;
}
</style>
</head>
<body>
<form id="form_validation_reg_generate_user">
<input type="text" name="userPassword" id="userPassword" />
<br/>
<input type="submit" />
</form>
<a id="docs" href="http://docs.jquery.com/Plugins/Validation" target="_blank">Validation Documentation</a>
<script type="text/javascript" src="js/jquery.validate.min.js"></script>
<script>
$(document).ready(function () {
$('form#form_validation_reg_generate_user').validate({
rules: {
userPassword: {
minlength: 5
}
},
submitHandler: function (form) { // for demo
alert('valid form submission'); // for demo
return false; //form demo
}
});
});
</script>
</body>
No validation occurs... I have a feeling I'm missing something obvious. It was working in a separate page when I was only validating required fields. Since adding the minlength... nothing.
I'm doing a test with your code and it seems to work perfectly. Check if your jquery.validate.min.js path is correct and if you can access properly to every script from your system.
Also you can use your browser development tools to check if you have exceptions.
The jquery.validate.iin.js version I used in the text is from this website. Maybe you have an older script?

Ajax call fail when I can trying to pass the special characters as data

This is the code I am using to add a comment using Ajax call.
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile- 1.1.0-rc.1.min.css" />
<script type="text/javascript" charset="utf-8" src="js/cordova-1.5.0.js">
</script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.js"></script>
<script src="js/global.js" type="text/javascript"></script>
</head>
<script>
var msgId = window.localStorage.getItem("clickedId");
processLogInData = function(){
var comment = ($("#comment").val());
temp = 'messageId=' + msgId +'&';
temp += 'uniqueId=' + device.uuid + '&';
temp += 'comments=' + comment;
var s= global1 +"rest/Comment/createCommentBO?"+temp;
$.ajax({
url:global1 +"rest/Comment/createCommentBO?",
data: temp,
dataType: 'xml',
timeout: 10000,
async: false,
cache: false,
type: 'POST',
success: function(data){
if($(data).find("isException").text() == "false")
{
//alert('No Exceptions found');
onTrue();
}
else
{
onFalse();
}
},
error:function(XMLHttpRequest,textStatus, errorThrown) {
// alert("Error status :"+textStatus);
// alert("Error type :"+errorThrown);
alert("Error message :"+XMLHttpRequest.responseXML);
$("#messagelist").append( XMLHttpRequest.responseXML);
}
});
}
function onTrue(){
location.replace("comments.html");
}
function onFalse()
{
console.log("onFalse Method");
alert("Unable to create Comment!");
}
function cancel(){
location.replace("comments.html");
}
</script>
<body>
<div data-role="page" data-theme="a">
<div data-theme="a" data-role="header">
<img src="images/logo_header.png" alt="Orange"/>
</div>
<div data-role="content">
<form method="post" name="login" data-ajax="false">
<label for="textarea"><h3><u>Add Comment</u> : </h3></label>
<textarea cols="15" rows="15" name="textarea" id="comment"></textarea>
</form>
<div>
<div class="ui-block-a"><button type="submit" data-theme="d" onclick="cancel();" data-mini="true" data-icon="delete">Cancel</button></div>
<div class="ui-block-b"><button type="submit" data-theme="a" onclick="processLogInData();" data-mini="true" data-icon="check" >Submit</button></div>
</div>
</div>
</div>
</body>
When I enter special character as content as pass it to Ajax call I am getting an error :( Ajax call works fine with out any special characters...
Is there any way to encode the data before passing it to ajax call???Please help me on this...
Thanks in advance.
(1.)Either you should put your data into a form and serialize it and then send to the server
(2.)Second way is you can use the js inbuilt function encodeURIComponent().

Cross-Domain Service Calls via JQuery Mobile/PhoneGap and ASP.NET MVC 3

I am trying to build a mobile app with JQuery Mobile and PhoneGap. This app will hit a backend I'm working on with ASP.NET MVC 3. Right now, I'm just trying to get a basic GET/POST to work. I've created the following test page.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="stylesheet" href="resources/css/themes/default/core.css" />
<link rel="stylesheet" href="resources/css/themes/default/app.css" />
<script src="resources/scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="resources/scripts/jquery.mobile-1.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
}
</script>
</head>
<body onload="initialize();">
<div id="testPage" data-role="page">
<div data-role="header" data-position="fixed">
<h1>TEST</h1>
</div>
<div data-role="content">
<input id="twitterButton" type="button" value="Test GET via Twitter" onclick="twitterButton_Click();" />
<input id="getButton" type="button" value="Test GET via MVC 3" onclick="getButton_Click();" />
<input id="postButton" type="button" value="Test POST via MVC 3" onclick="postButton_Click();" />
<div id="status"></div>
</div>
<div data-role="footer" class="ui-bar" data-position="fixed">
</div>
<script type="text/javascript">
function twitterButton_Click() {
$("#status").html("Testing Twitter...");
var vm = { q:"1" };
$.ajax({
url: "http://search.twitter.com/search.json?q=weekend&rpp=5&include_entities=true&result_type=mixed",
type: "GET",
dataType: "jsonp",
contentType: "application/json",
success: twitter_Succeeded,
error: twitter_Failed
});
}
function twitter_Succeeded(result) {
$("#status").html("Twitter GET Succeeded!");
}
function twitter_Failed(p1, p2, p3) {
$("#status").html("Twitter GET Failed :(");
}
function getButton_Click() {
$("#status").html("Testing Get...");
var vm = { q:"1" };
$.ajax({
url: "https://www.mydomain.com/myService/testGet",
type: "GET",
data: vm,
contentType: "application/json",
success: get_Succeeded,
error: get_Failed
});
}
function get_Succeeded(result) {
$("#status").html("MVC 3 GET Succeeded!");
}
function get_Failed(p1, p2, p3) {
$("#status").html("MVC 3 GET Failed :(");
}
function postButton_Click() {
$("#status").html("Testing POST...");
var vm = { data:"some test data" };
$.ajax({
url: "https://www.mydomain.com/myService/testPost",
type: "POST",
data: JSON.stringify(vm),
contentType: "application/json",
success: post_Succeeded,
error: post_Failed
});
}
function post_Succeeded(result) {
$("#status").html("MVC 3 POST Succeeded!");
}
function post_Failed(p1, p2, p3) {
$("#status").html("MVC 3 POST Failed :(");
}
</script>
</div>
</body>
</html>
When I run this page from within Visual Studio, I change the AJAX url calls to be relative calls. They work perfectly. However, because my goal is run this app from within PhoneGap, I know that this page will actually run as a local file (http://jquerymobile.com/demos/1.1.0/docs/pages/phonegap.html). Because of this, I've used the code above and created test.html on my local machine.
When I try to run this code, the Twitter test works. Oddly, all three actions work in Internet Explorer. However, when I use Chrome or FireFox, the tests to my server do NOT work. In Chrome, I notice the following in the console:
XMLHttpRequest cannot load https://www.mydomain.com/myService/testGet?q=1. Origin null is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load https://www.mydomain.com/myService/testPost. Origin null is not allowed by Access-Control-Allow-Origin.
I reviewed this: Ways to circumvent the same-origin policy. However, none of them seem to work. I feel like there is some server side configuration I'm missing. Currently, my TestGet and TestPost actions look like the following:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult TestGet(string q)
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
return Json(new { original = q, response=DateTime.UtcNow.Millisecond }, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestPost(string data)
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
return Json(new { status=1, response = DateTime.UtcNow.Millisecond }, JsonRequestBehavior.AllowGet);
}
I feel like I'm SO close to getting this work. What am I missing? Anyhelp is sincerely appreciated.
Try it from an actual device or simulator and it will work. From the FAQ:
The cross-domain security policy does not affect PhoneGap
applications. Since the html files are called by webkit with the
file:// protocol, the security policy does not apply. (in Android,you
may grant android.permission.INTERNET to your app by edit the
AndroidManifest.xml)
It will always work with Twitter as it uses JSONP to respond to queries. You have to start Chrome or Firefox the proper way to tell it to allow CORS. For Chrome it is:
chrome --disable-web-security

Resources