run php script with ajax shows no result - javascript

I'm trying to run a php script using ajax after a form submission.
this is the form
<form id="form" class="form">
<input id="email" type="email" required name="email" placeholder="Email" onchange="myUpdateFunction()" value="">
<textarea id="message" type="text" value="" name="message" onchange="myUpdateFunction()" required placeholder="Comments" style="border:none;border-bottom:1px solid #424242; width:530px;"></textarea>
<input id="submit" type="submit" class="submit" name="send_request" value="Submit" >
</form>
this is my script
$('.submit').on('click', function() {
$.ajax({
url: "send.php",
method:'post',
data: {'email': $('#email').val(), 'message': $('#message').val()}
}).done(function() {
alert('Message Sent.');
});
});
and this is my send.php file
<?php
if(isset($_POST['send_request'])){
//send email
}
?>
but it doens't work, the page is reloaded, the email is not sent and no "alert message" is displayed
there is no problem in php because if I delete the javascript and I add action="send.php" method="POST" as attributes in the form it works, so I think that the problem is the javascript

http://jsfiddle.net/o5xvpkmv/2/
You shouldn't use the onchange or the click event for this kind of stuff, but the submit event (preventing the default behaviour of submit button).
<form id="form" class="form">
<input id="email" type="email" name="email" placeholder="Email" required>
<textarea id="message" type="text" value="" name="message" placeholder="Comments" required></textarea>
<input id="submit" type="submit" class="submit" name="send_request" value="Submit">
</form>
$("#form").on('submit', function(e) {
e.preventDefault();
$.ajax({
url: "send.php",
method:'post',
data: $( this ).serialize()
}).done(function() {
alert('Message Sent.');
});
});
or (both ways are good)
$(document).ready(function () {
$('#submit').click(function () {
$.ajax({
url: "send.php",
method: 'post',
data: $(this).serialize()
}).done(function () {
alert('Message Sent.');
});
return false;
});
});
Also, about the backend, you should make this kind of check:
if (
isset($_POST["email"]) &&
!empty($_POST["email"]) &&
isset($_POST["message"]) &&
!empty($_POST["message"])) {
//send email
}

Related

HTML Ajax form not working with FormSubmit co API

I'm using Svelte and Astro. And I'm using formsubmit.co for the API to send the email. But it doesn't send the email.
Here is the js
<script>
import { onMount } from 'svelte';
import jq from 'jquery';
onMount(() => {
window.jq = jq;
jq("#form").submit(function (event) {
var formData = {
name: jq("#name").val(),
email: jq("#email").val(),
message: jq("#message").val(),
};
jq.ajax({
method: 'POST',
url: 'https://formsubmit.co/ajax/01e95b7b608117ff23368c8ea240889d',
dataType: 'json',
accepts: 'application/json',
data: formData,
success: (data) => console.log(data),
error: (err) => console.log(err)
});
});
});
</script>
Here is the form html
<form method="POST">
<div class="flex">
<input class="input-style" id="name" type="text" name="name" required placeholder="Name">
<input class="input-style" id="email" type="email" name="email" required placeholder="Email">
<input type="hidden" name="_subject" value="Downlu - Support Email">
</div>
<textarea class="input-style" id="message" name="message" type="message" cols="60" rows="4" placeholder="Message" required></textarea>
<button class="btn-submit" type="submit">Send</button>
</form>
It just reloads the page, and I've checked my email and nothing shows up.

How to check if submitting form with jQuery if successful?

I have following codes as form, and I wanted to check if the form is been successfully submitted.
I was wondering how I can check on the console. I want to check if the form is been successfully submitted so I can display another form.
<form id="signup" data-magellan-target="signup" action="http://app-service-staging.com" class="epic_app-signup" method="POST">
<div class="grid__column " style="width: 100%;">
<input type="text" name="first_name" placeholder="Name" required/>
</div>
<div class="grid__column " style="width: 100%;">
<input type="text" name="password" placeholder="Password" required/>
</div>
<div class="grid__column " style="width: 100%;">
<input type="text" name="confimred-password" placeholder="Confirmed password" />
</div>
<div class="grid__column " style="width: 100%;">
<input type="date" name="startdate" id="startdate" min="2019-12-16">
</div>
</div>
<button type="submit" class="grid__column" style="width: 50%;"></button>
</div>
</div>
</div>
</form>
and the script,
$('.epic_app-signup').on('submit', function(e) {
e.preventDefault();
var formData = $('.epic_app-signup').serializeArray();
var jsonData = {};
formData.forEach(function(item, index) {
jsonData[item.name] = item.value;
});
console.log('data\n', jsonData);
$.ajax({
url: 'http://app-service-staging.com/api/auth/register',
type:'POST',
data: jsonData,
contentType: 'application/json'
}).done(function(data, textStatus, jqXHR) {
if (textStatus === 'success') {
}
});
});
});
you can do this by various ways currently you are not using ajax request if you want to achieve this without ajax let follow these steps
when user click on submit button your form is submitted received form information(you define the path in action attribute where form submitted) after processing successfully redirect toward a new form
second solution use jquery ajax request
//first form
<form action='test.php' id='form_1' method='post'>
<label>Full Name</label>
<input type='text' name='full_name'>
<input type='submit'>
</form>
//second form
<form action='test.php' id='form_2' method='post' style='display:none'>
<label>Father Name</label>
<input type='text' name='father_name'>
<input type='submit'>
</form>
use jquery cdn
<script src='https://code.jquery.com/jquery-git.js'></script>
<script>
$("#form_1").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert("form submitted successfully");
$('#form_1').hide();
$('#form_2').show();
},
error:function(data){
alert("there is an error kindly check it now");
}
});
return false;
});
</script>

Submitting form with ajax and formspree using VuesJS

I'm trying to submit a form using formspree I get two different errors. When I try to submit the form after I refresh the page I get an error on a new page saying
Cannot POST /Contact
When I go back and try to submit the form again I get an error in the console saying:
POST https://formspree.io/sheabathandbody#mail.com 400 () jquery.min.js:4
send # jquery.min.js:4
ajax # jquery.min.js:4
(anonymous) # main.js:8
dispatch # jquery.min.js:3
r.handle # jquery.min.js:3
I've used this method/code to submit my forms before so i don't know what the problem could be
Contact.vue form
<form id="contact" name="contact-form" method="post" action = "">
<fieldset>
<input placeholder="Your name" name="name" type="text" id="name" tabindex="1" required="required">
</fieldset>
<fieldset>
<input placeholder="Your Email Address" name="email" id="email" type="email" tabindex="2" required="required">
</fieldset>
<fieldset>
<input placeholder="Your Phone Number (optional)" type="tel" tabindex="3">
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." tabindex="5" name="message" id="message" required="required"></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="submit_btn" >Submit</button>
</fieldset>
</form>
Here's my main.js
(function($) {
$(window).on("load", function() {
// Contact form
var form = $("#contact");
form.submit(function(event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: "https://formspree.io/sheabathandbody#mail.com",
method: "POST",
data: $(this).serialize(),
dataType: "json",
beforeSend: function() {
form.prepend(
form_status
.html(
'<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>'
)
.fadeIn()
);
}
}).done(function(data) {
form_status
.html(
'<p class="text-success">Thank you for contacting us. We will be in touch.</p>'
)
.delay(3000)
.fadeOut();
});
});
});
})(jQuery);
Guess this has nothing to do with VueJS since it does not use at all vue in that chunks of code you shared, this is pure jQuery.
Said that, the problem sending the form was because you were not listening correctly to submit event.
form.on('submit', function () { ... })
On the other hand, ajax call is not working correctly; you should check documentation of formspree.io and correct it.
Check next code
$(document).ready(function() {
// Contact form
var form = $("#contact");
form.on('submit', function(event) {
alert('Hola hola. This is working now!');
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: "https://formspree.io/sheabathandbody#mail.com",
method: "POST",
data: $(this).serialize(),
dataType: "json",
beforeSend: function() {
form.prepend(
form_status
.html(
'<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>'
)
.fadeIn()
);
}
}).done(function(data) {
form_status
.html(
'<p class="text-success">Thank you for contacting us. We will be in touch.</p>'
)
.delay(3000)
.fadeOut();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact" name="contact-form" method="post" action="">
<fieldset>
<input placeholder="Your name" name="name" type="text" id="name" tabindex="1" value="blah" required="required">
</fieldset>
<fieldset>
<input value="email#email.com" placeholder="Your Email Address" name="email" id="email" type="email" tabindex="2" required="required">
</fieldset>
<fieldset>
<input value="123123123" placeholder="Your Phone Number (optional)" type="tel" tabindex="3">
</fieldset>
<fieldset>
<textarea placeholder="Type your message here...." tabindex="5" name="message" id="message" required="required">Damn</textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="submit_btn">Submit</button>
</fieldset>
</form>
You can create a method for example postNow.
methods: {
postNow() {
const link = "https://formspree.io/sheabathandbody#mail.com"
var data = new FormData();
data.append('_replyto',this.email)
data.append('message',this.message)
this.axios.post(link,data , {
headers: {
'Accept': 'application/json',
},
// body: data,
}).then(res =>{
console.log("response ===" ,res)
this.email = "" ;this.message=""; //don't forget to create your data
}).catch(err =>{
console.log(err)
});
}
},
And in your template you can use the simple HTML form with few tweaks ofc,
<form #submit.prevent="postNow" method="POST" >
<label>
Your email:
<input type="email" name="_replyto" v-model="email" />
</label>
<label>
Your message:
<textarea name="message" v-model="message"></textarea>
</label>
<button type="submit">Send</button>
</form>

Submit form with ajax via callback

I want to submit the form when a gcapcha was clicked. I tried submit with (my silly) jquery function that I know. But it's not work.
Here is my code (what's wrong with it).
Javascript
var verifyCallback = function(e) {
document.getElementById("form-contact").submit();
$.ajax({
type : 'POST',
url : 'inc/contact_sent.php',
data : $(this).serialize(),
success : function(data){
$("#contact").html(data);
}
});
return false;
};
var onloadCallback = function() {
grecaptcha.render("captcha", {
sitekey: "xxx",
callback: verifyCallback
})
};
HTML
<div id="contact" class="contact-form">
<form class="ajaxForm detailedsearch inline-style" method="post" id="form-contact">
<input type="text" class="form-control" name="cntc_name" placeholder="Your name" required>
<input type="email" class="form-control" name="cntc_email" placeholder="Your email" required>
<input type="text" class="form-control" name="cntc_tel" placeholder="Your phone">
<input type="text" class="form-control" name="cntc_subj" placeholder="Subject" value="<?=(isset($_POST['ptitle']))?"Queries for $_POST[ptitle]":""?>" required>
<textarea class="form-control" name="cntc_desc" rows="6" placeholder="Your Detail" required></textarea>
<div class="form-group">
<div id="captcha" class="center-captcha"></div>
<div id="gcaptcha" style="transform:scale(0.50);-webkit-transform:scale(0.50);transform-origin:0 0;-webkit-transform-origin:0 0;"></div>
<span class="text-danger">*Please complete the form to proceed.</span>
</div>
<!-- <button type="submit" class="btn btn-success btn-block"><i class="fa fa-envelope-o"></i> Submit Form</button> -->
</form>
</div>
You should do this....
//register a event for form submit
$( "form" ).submit(function( e ) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'inc/contact_sent.php',
data : $(this).serialize(), //serialize the form data
success : function(data){
$("#contact").html(data);
}
});
});
var verifyCallback = function(e) {
//submit form
$("#form-contact").submit();
return false;
};
var onloadCallback = function() {
grecaptcha.render("captcha", {
sitekey: "xxx",
callback: verifyCallback
})
};

Inserting Data into MySQL without calling PHP file inside HTML

I have a form:
<form method="post" action="insert.php">
<input type="text" name="firstname" placeholder="Vorname" required>
<br>
<input type="text" name="lastname" placeholder="Nachname" required>
<br>
<input type="text" name="nickname" placeholder="Spitzname" required>
<br>
<input type="email" name="email" placeholder="Email" required>
<br>
<input type="submit" value="Speichern">
</form>
As you can see my action is action="insert.php" so that calls my insert.php. A new url is created and it is opened in the browser.
But what if i dont want that? I want to stay on the same site where the form is and i would prefer not to call any php directly. i would prefer to call a javascript function. For example, my select i do with ajax:
function getData() {
$.ajax({
url: "queries.php",
data: {action: "retrieve_data"},
dataType: "json",
type: "post",
success: function(output) {
// do stuff
}
});
}
Can i also do something like that with the insert?
<html>
<body>
<form method="post" action="insert.php" id="insertForm">
<input type="text" name="firstname" placeholder="Vorname" required>
<br>
<input type="text" name="lastname" placeholder="Nachname" required>
<br>
<input type="text" name="nickname" placeholder="Spitzname" required>
<br>
<input type="email" name="email" placeholder="Email" required>
<br>
<input type="button" id="insertData" value="Speichern">
</form>
<script type="text/javascript" src="lib/js/jquery-2-1-3.min.js"></script>
<script type="text/javascript">
$(function () {
$('#insertData').click({ inputs:$('#insertForm :input') }, getData);
});
function getData(o) {
var values = {};
o.data.inputs.each(function() {
values[this.name] = $(this).val();
});
$.ajax({
url: "queries.php",
data: {action: "retrieve_data", firstname: values['firstname'], lastname: values['lastname'], nickname: values['nickname'], email: values['email']},
dataType: "json",
type: "post",
success: function(output) {
// do stuff
}
});
}
</script>
</body>
</html>
Here you go, you can always edit is as you want, or what values are optional and such.
Remember i've used a type="button" so the page doesn't reload, so the action could just stay empty.
Since you seem to be using jQuery, this is easy; as explained in the documentation. If you give your form id=insertForm this should work:
$("#insertForm").submit(function(e){
$.ajax({
url: "/insert.php",
type: "post",
data: $(this).serialize();
});
e.preventDefault();
});

Categories

Resources