i have a very basic jqm/phonegap app
here is my html
<html>
<head>
<title>jQuery Mobile Web App</title>
<link href="jquery-mobile/jquery.mobile-1.0.min.css" rel="stylesheet" type="text/css"/>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-mobile/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0.min.js" type="text/javascript"></script>
</head>
<body >
<div data-role="page" id="home" >
<div data-role="header">
<h1>p</h1>
</div>
<div data-role="content" style="text-align:right" id="c1">
</div>
</div>
</div>
</div>
here is my js code which is placed in the body of html code
<script>
function get_news_list(id , link_ , refresh_ ){
jQuery.support.cors = true;
$.ajax({
url : link_ ,
success:function(data){
$('#c1').html(data);
} ,
error : function(data) {
alert(data.toSource);
}
});
}
get_news_list('latest' , 'http://pnup.ir/?feed=json' , refresh_);
</script>
when i run it as a webpage i get
this alert
if firefox
function toSource() {
[native code]
}
in chrome
undefined
which i assume is ok cuz it's a cross domain ajax request and it fails in a web browser (altho in firebug it's status is ok 200 it just doesn't return anything as response )
but when i test it on my android device i get the same undefined . i thought cross domain ajax request isn't problem once i rune it as app in android device ?
am i missing something ? should i use jsonp ? its a wordpress website and with json feed plugin its feeds are available in json but getting jsonp feed would be a nightmare ... at least i dont know how !
i implemented jsonp recently in one of my phonegap + jquerymobile project, i had the same issue but i used asp.net for my services
calling the service like below worked for me all you have to do is add ?fnCallBack=? at the end of the url
$.ajax({
url : link_+'?fnCallBack=?',
contentType : "application/json; charset=utf-8",
dataType : "json",
jsonp : 'json',
cache : false,
success : function(result) {
if (result != 'Error') {
var valX = JSON.stringify(result);
valX = JSON.parse(valX);
} else {
navigator.notification.alert("An error occured, Please try later");
}
}
});
and on the server side when you send json response just add fnCallBack like this
string jsoncallback = context.Request["fnCallBack"];
context.Response.Write(string.Format("{0}({1})", jsoncallback,jsonData));
this way i solved my cross domain issue so hoping you ll get a clue from this
Related
is there any way to call a controller function when someone click on a check box. Like There are 4 check box with each has a category so when a user click on particular category then it will hit an API that process the filter request from the backend. I searched on Google but there is option to change it to
But that I don't want. Do I have to use jquery or else?
As in the comment section you can achive this via JQuery/Javascript. I have added a simple example with JQuery for your reference. What I achive here is first catch all check un check events and then via Ajax I send a request to the server. So that controller function will get called. You can test this via network tab when you check or uncheck a checkbox.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Check the Status of Checkboxes</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
//Add CSRF token to headers
$.ajaxSetup({
headers:
{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$('input[type="checkbox"]').click(function(){
const val = $(this).val()
if($(this).prop("checked") == true){
alert(val+' Checked and sending data to server')
$.ajax({
type: "POST",
url: "file", // Route
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( "Data: " + msg );
});
}else{
alert($(this).val()+' unchecked');
$.ajax({
type: "POST",
url: "file",
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( 'Record removed' );
});
}
});
});
</script>
</head>
<body>
<input value="A" type="checkbox"> A
<input value="B" type="checkbox"> B
<input value="C" type="checkbox"> C
</body>
</html>
Take a look at:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Récupération d'un contenu HTML en Jquery Ajax</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script type="text/javascript">
function recupTexte() {
$.ajax({
url: "data.xml"
})
.done(function( texte ) {
$('body').append( " : " + texte );
});
}
setInterval(recupTexte, 1000);
</script>
</body>
</html>
data.xml
test
When I go to my web browser Safari, I have "test" displayed, but when I edit my data.xml file manually to "changed", Safari continues to display "test" and no "changed". Why ? I don't understand...
So, just to say it, this code only works in safari, and in local. When I put it in a server, nothing is displayed....
This might be an issue due to caching of get request. Try disabling the cache using :
$.ajaxSetup({ cache: false });
or inside your ajax call
$.ajax({
cache: false,
//other options...
});
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...
problem : ajax error with google chrome
index.html --- POST ---> page1.php --- link ---> page2.html
“index.html” contains a <form> that posts to “page1.php”
“page1.php” contains a link to “page2.html”
“page1.php” contains an ajax call to “ajax.php”
how to make the problem appear ?
visit “index.html”
post to “page1.php”
follow link to “page2.html”
go back to “page1.php” with the back button
reload “page1.php” with F5
accept to re-submit the datas
ajax error : the ajax call fails with an empty error message
why is... that thing ?
index.html :
<html>
<head>
</head>
<body>
index
<form method="post" action="page1.php">
<input type="submit">
</form>
</body>
</html>
page1.php :
<html>
<head>
<script src="jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function call_ajax()
{
$.ajax
(
{
type: "POST",
url: "ajax.php",
success: function( response )
{
console.log( response );
},
error: function (xhr, ajaxOptions, thrownError)
{
console.log( '%o', xhr );
console.log( '%o', xhr.responseText );
console.log( '%o', thrownError );
}
}
);
}
$( document ).ready(function() {
call_ajax();
});
</script>
</head>
<body>
page 1
page2
</body>
</html>
page2.html :
<html>
<head>
</head>
<body>
page 2
back
</body>
</html>
ajax.php :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('error_reporting', E_ALL);
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
$r = array( 'message' => 'one two one two, this is a test' );
echo json_encode( $r );
?>
Might it be, that there is something wrong with the configuration of your server/browser?
I tried to confirm your problem by creating the files with exactly the same code as above in my local installation of lighttpd using PHP via fastcgi and running Chromium version 30.0.1553.0 (209444), but was unable to reproduce your issue.
When looking at the console, the log always shows the correct output whether I access page1.php from index.html or from page2.html using the "back" link and refreshing with F5.
Object {message: "one two one two, this is a test"}
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