Cross-Domain Service Calls via JQuery Mobile/PhoneGap and ASP.NET MVC 3 - 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

Related

How to call a controller function when someone click on a check box in laravel 8

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>

Phonegap app works on emulator not on device

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...

Routing for Symfony2 TWIG templates with AJAX

I have been struggling with this for a couple days and have yet to find any real solutions online yet. I have a form that allows users to enter their email, then after they enter it fades out and is replaced by another form. I am using ajax to submit data from a form to a symfony2 controller, which stories it in the database and sends a response. However, the response ends up just sending me to a blank page with the response data displayed, instead keeping me on the same page and just fading the boxes as needed. I think my issue is with how I have the controller actions set up and the routing files.
EDIT
Well now the issue is that when I click on the submit button nothing happens. Nothing is sent to the controller, so nothing is being stored and no response is being given. What I changed was based on the answer by #PaulPro, appending the
<script> $('#emailForm').submit(submitForm); </script>
to the end of the html page. Thanks in advance for any help and insight!
The controller has 2 relevant actions, the one that renders the TWIG Template with the form, and the one that handles the ajax form submission and returns the response.
public function emailAction()
{
return $this->render('Bundle:email.html.twig');
}
public function submitEmailAction()
{
$em = $this->getDoctrine()-> getEntityManager();
$email = new Email();
$request = $this->getRequest();
$emailVar = $request->request->get('emailSignup');
$email -> setEmail($emailVar);
$em->persist($email);
$em->flush();
$return=array("responseCode"=>200);
$return = json_encode($return);
return new Response($return, 200, array('Content-Type'=>'application/json'));
}
This is the routing for those actions, most likely the culprit of it all:
Bundle_email:
pattern: /email
defaults: { _controller: Bundle:email }
requirements:
_method: GET
Bundle_submitEmail:
pattern: /submitEmail
defaults: { _controller: Bundle:submitEmail }
requirements:
_method: POST
And then here is the email.html.twig template and ajax script:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="{{asset('css/styles.css')}}" rel="stylesheet" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
function submitForm(){
var emailForm = $(this);
var path = "{{path('Bundle_submitEmail')}}"
$.ajax ( {
type: 'POST',
url: $("#emailForm").attr("action"),
emailSignup: $("#emailId").val(),
success: function(data){
if(data.responseCode==200 ){
$('.email-signup-form').fadeOut();
$('.share-form').delay(500).fadeIn();
}
}
});
return false;
}</script>
</head>
<body>
<form id="emailForm" action="{{path('Bundle_submitEmail')}}" method="POST" class="email-signup-form">
<input type="email" placeholder="e-mail address" name="emailSignup" id="emailId" required="true"/>
<input type="submit" value="Go">
</form>
<form class="share-form">
</form>
<script> $('#emailForm').submit(submitForm); </script>
</body>
</html>
You don't ever call submitForm (the function that tells the browser to use AJAX rather than a full page load). Just add a script at the end of your body that looks like:
<script>
$('#emailForm').submit(submitForm);
</script>

cross domain ajax request fails in android device

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

ajax call success function never called

The following code is a very simple ajax call to server that alerts back on success and complete events.
From a reason I cannot understand on my development machine it works fine and alerts on success and complete but on server it never alerts on success. WHY ???
**
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function dummy() {
$.ajax({
url: 'services/chatEngine.asmx/dummy',
async: true,
type: "POST",
complete: function () { alert('Done'); },
success: function (a, b, c) {
alert('Success');
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajaxToolkit:ToolkitScriptManager>
<div id="userList">Users:<br /></div>
<input id="Button3" type="button" value="dummy" onclick="dummy()" />
</div>
</form>
</body>
</html>
**
The server side dummy function returns nothing, code follows -
<WebMethod(True)>
Public Function dummy() As String
Return ""
End Function
You need to find out where the failure is.
1) Is the client making the request? Use your browsers developer tool request monitor or something like Charles to look at the request data. make sure the URL is correct.
2) Is the server getting the request? Use server logs or attach a debugger to verify the request is received.

Resources