Form still submits on preventDefault - forms

I am using jQuery to submit form data to a file in the form's action. However, when I submit the form, the browser redirects to the action (comment.php). I don't know why this is because e.preventDefault() should stop the browser's redirection. Ideally, I would like the browser to not redirect and remain on the current page (index.php).
jQuery:
<script type='text/javascript'>
$('document').ready(function(){
$('.commentContainer').load('../writecomment.php');
$('.answerContainer').on('submit', 'form', function(e){
e.preventDefault();
var form = $(this).closest('form');
$.post($(form).attr('action'),
$(form).serialize(),
function() {
$('.commentContainer').load('../writecomment.php');
$('.commentBox').val('');
}
});
});
</script>
HTML Form:
<form method='POST' action='../comment.php'>
//form contents
</form>

I don't think your selector and on method is working correctly. Try: $('form').on('submit', function(e) { are you sure you have wrapped your form in a element with the class answerContainer??
and then just to be sure don't use $.post use $.ajax:
and this inside an on i the element eg. form not the first selector .answerContainer.
$('document').ready(function(){
$('.commentContainer').load('../writecomment.php');
$('.answerContainer').on('submit', 'form', function(event) {
event.preventDefault();
var $form = $(this);
$.ajax({
"url": $form.attr("action"),
"data": $form.serialize(),
"type": $form.attr("method"),
"response": function() {
$('.commentContainer').load('../writecomment.php');
$('.commentBox').val('');
}
});
});
});

Related

AngularJS ignores form submit

I'm using AngularJS v1.2.13 to create a page with a form which will download a user's file on click.
I'm using $sce to enable the injection of the file URL which works fine.
However, the loading of the resource disables the form submit. I'm sure it has to do with the resource load because when I remove the load and hardcode the url it works fine. I've also created a JSFiddle without it and have not been able to reproduce the problem there.
Any ideas on why this is happening and how it can be fixed?
HTML:
<div ng-controller="viewProfileController" data-ng-init="findOne();">
<form method="get" action="{{downloadFileURL}}">
<button type="submit" class="no-button comment-small" >
Download File
</button>
</form>
</div>
Controller:
'use strict';
angular.module('bop.viewProfile').controller('viewProfileController', [
'$scope', 'Users', '$sce', '$routeParams',
function($scope, Users, $sce, $routeParams) {
$scope.downloadFileURL = '';
// Find current user
$scope.findOne = function() {
Users.get({
userId: $routeParams.userId
}, function(user) {
$scope.user = user;
$scope.downloadFileURL = $sce.trustAsResourceUrl($scope.user.file.url);
});
};
}]);
Users Service:
var userServices = angular.module('bop.users', ['ngResource']);
userServices.factory('Users', ['$resource', function($resource) {
return $resource(
'users/:userId',
{ userId: '#_id' },
{ update: { method: 'PUT' } }
);
}]);

angularjs $resource : can't $save JSON

starting with angular, i am trying to GET data from the server and then POST back modifications with $resources.
It's working fine except the "save" function. No Data is POSTed back to the server.
here is the html
<div ng-controller="myCtrl">
<div ng-repeat="obj in objs">
<h2>{{obj.data_1}}</h2>
<h3>{{obj.data_2}}</h3>
<input type='text' ng-model="obj.data_1"><br/>
<textarea ng-model="obj.data_2" required></textarea><br/>
<button ng-click="save()">Save</button>
</div>
</div>
service.js
'use strict';
angular.module('App.services', ['ngResource']).
factory('Obj', function($resource){
return $resource('url/to/json');
});
controller.js:
'use strict';
angular.module('App.controllers', []).
controller('myCtrl', ['$scope', 'Obj', function($scope, Obj) {
$scope.objs = Obj.query();
$scope.save = function() {
$scope.objs.save();
}
}]);
Do you know why nothing is POSTed back when i save ?
Using the query method on the $resource object implies return as follows 'query': {method:'GET', isArray:true} it's mean that your $scope.objs is an array of objects and not an object and depending on number of elements you can use the folowing notation:
$scope.objs[i].save()
where i is the index of element in the array, forexample if you have return like:
[ {id:1, name:'Some name', age:35} ];
then your code : $scope.objs[0].save()
Edit:
I have created a plunk, maybe it will help you... http://plnkr.co/edit/62iPCAUNjV0oJROhul1G
Shouldn't there be another $resource declared for POST the way it is declared for GET? Each $resource specify particular REST service.
//services.js
'use strict';
angular.module('App.services', ['ngResource'])
.factory('GetObj', function($resource){
return $resource('url/to/json');
}
.factory('SaveObj', function($resource){
return $resource('url/to/post');
});
//controller.js
'use strict';
angular.module('App.controllers', []).
controller('myCtrl', ['$scope', 'GetObj', 'SaveObj', function($scope, GetObj, SaveObj) {
$scope.objs = Obj.query();
$scope.save = SaveObj.save(objs, function(resp) {
//Callback
console.log("Response from POST: %j", resp);
}
}]);

Tipsy tooltip script does not work with Ajax

I use Tipsy tooltip script on my website:
Script homepage and examples
See the script
It displays some information on mouseover. For example, I have a page with users photos (thumbnails) and onmouseover Tipsy displays user name and age.
<div id="up_gus" style="display:inline-block;">
<a href="/profile.php"><img class="west" title="username showed by Tipsy" src="/foto.jpg"/>
</a></div
It works fine, but now I added Ajax/Jquery to load more photos without page refresh.
<div id="more"><a class="l_more" id="<?php echo $pid;?>" href="#!" >Show more</a></div>
$('.l_more').live("click",function() {
var last_msg_id = $(this).attr("id");
if(last_msg_id!='end'){
$.ajax({
type: "POST",
url: "/mas.php",
data: "vid="+ last_msg_id,
beforeSend: function() {
$('a.l_more').append('<img src="../load.gif" />');
},
success: function(html){
$("div#more").remove();
$("div#up_gus").append(html);
}
});
}
return false;
});
If I load more results (photos) Tipsy onmouseover does not display anything. Any ideas whi it does not work with Ajax?

Customize google cloud print button function

Currently i am using the google cloudprint button for my site
<script src="//www.google.com/cloudprint/client/cpgadget.js"></script>
<script defer="defer">
var gadget = new cloudprint.Gadget();
gadget.setPrintButton(document.getElementById("custom_print_button"));
gadget.setPrintDocument("url", "Cloud Print test page",
"http://www.google.com/cloudprint/learn/");
</script>
I want to send an email when I hit the print button, is this possible?
No problem at all... just attach an onclick handler to the print button, or bind the click with jQuery and call a function to do your email. I used it to create a document with Ajax before it was printed:
<script>
function printIT() {
jQuery.ajax({
url: "print_this.php",
context: document.body,
success: function(responseText) {
alert("Document sent!");
return false;
}
});
}
</script>
<button id="print_button_container" class="ui-link" onclick="printIT();"></button>
<script src="//www.google.com/cloudprint/client/cpgadget.js">
</script>
<script defer="defer">
var gadget = new cloudprint.Gadget();
gadget.setPrintButton(document.getElementById("print_button_container"));
gadget.setPrintDocument("url", "My Document", "http://www.yourpath.com/yourdoc.html");
</script>
Simplified version... not tested but should work :)

Jquery, Validate, Submit Form to PHP (Ajax Problem)

Very early days playing Javascript, Jquery and Validate.
I am using the Submit Button onClick method for form submission.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using the submit, in case no data or not every field has been tested.
The logic is working, but the AJAX call does not appear to be working. I have stripped down the PHP to
<?php
touch('phpTouch.txt');
phpinfo();
sleep(30;)
?>
The javascript is
$(document).ready(function () {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form() ) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
$.ajax({
url: "testPHP.php",
type: "POST",
data: frmData,
dataType: "json",
success: function () {
alert("SUCCESS:");
},
error: function () {
alert("ERROR: ");
}
});
} else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
return false; // Prevent the default SUBMIT function occurring (is this a fact ??)
};
Can anyone advise as to what I am doing wrong.
Thanks
Do these things
Change onClick="submitForm()" on the HTML markup to onclick="submitForm(event)"
Now change the submitForm function like this.
function submitForm(evt) {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').valid() ) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
$.ajax({
url: "testPHP.php",
type: "POST",
data: frmData,
contentType: "application/json;",
success: function () {
alert("SUCCESS:");
},
error: function (a, b, c) {
alert(a.statusText);
}
});
} else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
evt.preventDefault();
};
Please note these things
Check .valid() to determine form validity
Call .preventDefault() instead of return false; ( Its more jQuery-ish )