Im learning Jquery and AJAX on my own through online tutorials and by posting on SO when I gets stuck, so please keep in mind I am a novice should you be so kind to answer my question.
I have a form inside a modalbox. Ajax prevents it from closing/reloading and a message gets displayed after submission as you can see in image below:
My problem
Both the success and failure messages gets displayed. I would like to change this so that 1) Success message gets displayed on successfull submission or 2) failure message gets displayed on failed submission:
My Form
<div id="inline3" style="width:400px;display: none;">
<h3>Contact Us</h3>
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
<div>
JQUERY
$(function(){
$("#contact-form").submit(function(e){
e.preventDefault();
$form = $(this);
$.post(document.location.url, $(this).serialize(), function(data){
$feedback = $("<div>").html(data).find(".form-feedback").hide();
$form.prepend($feedback)[0].reset();
$feedback.fadeIn(1500)
})
});
})
If anyone can give me a bit of help or advise here it will be greatyly appreciated.
Thanks for reading
First thing I would do is change the backend so that instead of returning html it return json containing only the information you need (like whether the submission was a success or failure and any other messages, etc.).
Then the easiest fix that comes to my mind is to give each of your two feedback message divs unique id's:
<div id="form-feedback-success" class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div id="form-feedback-error" class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
Keep the class names so that you can use css to style the two in a similar manner.
Then in your javascript check for a success or failure flag. Based on the flag display one or the other div based on the id:
$.post(document.location.url, $(this).serialize(), function(data){
if(data.success) {
$('#form-feedback-success').fadeIn(1500);
}
else {
$('#form-feedback-error').fadeIn(1500);
}
});
You may need to make some tweeks(like deserialize the response from json to an object), but that is the gist of it.
Related
is there any know that?
I'm testing some javascript as follows
function mem_join_next() {
if (document.mem_join.email.value == "") {
alert("please input your email ID");
document.mem_join.email.focus();
return;
}
document.mem_join.submit();
}
<form name="mem_join" action="/join_step_3" method="post">
<div class="col-xs-12 id">
<p><span>EMAIL</span><span class="star">*</span>
</p>
<input name='email' class="email1" type="text" style="IME-MODE: disabled" size="11">#
<input class="email2" type="text">
<div class="email-check">email_check</div>
</div>
<div class="col-xs-6 next" align="right">
<a onClick="mem_join_next()" style="cursor:pointer">
<img src="/page_imgs/member_img/btn-next.jpg">
</a>
</div>
It's code what i want to run.
But when It is processing, the screen come out the 404 not found error.
even it is right route.
I think the post is not working
cause if i go straight way to single URL address(localhost/join_step_3) , the screen come out the /join_step_3 address screen.
but if i go From join_step_2 form next button TO join_step_3, It is 404 not found please hell me! GOD PROGRAMMERS!
If you directly typed the url and it worked means the page at localhost/join_step_3 worked using GET, because the browser url uses the GET Method.
So, it is quite possible that your localhost/join_step_3 doesn't support POST Method. Therefore, either add the post support on the page depending on the server-side scripting you use, or change method="post" to method="get" in your client html.
Im very new to Ajax and Jquery and learning through SO and online tutorials so please keep in mind im a rookie should you read and be kind enough to answer my post.
I have managed to create the following which is a form that displays a message on submit. If form was successfully submitted a message is displayed without page refreshing as you can see in image below:
FORM
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
<div>
JQUERY
$(function(){
$("#contact-form").submit(function(e){
e.preventDefault();
$form = $(this);
$.post(document.location.url, $(this).serialize(), function(data){
$feedback = $("<div>").html(data).find(".form-feedback").hide();
$form.prepend($feedback)[0].reset();
$feedback.fadeIn(1500)
})
});
})
What I want to do
Retrieve the value from text field message and assign it to php variable
My problem
When I try to retrieve the value of message with the following code, nothing happens:
PHP code below form
<?php
if(isset($_POST['contact'])){
$message = $_POST['msg'];
echo $message;
}
?>
Im very new to Ajax so I guess I am doing something wrong here, unfortunately I dont know where I am going wrong so I am hoping someone can put me on the right path here.
Thanks in advance
Hanoncs suggestion will work, but keeping things only browser side (by displaying the message only from form to div), will always give the user the impression that message is send (processed) server-side, while it is not always the case, one would make php return it before displaying it with javascript. So here is another approach I suggest:
First, Make a Separation of concerns: Sending a POST HTTP Request to the same current page contardicts somehow the purpose of AJAX. The HTTP Response will contain all the page ( the HTML rendred by PHP, the embeded HTML used for templating, and maybe the script if it is not joined in a script tag). Instead, I suggest you create a small separate php file that is responsible for rendereing only the needed markup. And so, instead of using $.post(document.location.url.., one would use $.post('pathToSmallPHPFile'..
Second, let jQuery AJAX functions accept callbacks or use promises. I suggest you carefully read the following link.
The issue is that you are using ajax, which does not cause a page refresh, and then trying to echo out the posted variable, since there is no page refresh, php will not process the page again to echo the posted variable.
My solution is to use javascript to display the text entered and then database it using php.
Here is an example,
$(document).ready(function () {
$(".button").click(function () {
$('p').text($('#msg').val());
});
});
http://jsfiddle.net/r4nanmof/ you dont need ajax if all you want to do is display it on the page. If you plan on saving in the database then ajax is required.
Jquery Code for posting the message value to the php file is given below:
$('#contact_btn').click(function(event){
event.preventDefault();
var url = "url/of/the/php/page/where/to/process/data";
var data = $("#msg_box").val();
var wrapper = $('#wrapper');
$.ajax({
type: "POST",
url: url,
data: data,
success: function(response){
wrapper.html("The reponse from the page is " + response);
},
error: function(xhr,status,msg){
//Handle error here
}
});
});
<code>
<div id="wrapper">
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" id="msg_box" value="" /><br />
<input type="submit" id="contact_btn" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
</div>
</code>
Message
Thank You We will Get Back to you
Ooops....Something Went Wrong
Its not necessary in your case but change method"post"> to method="post">
And change your Form
<form name="message-form" action="" id="contact-form" method="""post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none"> </div>
And use the following jQuery code to post your data
$(function () {
$("#contact-form").submit(function (e) {
e.preventDefault();
$form = $(this);
$.post(
document.location.url,
$(this).serialize(),
function (data) {
$(".form-feedback").html("Your msge " + data + " is recieved and we will get back soon");
$(".form-feedback").show();
})
});
});
Alright, after hours and hours of research and trying things I am completely stuck at the moment. I coded quite a lot for a web page so I'll try to summarize it as good as possible.
So I've got this ASP CLASSIC page where a user can create a ticket using a form.
The coded page consists out of 3 main parts:
Javascript client side error handling.
ASP CLASSIC server side error handling after submission (checking if
database values exists like email).
The form submitting (sending an email + inserting the data into the
database).
After the form is submitted there is some ASP error handling. When a error is encountered a Javascript popup box will be shown with the error and the data submission and email is being cancelled.
The form is auto filled with the inputted values (with asp code) so that after a error the inputted values are kept in the form. This all works.
The form code:
<div align="left"><form name="myForm" method="post" style="display:inline" onsubmit="return(validate());">
<div class="FormTitel">Voor welke afdeling is de ticket bestemd?
</div>
<div class="radio">
<input type="radio" class="radio" name="automatisering" value="Automatisering" checked <% if Request.Form("automatisering") = "Automatisering" then response.write("checked")%>>Automatisering
<input type="radio" class="radio" name="automatisering" value="Software" <% if Request.Form("automatisering") = "Software" then response.write("checked")%>>Software
<div id="Error1" style="display:none" color="white"></div>
</div>
<div class="FormTitel">Soort ticket
</div>
<div class="radio">
<input type="radio" class="radio" name="probleem" value="Probleem" <% if Request.Form("probleem") = "Probleem" then response.write("checked")%>>Probleem
<input type="radio" class="radio" name="probleem" value="Wijziging"<% if Request.Form("probleem") = "Wijziging" then response.write("checked")%>>Wijziging
<div id="Error2" style="display:none" color="white"></div>
</div>
<div class="FormTitel">Uw gegevens
</div>
<div>
<input type="text" name="Name" class="name" placeholder="Vul hier uw voor- en achternaam in" style="color:#888;"
onfocus="inputFocus(this)" onblur="inputBlur(this)" value="<%=Request.Form("Name")%>">
<div id="Error3" style="display:none" color="white"></div>
</div>
<div>
<input type="text" name="EMail" class="name" placeholder="Vul hier uw emailadres in" style="color:#888;"
onfocus="inputFocus(this)" onblur="inputBlur(this)" value="<%=Request.Form("EMail")%>"/>
<div id="Error4" style="display:none" color="white"></div>
</div>
<input type="submit" class="ticketVerstuur" value="Verstuur ticket" />
</form></div>
*The error id's are client side styling boxes that are being showed when a Validation returns false (with javascript).
*Sorry for not translating the title's, names, etc. but that would be quite some work;)
The ASP IF statements in the form make sure that the inputted values are returned and not lost when a error is being showed.
Alright now for the part where it goes wrong.
After submission, which is being activated by If Request.ServerVariables("REQUEST_METHOD") = "POST" Then some stuff is happening. Namely, the input values are being parameterized for sql injection, some input values are being checked on the server side, for example; does the submitted email exists in the database? and if the server side validation is all fine then the data is being inserted in the database and a email is being send.
The error messages on the server side are being shown to the user as javascript popup boxes. This works.
The javascript popup code:
function popup(popup,container) {
var thisPopup = this;
thisPopup.load = function() {
container.animate({
"opacity": "0.3"
},250, function() {
popup.fadeIn("250");
});
container.off("click").on("click", function() {
thisPopup.unload();
});
$('#closePop').off("click").on("click", function() {
thisPopup.unload();
});
}
thisPopup.unload = function() {
popup.fadeOut("250", function(){
container.animate({
"opacity": "1"
},250);
});
}
}
The function is called in the submit code like so: new popup($("#popup_box"),$("#container")).load(); The popup div is put above the form and the container is wrapped around the form. (popup works).
The problem though is that after the server side validation is all good, so the data goes into the database and the email is send, I popup a new javascript box saying that the everything was successful. When it is successful I want to clear my form (to avoid confusion).
First I try'd to do this with a response.redirect ("mypage.asp"). Though, when I use this the javascript popup box wont show.
Then I try'd to use a window.location.replace("http://stackoverflow.com"); on my close / unload function of the popup box, this has no effect though (data is not being cleared). Also try'd it with setting a var to true when the popup is unloaded and then later checking the var if it is set to true (then redirect) but this also doesn't work, even a direct javascript redirect, so without the popup, in the submission code (after all is successful) doesn't seem to work for some reason. In matter of fact only alert seems to work. Here the example of the adjusted popup unload:
thisPopup.unload = function() {
window.location.replace("http://stackoverflow.com");
popup.fadeOut("250", function(){
container.animate({
"opacity": "1"
},250);
});
}
So what causes this problem and how can I fix it? I can imagine it requires a bit more of my code so don't hesitate to ask for it, but the post is big enough as it is.
Last but not least a short summary of how my code is setup:
<html>
<head>
stylesheet
<title></title>
</head>
<body>
<javascript>
Pop up box code + validate form code
</javascript>
<form>
</form>
</body>
</html>
<asp server side code (on submit)>
Some functions (mail - anti injection) + request form values
Validation server side (with javascript poups)
Insert data in database
Sending mail
I think you were on the right track with the redirect. To get a pop-up to show after a redirect, do something like this:
response.redirect "mypage.asp?ShowSuccess=true"
Then in mypage.asp use this:
<%
if request("ShowSuccess") = "true" then
onload = "alert('Success message here!');"
end if
%>
<body onload="<%=onload%>">
I have have my angular app validating a sign-up form. On submit, the server also validates the data. I'm outputting error messages in angular using ng-messages.
Here is a shortened version of my form, which works perfectly so far.
<form name="signUpForm" novalidate data-ng-submit="attemptSignUp()">
<label for="firstName">First name</label>
<input type="email" name="email" id="email" required data-ng-model="data.user.email" />
<div class="error" data-ng-messages="signUpForm.email.$error" data-ng-show="signUpForm.$submitted" data-ng-cloak>
<p data-ng-message="required">Please provide your email</p>
</div>
</form>
The server verifies the email address is unique, and if not, returns a 422 error (from Laravel 5), with an array of errors.
[
'email' => 'This email is already in use'
]
I'd like to merge in this, and any other messages sent back from the server into their relevant ng-messages block. Any idea how I could accomplish it?
A simple solution is to have two arrays. One for client side and one for server side errors which is populated in your controller. You can hide the server side errors if client errors exists or opposit to avoid double messages.
The reason I choose to have two arrays instead of populating the forms array is that the JavaScript controller should not know or be dependent on the structure of the HTML. The HTML AngularJS template should be bound to the controller, not opposit.
<form name="signUpForm" novalidate data-ng-submit="attemptSignUp()">
<label for="email">E-mail
<input type="email" name="email" id="email" required data-ng-model="data.user.email" />
<div class="error" data-ng-messages="signUpForm.email.$error" data-ng-show="signUpForm.$submitted" data-ng-cloak>
<p data-ng-message="required">Please provide your email</p>
</div>
<div class="error" data-ng-messages="serverErrors" data-ng-show="signUpForm.$submitted" data-ng-cloak>
<p data-ng-message="emailexists">Email already exists</p>
</div>
</label
</form>
A note on the label: Users using screen-readers will not get your error messages read out loud to them if they are not wrapped inside the label.
Well, this is not the most elegant solution since you really should
leverage the asyncValidators in angular 1.3.x and then create your
custom validation directives.
Resources
http://plnkr.co/edit/s4jJAOqehBkFUC9osMsy?p=preview found in the post by this guy.
Possibly here http://odetocode.com/blogs/scott/archive/2014/10/16/working-with-validators-and-messages-in-angularjs.aspx
And of course in the docs
But be cautious as this is not in any way a complete example ready to be used. It's mostly here for demo purpose and to sort of give you an idea where to start. I have not bothered with clearing any previous errors, revalidating the form or taken into account other validation errors.
Awesomeness
Imagine your controller looks like this
$scope.serverValidations = {};
$scope.attemptSignUp = function(){
Api.validateEmail($scope.email).then(angular.noop, function(data){
$scope.serverValidations = data
for(prop in $scope.serverValidations){
if($scope.signUpForm[prop]){
angular.forEach($scope.serverValidations[prop],function(validation){
$scope.signUpForm[prop].$setValidity(validation.type, false);
});
}
}
});
}
and your response data containing validation errors look like this
{
email:[
{type:'unique', message:'This email is already in use'}
],
name:[
{type:'maxlength', message:'Your name is to long, get a new one :)'}
]
};
Then in your HTML you could do like this
<div class="error" data-ng-messages="signUpForm.name.$error" data-ng-cloak="">
<p data-ng-message="required">You don't have a name?</p>
<p ng-repeat="validation in serverValidations['name']" ng-message="{{validation.type}}">{{validation.message}}</p>
</div>
Here's a dirty Codepen for you: http://codepen.io/anon/pen/yyzMgG?editors=101
When you press submit, after 2 seconds (the time it takes to hit the fake server) your server validations are presented.
First of all you should set validity and error messages
$scope.formErrors = {};
angular.forEach(errors, function(data, name) {
if (!vm.register_form[name]) {
return;
}
$scope.formErrors[name] = data.message;
//this will set errors->server to invalid state
$scope.register_form[name].$setValidity('server', false);
});
The next step will be rendering by ng-messages
<div ng-messages="register_form.email.$error">
<div ng-message="required">Email is required</div>
<div ng-message="email">Invalid email</div>
<div ng-message="server">{{formErrors.email}}</div>
</div>
I had a similar question, but the solutions did not work for me. What I did, and it is/was a hack/work around, was to send different errorcodes, and set a case statement.
I am trying to submit without reloading using AJAX, but when I press the Submit Button and no records are insert, however it prints out that All records are Submitted. Any Idea
<?php echo validation_errors(); ?>
<?php echo form_open('', 'class="form-horizontal" id="myForm"'); ?>
<div class="form-group">
<label for="note_text" class="col-sm-1 control-label">Note</label>
<div class="col-sm-10">
<textarea class="form-control" name="note_text" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<button type="submit" class="btn btn-default">Post</button>
</div>
</div>
<div class="buttons"> <span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
</form>
<script>
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
$.ajax({
url:'',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000); //=== Show Success Message==
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});
});
</script>
Also can someone point me to a tutorial about how to do LIVE UPDATE. I mean this function for example is in index() where is also my loop for all the notes and what I am searching for is as soon as I submit it and immediately the new record of notes to be shown below. Something like Facebook posting
I think the issue is in your server side code, it's returning a HTTP 200 response so the $.ajax function thinks it succeeded but actually it didn't. This might happen if you're catching the error and outputting a message, but not throwing say a 500 error.
If you have google chrome press F12 to bring up developer tools > Go to network > Press submit and a new entry should appear in the list > click on that entry. Take note of the "Status Code" in the headers tab, and the output in the response tab.
If that doesn't return what you'd expect (ie. non-200 when the update fails and the correct response) then you should start debugging your server side code.