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

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 )

Related

How to redirect to url within same context

I have /logout action, that should redirect to /login. /login renders template, where I read flash message from context. This works, but url in browser is still remains "/logout":
router.get("/logout").handler((ctx) => {
if (ctx.user()!=null) {
ctx.clearUser()
//flash message
ctx.put("msg", "Logout succeed")
}
ctx.reroute("/login")
})
What I want, but url should be "/login":
Better to use(?):
ctx.response.putHeader("location", "/login").setStatusCode(302).end()
But there is different context. So I haven't flash message.
How to redirect to /login within same context?
Upd.
Question related to this issue
In order to work with flash messages you should add a cookie to the redirect with the content:
// this makes the message available to the client
ctx
.addCookie(Cookie.cookie("flashMessage", "Logout succeed"));
// configure where to redirect
ctx.response()
.putHeader("location", "/login");
// perform the redirect
ctx.end(302);
Then on the client side you need a bit of JavaScript to read the message and
perform the display as you wish. Since there is no simple way to read cookies on the browser if you're using jQuery with the cookie plugin you can do something like:
$.fn.flashMessage = function (options) {
var target = this;
options = $.extend({}, options, { timeout: 3000 });
if (!options.message) {
options.message = getFlashMessageFromCookie();
deleteFlashMessageCookie();
}
if (options.message) {
if (typeof options.message === "string") {
target.html("<span>" + options.message + "</span>");
} else {
target.empty().append(options.message);
}
}
if (target.children().length === 0) return;
target.fadeIn().one("click", function () {
$(this).fadeOut();
});
if (options.timeout > 0) {
setTimeout(function () { target.fadeOut(); }, options.timeout);
}
return this;
function getFlashMessageFromCookie() {
return $.cookie("FlashMessage");
}
function deleteFlashMessageCookie() {
$.cookie("FlashMessage", null, { path: '/' });
}
};
And add a placeholder in your HTML like:
<div id="flash-message"></div>
And trigger it like:
$(function() {
$("#flash-message").flashMessage();
});

Form - new page on submit button

Last year i build a form for one of our costumers, when visitors submitted the form they
got a message on the same page. But now he asks me if it is possible to
make a succes page if the form is filled in correctly.
I can't make it work. It's a bit out of my league.
So i hope anyone of you can help me out!
$(document).ready(function() {
$("#ajax-contact-form").submit(function() {
$('#load').append('<center><img src="ajax-loader.gif" alt="Currently Loading" id="loading" /></center>');
var fem = $(this).serialize(),
note = $('#note');
$.ajax({
type: "POST",
url: "contact/contact2.php",
data: fem,
success: function(msg) {
if ( note.height() ) {
note.slideUp(500, function() { $(this).hide(); });
}
else note.hide();
$('#loading').fadeOut(300, function() {
$(this).remove();
// Message Sent? Show the 'Thank You' message and hide the form
result = (msg === 'OK') ? '<div class="success">Uw bericht is verzonden, we nemen z.s.m. contact met u op!</div>' : msg;
var i = setInterval(function() {
if ( !note.is(':visible') ) {
note.html(result).slideDown(500);
clearInterval(i);
}
}, 40);
}); // end loading image fadeOut
}
});
return false;
});
<form id="ajax-contact-form" target="_blank" method="post" action="javascript:alert('success!');" >
Instead of displaying the "success" message, redirect to a new page:
window.location = successPageUrl;
Just redirect to success page after ajax success.

Two near-identical forms functioning differently

I have two nearly identical forms on two different pages which take in a user's name and email address. When I press the submit button, both of them call a validator, which works correctly, and then both are supposed to make an Ajax call and display the results. At this point, one of them makes the call successfully, and the other simply refreshes the page. I'm not sure what the difference is that causes one to work successfully and the other to fail. With the one that works, I already had this problem once with the form that works, which was caused by me generating the form through javascript. I have no idea what is causing it now. Here is the inline code for the functioning one:
<!--// MODAL: INVITE //-->
<div id="inviteModal" class="modal" style="display: none">
<div class="response"></div>
<form id="inviteForm" >
<script type="text/javascript" src="/includes/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var invites = <?php echo $user->getInvitesLeft(); ?>;
</script>
</form>
</div>
Response is where it displays the response from the Ajax call. I have to generate the content later on using Javascript because I take different actions depending on the value of invites. I was originally generating the whole thing, but I found that I had to have the form tags in place to prevent the refreshing problem the first time. Here is the code that generates the form the user sees:
if(invites < 1){
$("#inviteModal").html("You have no invites left. You can get more by increasing your score.");
}
else{
$("#inviteForm").html("<h2>Please enter the specified information for the friend you wish to invite. </h2>"+
"<p>First: <input type=\"text\" name=\"first\"></p>"+
"<p>Last: <input type=\"text\" name=\"last\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>");
}
$("#inviteModal").css('display', "block");
$("#overlay").css("display", "block");
And here is the validator function:
$("#inviteForm").validate({
//Rules for invite validation
rules: {
first: "required",
email: {
required: true,
email: true
}
},
//Messages to print if validation fails
messages: {
first: "Please provide your friend's name.",
email: "We cannot contact your friend without a valid email address.",
},
//What to do when validation succeeds
submitHandler: function(form) {
//Form is valid, make Ajax call
$.ajax({
type: "POST",
url: '/invite/process',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
//alert(data);
if(data.indexOf("Thank you") >= 0 ){
$("#inviteModal .response").text(data);
invites -=1;
}
else{
$("#inviteModal .response").text(data);
}
}
}); //End ajax
} //End submitHandler
}); //End validator
As I said, this one works perfectly fine. The only difference between this one and the one that refreshes is that the non-functioning one is on a page that you don't have to be logged in to see, and takes different actions depending on whether or not a user is logged in. Here is the inline code:
<!--// MODAL: INVITE //-->
<div id="inviteModal" class="modal" style="display: none">
<div class="response"></div>
<form id="inviteForm" >
<script type="text/javascript" src="/includes/js/jquery-1.7.2.min.js"></script>
<?php
if(!$user || $user == null){ //No user logged in, display invite request form instead
$loggedin = false;
}
else{ //Allow user to invite friends
$loggedin = true;
}
?>
</form>
Here is the generation code, almost identical except for one extra if layer:
if(!loggedin){
$("#inviteForm").html("<h2>Please enter the specified information to request an invitation. </h2>"+
"<p>First: <input type=\"text\" name=\"first\"></p>"+
"<p>Last: <input type=\"text\" name=\"last\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>");
}
else{
invites = <?php echo $user->getInvitesLeft(); ?>;
if(invites < 1){
$("#inviteModal").html("You have no invites left. You can get more by increasing your score.");
}
else{
$("#inviteForm").html("<h2>Please enter the specified information for the friend you wish to invite. </h2>"+
"<p>First: <input type=\"text\" name=\"first\"></p>"+
"<p>Last: <input type=\"text\" name=\"last\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>");
}
}
$("#inviteModal").css('display', "block");
$("#overlay").css("display", "block");
And here is the validator:
$("#inviteForm").validate({
//Rules for invite validation
rules: {
first: "required",
email: {
required: true,
email: true
}
},
//Messages to print if validation fails
messages: {
first: "Please provide your friend's name.",
email: "We cannot contact your friend without a valid email address.",
},
//What to do when validation succeeds
submitHandler: function(form) {
//Form is valid, make Ajax call
if(loggedIn){ //They are inviting a friend
$.ajax({
type: "POST",
url: '/invite/process',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
//alert(data);
if(data.indexOf("Thank you") >= 0 ){
$("#inviteModal .response").text(data);
invites -=1;
//$("#overlay").css("display", "none");
//$("#inviteModal").fadeOut(5000);
}
else{
$("#inviteModal .response").text(data);
}
return false;
}
}); //End Ajax
}
else{ //They are requesting an invite for theirself
$.ajax({
type: "POST",
url: '/invite/request',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
//alert(data);
$("#inviteModal .response").text(data);
return false;
}
}); //End ajax
}
return false;
} //End submitHandler
}); //End validate
Again almost identical except for one extra layer of if. So why would the bottom one refresh the page instead of making the Ajax call while the first one works perfectly fine?
how about commenting out those return false statement in the ajax success callback functions for the second one?

JSON object parsing error using jQuery Form Plugin

Environment: JQuery Form Plugin, jQuery 1.7.1, Zend Framework 1.11.11.
Cannot figure out why jQuery won't parse my json object if I specify an url other than a php file.
The form is as follows:
<form id="imageform" enctype="multipart/form-data">
Upload your image <input type="file" name="photoimg" id="photoimg" />
<input type="submit" id ="button" value="Send" />
</form>
The javascript triggering the ajax request is:
<script type="text/javascript" >
$(document).ready(function() {
var options = {
type: "POST",
url: "<?php $this->baseURL();?>/contact/upload",
dataType: 'json',
success: function(result) {
console.log(result);
},
error: function(ob,errStr) {
console.log(ob);
alert('There was an error processing your request. Please try again. '+errStr);
}
};
$("#imageform").ajaxForm(options);
});
</script>
The code in my zend controller is:
class ContactController extends BaseController {
public function init() {
/* Initialize action controller here */
}
public function indexAction() {
}
public function uploadAction() {
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = $_FILES['photoimg']['tmp_name'];
$im = new imagick($image);
$im->pingImage($image);
$im->readImage($image);
$im->thumbnailImage(75, null);
$im->writeImage('userImages/test/test_thumb.jpg');
$im->destroy();
echo json_encode(array("status" => "success", "message" => "posted successfully"));
}
else
echo json_encode(array("status" => "fail", "message" => "not posted successfully"));
}
}
When I create an upload.php file with the above code, and modify the url from the ajax request to
url: "upload.php",
i don't run into that parsing error, and the json object is properly returned. Any help to figure out what I'm doing wrong would be greatly appreciated! Thanks.
You need either to disable layouts, or using an action helper such as ContextSwitch or AjaxContext (even better).
First option:
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
And for the second option, using AjaxContext, you should add in your _init() method:
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('upload', 'json')
->initContext();
This will disable automatically disable layouts and send a json header response.
So, instead of your two json_encode lines, you should write:
$this->status = "success";
$this->message = "posted successfully";
and
$this->status = "fail";
$this->message = "not posted successfully";
In order to set what to send back to the client, you simply have to assign whatever content you want into view variables, and these variables will be automatically convert to json (through Zend_Json).
Also, in order to tell your controller which action should be triggered, you need to add /format/json at the end of your URL in your jQuery script as follow:
url: "<?php $this->baseURL();?>/contact/upload/format/json",
More information about AjaxContext in the manual.
Is the Content-type header being properly set as "application/json" when returning your JSON?

Form still submits on preventDefault

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('');
}
});
});
});