I have an ASP.NET MVC project and currently I am using ViewData["ResultMessage"] to show the result of a form (which is done after the user submits & refreshes the page).
I want to do it right after he clicks submit (without refreshing the page). So I have to use Javascript for that, which I am new with. No experience what so ever.
How my form looks like is this:
<form id="contactForm" method="post" action="..">
<div class="field half first">
<label for="Name">Name</label>
<input type="text" name="Name" id="Name" placeholder="Your name" required />
</div>
<div class="field half">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" placeholder="Your email" required />
</div>
<div class="field">
<label for="Message">Message</label>
<textarea name="Message" id="Message" rows="5" placeholder="Your message" required minlength="20"></textarea>
</div>
<input type="submit" value="Send Message" />
<p>#ViewData["ContactActionResult"]</p>
</form>
You can see the result is displayed with Razor using ViewData. Now I want to do it without refreshing the page and learn JS on the way.
What I have tried so far:
$(function () {
$("button").click(function (e) {
e.preventDefault()
$.ajax({
type: "POST",
url: "/Receiver",
data: car,
datatype: "html",
success: function (data) {
alert("Congratulations, it worked!");
$('#contactForm').html(data);
},
error: function(data) {
alert("Failed.");
}
});
});
});
But I am not sure if I did something wrong or simply not implementing it right. I have the above function inside <script> here </script> in my HTML page. Nothing happens when I click the submit button on the form.
If it is an ajax call, It is best if you return a JSON response . You can use the Request.IsAjaxRequest() to determine whether the request is normal form request or ajax call.
You should also consider using to the PRG pattern. After successfully saving, you should do a redirect to a GET action where you can render a view, instead of returning to the same view with a viewbag message. If you want to pass some message to the new view/action, use TempData instead of ViewData.
[HttpPost]
public ActionResult Receiver(string name, string Email)
{
// Your existing code to save
if(Request.IsAjaxRequest())
{
return Json(new { status = "success", message = "Created successfully" });
}
// Normal form submit. So let's follow PRG pattern
TempData["ResultMessage"] = "Created successfully";
return RedirectToAction("Index");
}
You can also put a try/catch and return a json like this for error usecase
return Json(new { status = "error", message = "some serious error" });
In Index action/view, you can read TempData["ResultMessage"] and display to user.
Now, for the ajax usecase, in your current view, you can add a div to show the message
<form id="contactForm" method="post" asp-action="Receiver">
<div id="msg"></div>
<div class="field half first">
<label for="Name">Name</label>
<input type="text" name="Name" id="Name" placeholder="Your name" required />
</div>
<div class="field half">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" required />
</div>
<div class="field">
<label for="Message">Message</label>
<textarea name="Message" id="Message" rows="5"
placeholder="Your message" required minlength="20"></textarea>
</div>
<input type="submit" value="Send Message" />
</form>
and now in your ajax call's success callback, check the json response coming back from server and show the message property as needed. If you are putting the script inside the razor view file, make sure you are putting it inside a Scripts section so that it will be evaluated in the proper order (After jQuery is loaded, assuming you load jQuery before calling RenderSection("scripts") inside the layout)
#section Scripts
{
<script>
$(function (){
$("#contactForm").submit(function (e){
e.preventDefault()
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: car,
success: function (data){
if (data.status === "success")
{
$('#msg').html(message);
}
//to do : handle statuss=="error" as needed
},
error: function (data)
{
alert("Failed.");
}
});
});
});
</script>
}
For asp.net core, you can write a IsAjaxRequest method in your base controller and use that. jQuery will add X-Requested-With header with value XMLHttpRequest for your ajax calls.
protected bool IsAjaxRequest()
{
return Request.Headers["X-Requested-With"] == "XMLHttpRequest";
}
Related
I have a headless WordPress site. I'm working on the event handler to submit the contact form. I'm using Contact Form 7. I've tried using vanilla JS, I'm using jQuery here because it seems like a better option, and I'm losing my mind.
Essentially, the form submits but the fields do not clear. I've tried form.reset() in JS, $('#formid')[0].reset() in jQuery, and the code below. I don't know why this isn't working and the result is really suboptimal. Any ideas?
I will fully admit that I am more comfortable working in javascript than jQuery so I might be missing something obvious.
If I don't have the iframe set as the form target, the page redirects to a white page with JSON data. Am I missing something about event.preventDefault()? It's not working the way it should, and has in my experience.
$(document).ready(function() {
$('#formElem').on('submit', function(event) {
event.preventDefault();
let request = $.ajax({
url: "https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback",
type: "post",
data: new FormData(this)
}).done(resetForm());
})
function resetForm($form) {
$form.find('input:text, input:tel, input:file, select, textarea').val('');
$('datePicker').val('').attr('type', 'text').attr('type', 'date');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback" id="formElem" name="contactForm" method="post" class="contact__form" target="formtarget">
<h3 class="contact__form--heading">Contact</h3>
<p class="contact__form--paragraph">Currently operating out of Minot, North Dakota. Soon to be in South Korea!</p>
<input id="your-name" class="contact__form--input" type="text" name="your-name" placeholder="Name">
<input id="your-email" class="contact__form--input" type="text" name="your-email" placeholder="Email">
<input id="your-tel" class="contact__form--input" type="tel" name="your-tel" placeholder="Phone">
<input id="preferred-date" class="contact__form--input" placeholder="Select session date" type="date" name="preferred-date">
<textarea id="your-info" class="contact__form--input" placeholder="Tell me about yourself!" name="your-info"></textarea>
<textarea id="services" class="contact__form--input" placeholder="What services are you interested in booking?"></textarea>
<textarea id="how-heard" class="contact__form--input" placeholder="How did you hear about my business?" name="how-heard"></textarea>
<input id="btnSubmit" class="contact__form--input btn-contact" type="submit" name="submit">
<div id="messageArea"></div>
<iframe class="formtarget" name="formtarget"></iframe>
</form>
There's several separate issues:
.done(resetForm()) is incorrect as it immediately calls resetForm() and sets the returned value from that call as the event handler.
You need to send the $form argument in the resetForm() method call, so provide a full function block to the done() handler, including that argument
When sending a FormData object in a jQuery AJAX call you need to set processData and contentType to false so the data is encoded correctly.
jQuery does not have :tel and :file pseudo selectors. Instead you can use :input to select all input, textarea and select elements to reset their values.
Changing the type of the date control to text and then back to date is not necessary, even without the above point.
$(document).ready(function() {
const $form = $('#formElem').on('submit', function(e) {
e.preventDefault();
let data = new FormData(this);
let request = $.ajax({
url: "https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback",
type: "post",
data: data,
contentType: false,
processData: false
}).done(function() {
resetForm($form)
});
})
function resetForm($form) {
$form.find(':input').val('');
// alternatively to reset the form to original state, not wipe all fields use this
// $form.get(0).reset();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback" id="formElem" name="contactForm" method="post" class="contact__form" target="formtarget">
<h3 class="contact__form--heading">Contact</h3>
<p class="contact__form--paragraph">Currently operating out of Minot, North Dakota. Soon to be in South Korea!</p>
<input id="your-name" class="contact__form--input" type="text" name="your-name" placeholder="Name">
<input id="your-email" class="contact__form--input" type="text" name="your-email" placeholder="Email">
<input id="your-tel" class="contact__form--input" type="tel" name="your-tel" placeholder="Phone">
<input id="preferred-date" class="contact__form--input" placeholder="Select session date" type="date" name="preferred-date">
<textarea id="your-info" class="contact__form--input" placeholder="Tell me about yourself!" name="your-info"></textarea>
<textarea id="services" class="contact__form--input" placeholder="What services are you interested in booking?"></textarea>
<textarea id="how-heard" class="contact__form--input" placeholder="How did you hear about my business?" name="how-heard"></textarea>
<input id="btnSubmit" class="contact__form--input btn-contact" type="submit" name="submit">
<div id="messageArea"></div>
<iframe class="formtarget" name="formtarget"></iframe>
</form>
In your code you are calling resetForm and assigning what it returns to the done event handler. It is not calling that function when done is called.
You also are not passing the form reference to the function. So you will have an error message in your console.
$(document).ready(function() {
$('#formElem').on('submit', function(event) {
var form = this;
event.preventDefault();
let request = $.ajax({
url: "https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback",
type: "post",
data: new FormData(form)
}).done(function () { resetForm(form); });
})
function resetForm($form) {
$form.find('input:text, input:tel, input:file, select, textarea').val('');
$('datePicker').val('').attr('type', 'text').attr('type', 'date');
}
});
I have a very simple form that has an input field for first name. I captured the form data and transmitted it via ajax to a PHP page using the standard jQuery posting method. However, I am not able at all get any responses from the PHP page that any data was captured on the server-side. I am not sure what I have done wrong or what is missing.
Here is my code.
Form:
<form action="process.php" method="POST">
<div class="form-group">
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
<div class="d-none" id="firstName_feedback">
<p>Please enter a first name.</p>
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
Here is my Jquery Ajax call:
<script>
$(document).ready(function() {
$('form').submit(function(event) {
var formData = $("form").serialize();
console.log(formData);
$.ajax({
type: 'POST',
url: 'form.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
And here is my PHP page:
if(isset($_POST['formData']))
$ajaxData = ($_POST['formData']);
echo $ajaxData;
{
}
In your Ajax function, you're passing the contents of formData to the server, though not as formData but as their original input name.
In this case, you have:
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
The input's name is firstName, so you need to call $_POST['firstName'] instead of $_POST['formData'].
if (isset($_POST['firstName'])) {
$ajaxData = $_POST['firstName'];
echo $ajaxData;
}
The same applies for any other field you would have in your form, so for example, having another input with the name lastName means you'd have to call $_POST['lastName'] to access it.
There were also some misplaced brackets and parentheses in the PHP code which I accommodated above.
I am trying to have my all my text/email input forms have a required attribute before you can "Submit" The email
But since I am using some Ajax to keep the page from refreshing after pressing the button the required attribute will not work.
This is why I am asking for an alternative for required with Javascript or jQuery (trying to prevent email form spam).
HTML (FORM)
<form id="contact">
<div class="form-group">
<label for="name">Voornaam*</label>
<input name="fn" type="text" class="form-control" id="fn" required>
</div>
<div class="form-group">
<label for="name">Achternaam*</label>
<input name="ln" type="text" class="form-control" id="ln" required>
</div>
<div class="form-group">
<label for="email">Email-address*</label>
<input name="email" type="email" class="form-control" id="email" required>
</div>
<div class="form-group">
<label for="message">Bericht*</label>
<textarea name="message" required class="form-control" id="message" rows="6"></textarea>
</div>
<button type="button" onClick="doIets(); this.form.reset();"
name="submit" id="submit" class="btn btn-primary">Verstuur <span id="result"></span></button>
<div id="result2"></div>
</form>
Ajax script
<script type="text/javascript">
function doIets()
{
console.log("doe iets");
var data = {
ck: (new Date()).getTime(),
fn: $("#fn").val(),
ln: $("#ln").val(),
email: $("#email").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "sendmail.php",/*php file path*/
data: data,
beforeSend: function(){
$('#result').html('<img src="loader" style="height:10px;"/>')
},
success: function(data){
$('#result').hide();
$('#result2').html(data);
}
});
}
</script>
You will need to use e.preventDefault() when they click on the submit button and then validate the form and after that submit it using the ajax call you created above.
since you already read out the data, you can check whether your message is long enough for you via
data.message.length
if it is 0 (or lower than a threshold you defined), you can skip the ajax call and return some info to the user.
You might also want to trim the message first in order to be sure there aren't only whitespace in there.
Here is part from my code, where I bind the submit event to my form and check by looping if any required field is empty or if I want to do any such thing.
This way may help you--
$('.form .contact-form').submit(function(e) {
e.preventDefault();
$('.form .message').eq(0).html("<i>Sending... Please Wait...</i>");
var form = $(this);
var validated = true;
$('input[type="text"]',this).each(function(){
if($(this).val().length < 1){
$(this).addClass('error').focus();
validated = false;
return false;
}
});
if(validated === true){
$.post(__asyn.ajaxurl, $('.form form').eq(0).serialize(), function(data, textStatus, xhr) {
console.log(data);
});
}
});
Just pass the event object to your handler onClick="doIets(event);
and then add
function doIets(event) {
event.preventDefault();
...
}
I am working as junior web master maybe that's why I have come with a simple question here. I have designed a single page application for client which has contact form at the end of page, validation is done using bootstrap but to send form data to mail id only method I know is using php with action directing different page. since my website is single page application i would like a popup on successful submission to mail id
Below is the HTML code for the contact form
<form class="form-inline" data-toggle="validator" role="form" method="post" id="enquiry" action="index.php">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">Name</label>
<input type="text" class="form-control" name="name" id="exampleInputEmail3" placeholder="Name" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Mobile Number</label>
<input type="text" class="form-control" id="exampleInputPassword3" name="mobile" placeholder="Mobile Number" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Email Id</label>
<input type="email" class="form-control col-lg-12" id="exampleInputPassword3" name="email" placeholder="Email Id" required>
</div>
<br/> <br/>
<div class=" col-lg-12 form-group">
<textarea cols="80" placeholder="Enter query Here" class="form-control" name="query" id="address" data-error ="Please Enter Your Query" required></textarea><br/><br/>
</div>
<button style="background-color:#f15a24; color:#FFF;" name="submit" id="submit" type="submit">Submit</button>
</form>
Can use php to send form data and still get a pop up in same page?
Or do I need to use jquery to send data and pop-up?
It would be great if somebody helps me out with code, thanks in advance
Updated
below(index.php page) i have added the code what you have given,
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.easing.min.js"></script>
<script src="js/jquery.fittext.js"></script>
<script src="js/wow.min.js"></script>
<script src="js/creative.js"></script>
<script src="js/validator.js"></script>
<script>
$(document).ready(function(){
$("#enquiry").on("submit",function(e){
e.preventDefault();
var dataString = $('#enquiry').serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(ret) {
if(ret === "Success"){ alert("Success"); }else{ alert("Failed"); }
//Failure message if ret is false
});
}
});
});
</script>
Add this js to your script
<script>
$(document).ready(function(){
$("#enquiry").on("submit",function(e){
e.preventDefault();
var dataString = $('#enquiry').serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(ret) {
if(ret === "Success")
{
alert("Success");
} else {
alert("Failed");
}
}
});
}
);
});
submit.php contains the code to send and exit it with the success (true) or failure (false) message. That will be caught in ret variable.
Edited
This will be more detailed answer I was looking for, I thought it be would be helpful for somebody so I have answered my own question as an alternative solution, check out the links below.
Show submitted form response on the same page. (No Reload)
http://www.9lessons.info/2009/04/submit-form-jquery-and-ajax.html
I'm working on phonegap, basically its like making mobileapps crossplatform by using HTML, JS and CSS. On the device i currently have the JS and the HTML (form) in same document.
What I'm trying to do is to pass email and password to my server, and then process it there through a login. I've tested the login script on the server and it works with hardcoded data. So I'm guessing somewhere when sending the data from the device its failing.. I'm fairly new to JS too.
I tried to hardcode the data in the AJAX but it doesnt seem to work. Preferebly I would like to use something like var pdata = $('#form').serialize(); or something else if its better.
Any ideas?
EDIT: Forgot to say that the PHP on the server auto submits by using JS when $_POST is set (isset)
The form
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="email" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-primary">Logg inn</button>
</form>
The javascript
<script>
function dologin() {
//var pdata = $('#form').serialize();
//alert(pdata);
$.ajax({
type: 'POST',
data: {email:"test#test.no",password:"test"},
url: 'LINK',
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
};
</script>
The PHP
<form id="form" method="post">
<!-- {{ Form::label('email', 'Email Address') }} -->
<div class="form-group">
<input type="text" name="email" value="<?php if(isset($_POST["email"])) echo $_POST['email'];?>">
</div>
<div class="form-group">
<!-- {{ Form::label('password', 'Password') }} -->
<input type="text" name="password" value="<?php if(isset($_POST["password"])) echo $_POST['password'];?>">
</div>
</form>
Are you able to hit your server via through phonegap?
If no then please check your config.xml for white list urls - change access control property to
access origin = "*"
Hopeful you will be able to hit your server with data.
You can use weinre to debug your app. That way you will be able to see if the request was placed from the app or not.
http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html