Routing for Symfony2 TWIG templates with AJAX - 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>

Related

Send method in new Vue is not called when form is submitted

<!DOCTYPE html>
<head>
<meta charset=" UTF-8">
<title> Document</title>
</head>
<body id="chat">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.5.0/socket.io.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.min.js"></script>
<form v-on="submit: send">
<input v-model="message">
<button>Send</button>
</form>
<script>
var socket = io();
new Vue({
el: '#chat',
date: {
message: ''
},
methods: {
send: function(e)
{
e.preventDefault();
alert("a");
}
}
})
</script>
</body>
I want to call the send method defined in new Vue when the form is submitted ,
But when i submit the form, page is reloading.
I have created a Vue object and linked it to the chat element.
I guess e.preventDefault() is not working.
Interesting, I just helped somebody with a similar issue, the syntax for Vue.2.0 is v-on:submit="send" not v-on="submit: send". Vue already has a way stop the form submitting which is: v-on:submit.prevent so you don't need the e.preventDefault, you would get:
<form v-on:submit="send" v-on:submit.prevent>
or a shorter version:
<form v-on:submit.prevent="send">
There are a few more issues here, so I will go through them for you:
Firstly, you are never submitting the form. To submit a form you need a submit input, not a button:
<input type="submit" value="Send" />
However, from what I can see it's likely you don't even need a form, and can simply use a button with v-on:click:
<div>
<input v-model="message">
<button v-on:click="send">Send</button>
</div>
And then get what was submitted from the view model:
send: function()
{
alert(this.message);
}
You should also use the console (under developer tools in your browser) and log any output rather than alert (console.log(this.message)), because it will also sniff out any general errors with your code - for example I can see that you also have a typo (the same one I always make) it's data not date:
data: {
message: ''
},
Okay, what about this
<form #submit.prevent="send">
<input v-model="message">
<button>Send</button>
</form>
And then you can remove preventing default browser action from your send() method

Form submission then send an xAPI statement

I am trying to send an xAPI statement after someone submits a their full name and email address through a form. In addition to sending the statement I would like to display a video.html page whereby they can watch a video. I know that there is an example of this on GitHub but I'm trying to do a much simpler example on my own. Can someone have a look at my attempt below and tell me why it is not working. Thanks very much.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="js/xapiwrapper.min.js"></script>
<script type="text/javascript">
var button = document.getElementById("theButton"),
fullName = button.form.fullNameID.value;
emailAddress = button.form.emailAddressID.value;
button.onclick = function() {
var stmt = new ADL.XAPIStatement(
new ADL.XAPIStatement.Agent(ADL.XAPIWrapper.hash('mailto:emailAddress'), 'fullName'),
new ADL.XAPIStatement.Verb('http://adlnet.gov/expapi/verbs/registered', 'registered'),
new ADL.XAPIStatement.Activity('act:http://ISO9000Video.html', 'Preparing for the ISO 9000 Audit',
'Preparation steps for the upcoming ISO 9000 audit.')
);
stmt.generateId();
stmt.addOtherContextActivity( new ADL.XAPIStatement.Activity('compId:internet_proficiency') );
stmt.generateRegistration();
ADL.XAPIWrapper.changeConfig({
'endpoint': 'https://lrs.adlnet.gov/xapi/',
'user': 'xapi-tools',
'password': 'xapi-tools',
});
ADL.XAPIWrapper.sendStatement(stmt);
var o = document.getElementById('output');
o.innerText = JSON.stringify(stmt, null, ' ');
}
</script>
</head>
<body>
<form id="frm1" action="">
Full Name: <input type="text" id="fullNameID" name="fullName"><br>
Email: <input type="text" id="emailAddressID" name="emailAddress"><br><br>
<input type="button" id="theButton" value="Submit">
</form>
<p>
<code><pre id='output'></pre></code>
</p>
</body>
</html>
Your script at the top of the page is being executed when the page loads, but the form element with the button hasn't been set as the property of the button yet because that part of the DOM hasn't been parsed. If you check the console in your browser you'll see an error such as:
Uncaught TypeError: Cannot read property 'form' of null
Move the <script> block that is currently in the <head> to the bottom of the <body> and it should work.

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

CodeIgniter Check if image existing with Jquery Ajax

I would like check the image whether existing on server file system and the file list was store into database. I want to make a ajax call to doing validation then return the result to screen with append effect. Here is my code, but don't work :( Please help me.
UPDATE: Code is workable, but it's not my expectation, because three thousand record with caused timeout and No append effect. thanks
Controller
public function getImageList()
{
$this->load->model('image_model');
$data['list'] = $this->image_model->get_image();
foreach ($data['list'] as $key){
$result[] = $this->imageValidation($key->filename);
}
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($result));
}
private function imageValidation($imgfile)
{
if(!file_exists(LOCAL_IMG_TEMP.$imgfile))
{
return "<pre>". $imgfile." Not Find"."</pre>";
}
}
View
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title></title>
</head>
<body>
<script>
function makeAjaxCall(){
$.ajax({
type: "POST",
url: "http://127.0.0.1:8888/index.php/ajax/getImageList",
cache: false,
dataType : "json",
success: function(data){
$("p").append(data);
}
});
}
</script>
</script>
<input type='button' id='PostBtn' value='Check Image' onclick='javascript:makeAjaxCall();' />
<p></p>
</body>
</html>
try to use file_exists()
check it

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