Subscribe Form using Ajax - javascript

I'm really clueless as to how to get this done.
I need to make a subscribe with email button and it needs to be validated and show a little message for success, Loading ands Error.
I have never worked with Ajax before and this is what I have to do, I have To complete the newsletter subscribe ajax-functionality using a pre-defined controller in a php file on the server called newsletter.php and the I should use the controller function named subscribe in there to generate the response for the ajax request.
If that makes any sense please help me out.
This is my form for the email address
<div id="subscribeText">
<form action="" method="post" name="ContactForm" id="ContactForm" >
<input type="submit" name="subscribeButton" id="subscribeButton" value="Submit" />
<input type="text" name="subscribeBox" id="subscribeBox" value="Enter your email address..." size="28" maxlength="28" onFocus="this.value=''" />
</form>
</div>
http://jsfiddle.net/vaaljan/R694T/
This is what the success should look like and error and loading pretty much the same.
What the success message looks like
Hope this isn't too far fetched, I have not worked with java script that much yet but I understand more or less.
Thanks

I have made a small example on jsfiddle.
$('#send').click(function (e) {
e.preventDefault();
var emailval = $('input#email').val();
console.log(emailval);
if (emailval !== "") {
$.ajax({
cache: false, // no cache
url: '/echo/json/', // your url; on jsfiddle /echo/json/
type: 'POST', // request method
dataType: 'json', // the data type, here json. it's simple to use with php -> json_decode
data: {
email: emailval // here the email
},
success: function (data) {
console.log(data);
$('<strong />', {
text: 'Successfull subscribed!'
}).prependTo('#state');
},
error: function (e) {
$('<strong />', {
text: 'A error occured.'
}).prependTo('#state');
},
fail: function () {
$('<strong />', {
text: 'The request failed!'
}).prependTo('#state');
}
});
} else {
alert("Insert a email!");
}
});
Here it is.
It uses jQuery for the ajax request.
The example shows how ajax works.

Related

jQuery validation AJAX form

I'm trying to add validation to my ResetPassword function. validation its work fine, but I got another problem my ResetPassword function not going to work after I add validation.Can anyone direct me in the right direction? thx.
HTML code:
<div class="PopUpBG">
<div class="PopUp">
<h3 class="modal-title">
<span>Reset PAssword</span>
</h3>
<form id="form">
<input type="email" name="ResetEmail" id="ResetEmail" placeholder="Email Adresse" required/>
<input type="submit" class="btn btn-success" value="Send" onclick="ResetPassword(this)"/>
</form>
</div>
</div>
ResetPassword & validation code:
function ResetPassword(e) {
var email = $("#ResetEmail").val();
if ($("#form").validate()) {
return true;
} else {
return false;
}
$(".PopUp").html("We have sent mail to you");
$.ajax(
{
type: "POST",
url: "/Account/loginRequestResetPassword",
dataType: "json",
data: {
Email: email,
},
complete: function () {
console.log("send");
$(".PopUpBG").fadeOut();
}
})
}
The issue is because you're always exiting the function before you send the AJAX request due to your use of the return statement in both conditions of your if statement.
Change your logic to only exit the function if the validation fails:
function ResetPassword(e) {
if (!$("#form").validate())
return false;
$.ajax({
type: "POST",
url: "/Account/loginRequestResetPassword",
dataType: "json",
data: {
Email: $("#ResetEmail").val().trim(),
},
success: function() {
console.log("send");
$(".PopUp").html("We have sent mail to you");
setTimeout(function() {
$(".PopUpBG").fadeOut();
}, 10000); // fadeout the message after a few seconds
},
error: function() {
console.log('something went wrong - debug it!');
}
})
}
Also note that I amended the logic to only show the successful email message after the request completes. Your current code can show the 'email sent' message to the user, even though there is still scope for the function to fail.

Laravel - do not continue after form validator if ajax request

I want to create a ajax form validation that verifies that form data and gives user instant feedback before really submitting the form.
For this i added a javascript function on form submit:
<form id="x" onsubmit="return dosubmit(this)" action="{{ url('/x') }}" method="POST">
<script>
function dosubmit(form) {
$.ajax({
url: $(form).attr('action'),
type: 'post',
data: $(form).serializeArray()
}).done(function (data) {
form.submit();
}).fail(function (data) {
alert('error');
});
return false;
}
</script>
And i have custom a form validator request:
class X extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required',
];
}
}
When my ajax request fails everything works fine. My form validator returns the error in json and i can display it to user. The problem is that when it is successful it actually posts the data two times - first time from the ajax request and second time because i call form.submit() after ajax request is successful. Because i want to redirect the user after submit i would actually like only the second submit to reach the controller. This means i have to stop the ajax request after validation. My current workaround is that i have a line like this in my controller:
public function store(X $request)
{
if ($request->ajax()) {
return;
}
// only actual request reaches here
}
This works, but its not pretty. I don't like including this line in my controller. I would be happy if i could do something similar in my request validator, but I cant find a good way to return after validation from there. Any ideas how can i accomplish this?
You can try it like this:
<script>
function dosubmit(form) {
$.ajax({
async: false, // make ajax not async
url: $(form).attr('action'),
type: 'post',
data: $(form).serializeArray()
}).done(function (data) {
form.submit();
}).fail(function (data) {
alert('error');
});
return false;
}
</script>
and in controller just do it normally without this...
if ($request->ajax()) {
return;
}
And please give feedback if it works...I am also interested.
Your problem can be solved with some changed in javascript code. I think you're confused about what deferred.done() method will do. In your code, you're submitting your form twice.
Let me break down your js script, the done() method is used to do further actions after submitting your form (Please refer).
In your code, the first $.ajax actually submits your form to backend (here, if there are any errors from backend you can handle them in fail section). If the form submits successfully without any errors, then in done section you can define functions or actions about what you want to do after a successful form submission.
Instead of defining what to do after a successful form submission, you are resubmitting the same form again. So remove that part from js code and also the workaround you've done in your backend.
function dosubmit(form) {
$.ajax({
url: $(form).attr('action'),
type: 'post',
data: $(form).serializeArray()
}).done(function (data) {
// form.submit();
// handle successful form submission
}).fail(function (data) {
alert('error');
});
return false;
}

How to get jQuery to submit a form to a post

I have a form that I am validating with jQuery.
<form id="target" class="center-block" action="/" method="POST">
<textarea class="form-control" id="name" rows="3" name="name" placeholder="Enter a burger you would like to devour!"></textarea>
<button type="button" id="submit" class="center-block btn btn-default top">Submit</button>
</form>
After validation I am also trying to submit the form via jQuery.
if (validateForm() == true) {
$("#target").submit();
}
The validation is working however, it doesn't seem like the form is submitting to the post route. I was able to get the form to post using ajax, but the post wouldn't redirect after finishing. Was hoping this method would give the desired effect.
The app is running on Express and using MySQL.
I don't think your jquery submit will work ,because an element id or name submit will replace the form.submit method, you should simply change id (name also shouldn't give that).
<button type="button" id="changeThisId" class="center-block btn btn-default top">Submit</button>
Use Ajax and if you want to redirect to the current page, on success reload the current page
$.ajax({
url: yourUrl,
type: "post",
data: $("#target").serialize(),
success: function(r){
//form posted successfully
window.location.reload();
},
error: function(error){
alert(error);
}
});
I might have a typo in there, but the idea is:
$('#target').submit(function(event){
event.preventDefault();
}).validate({
rules: { ... },
submitHandler: function(form){
$.ajax{
type: 'POST',
data: $(form).serialize(),
url: '/',
success: function(result){
console.log(result);
}
error: function(err){
console.log(err.message);
}
}
});
});

Submit form using JS and AJAX

I have little problem with JS and AJAX, i dont know this languages. I know php and i have applied for position php developer, now i have some tasks to do and i stucked at one. It is simple task, form, submit, process information, store in DB, and send. Only problem is i have to use AJAX to submit form, i done little research and somehow i made wrote this code but it doesnt work.
<div>
<form method="POST" action="add.php" id="form">
<input type="email" name="email" id="email" value="Email">
<textarea name="content" id ="content">Message</textarea>
<input type="submit" value="Submit" id="submit">
</form>
Send messages from database
</div>
<script>
$(document).ready(function() {
// When click on button store values from form fields into variables
$("form").submit(function(event) {
event.preventDefault();
var email = $("#email").val();
var content = $("#content").val();
// Check if fields are empty
if (email=="" || content="") {
alert("Please fill all fields");
}
// AJAX code to submit form
else {
$.ajax ({
type: "POST",
url: ("#form").attr('action');
data: { "email": email, "content": content},
cache: false,
success: function() {
alert("Data successfully forwarded to add.php");
}
});
}
return false;
});
});
</script>
</body>
IN form can i use input type button instead of submit (so no need for preventDefault in JS) and in JS i do it
$("#submit").click(function.....
I think i have tried all combinations and when form is submited it goes with default, no JS activated...
SOLVED: problem was in IF statment, content="" instead of content=="", OMG how i overlooked that...
To answer your questions, yes you are right, you can use an input of type button and you don't necessary need to depend on submitting the form. Here is how you'd write it without form submission:
<div>
<form method="POST" action="add.php" id="form">
<input type="email" name="email" id="email" value="Email">
<textarea name="content" id ="content">Message</textarea>
<input type="button" value="Submit" id="submit" onclick="SendAjax();">
</form>
Send messages from database
</div>
<script>
// When click on button store values from form fields into variables
function SendAjax() {
var email = $("#email").val();
var content = $("#content").val();
// Check if fields are empty
if (email=="" || content=="") {
alert("Please fill all fields");
}
// AJAX code to submit form
else {
$.ajax ({
type: "POST",
url: "type your URL here",
data: { "email": email, "content": content},
cache: false,
success: function() {
alert("Data successfully forwarded to add.php");
}
});
}
}
</script>
As you can see, I prefer to specify the URL in AJAX instead of taking it from the form's action which I sometimes have it set to a different URL from the AJAX. However, if you want to take the URL from the form's action, then fix that line in your code to be:
url: $("#form").attr('action'),
Use the serialize() method (described bellow) instead of manually getting the value of each field of your form in order to build the JSON object.
$('#form').submit(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function() {
alert("Data successfully forwarded to add.php");
}
});
return false;
});
You have a syntax error in your ajax call.
$.ajax ({
type: "POST",
url: ("#form").attr('action'); // This is bad JSON
data: { "email": email, "content": content},
cache: false,
success: function() {
alert("Data successfully forwarded to add.php");
}
});
Replace that line with:
url: $("#form").attr('action'),

how to prevent redirect on form submit

i am getting a form with user parameters when i make an AJAX call to a page which later on is submiited to a url so that i can create a session for the same user in advance and when
that person goes to that site he sees his name there.
i created one div tag with id "abc_session", assign that form (whose id is fm1) to it,and submitted the form.
now as per the requirement session is created but page automatically gets redirected to that site url to which form is submitted.i just don't wan't that to happen.
can anyone please suggest something..or some workaround
the form that AJAX returns looks something like this:
<html>
<body onload="document.fm1.submit();return false">
<form name = "fm1" method="post" action = "https://abcd.com/abc ">
<input type=hidden name ="name" value="xyz">
<input type=hidden name ="login_parameters" value="CDF5D71C5BDB942EE2FB6C285B8DEBFE4C5675137B615CD2276571813AAC872AC8942E26B71026414BED1FEA09427D0B20A50FE2F70032D2E5B382598EC3C71D73EAB4ECBF7273A73BEB98ACEA4A0B775E7772BDC7C6746C355">
</form></body>
</html>
and the script goes like this
$(document).ready(function() {
function callwebsite()
{
$.ajax({
url: "/NASApp/benemain/website",
data: {},
type:"POST",
dataType: 'text',
cache: false,
success: function (data) {
alert("Call made to website.. ");
console.log(data);
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit();
},
error : function(response){
console.log('ERROR');
},
statusCode : {
500 : function() {
console.log('500 error');
window.location.reload(true);
},
401 : function() {
console.log('401 error');
window.location.reload(true);
},
404 : function(){
console.log('400 error');
}
}
});
}
callwebsite();
tried extracting the data and maiking another ajax call as suggested by quentin but getting this error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource.This can be fixed by moving the resource to the same domain or enabling CORS."
$.ajax({
url: lcAction,
data: {partner_id:lcPartner,login_parameters:lcLP },
type:"POST",
headers:{'Access-Control-Allow-Origin': '*'},
dataType: 'text',
//crossDomain: true,
//cache: false,
success: function(data)
{
alert("success");
},
error:function(response)
{
//alert("error");
console.log(response);
}
});
You are submitting the form:
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit(); // Here
Don't do that.
Extract the data from it and make another Ajax request.
You should use e.preventDefault() as soon as you submit the form.

Categories

Resources