jQuery form data not sending to PHP page - javascript

I'm very new to anything outside of PHP, so forgive me if this comes off as simple.
I'm trying to create a simple registration form, which then calls a PHP function, which inserts the data.
The problem is, the data doesn't seem to be going to the page.
My form:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function () {
$('#register').on('submit', function (e) {
$.ajax({
type: 'POST',
url: 'http://warofman.com/actions.php?type=register',
data: $('#register').serialize(),
success: function () {
alert('Form was submitted.');
console.log(e);
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form id="register">
Username: <input type="text" name="login"><br>
Email: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
Confirm Password: <input type="password" name="confpass"><br>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
And then, the PHP:
function register()
{
$login = $_POST['login'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
do_reg($login, $email, $password, $confpass);
}
Where do_reg() calls the process of registering.

Make the following changes, (follow good practice)
<form id="register" action="" method="post">
<label for="login">Username:</label>
<input id="login" type="text" name="login"><br>
<label for="email">Email:</label>
<input type="email" name="email" id="email" /><br>
<label for="password">Password:</label>
<input type="password" name="password" id="password"><br>
<label for="confpass">Confirm Password:</label>
<input type="password" name="confpass" id="confpass"><br>
<input type="submit" name="submit" value="Register">
</form>
On php side:
You are writing everything inside a function(register) and not calling it, instead do something like this,
if(isset($_POST['submit'])){
$login = $_POST['login'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
do_reg($login, $email, $password, $confpass);
}

You can't pass a query string in the URL using POST. Add the "type=register" to your data:
$.ajax({
type: 'POST',
url: 'http://warofman.com/actions.php',
data: "type=register&" + $('#register').serialize(),
success: function () {
alert('Form was submitted.');
console.log(e);
}
});
e.preventDefault();
});

Related

Contact form Ajax, php, Jquery:

I'm trying to make a contact form with Ajax, php and Jquery for my last study project (php with mvc architecture). I have some questions about it:
my contact form is ok: I receive emails! But I am not sure that is really an Ajax request even if I use the $.ajax() because in my terminal there is no XHR request...
I would like to show a message when email is send like "Thanks for your message" but the message appear only for one second and the page is refreished so all informations are cleaned. I tryed with a e.preventDefault() but when I use it, I don't receive the email.
Thanks for your answers and you help.
contat view:
<section class="form_container">
<form class="contact_form" id="contact_form" method="post" action="index.php?action=contact">
<input class="firstname form" type="text" name="firstname" placeholder="Nom" id="firstname" required>
<span class="error-message"></span><br/>
<input class="lastname form" type="text" name="lastname" placeholder="Prénom" id="lastname" required>
<span class="error-message"></span><br/>
<input class="email form" type="text" name="email" placeholder="Email" id="email" required>
<span class="error-message"></span><br/>
<input class="object form" type="text" name="object" placeholder="Objet" id="object" required>
<span class="error-message"></span><br/>
<textarea class="content form" name="content" placeholder="Votre message" id="content" cols="30" rows="10" required></textarea>
<span class="error-message"></span><br/>
<input class="envoyer form" type="submit" name="submit" value="Envoyer" id="submit"><br/>
</form>
<div id="msg-ok">Merci. Votre message a bien été envoyé.</div>
<div id="msg-notok">Merci de renseigner correctement tous les champs .</div>
</section>
contact_form.js:
// send messages with Ajax
'use strict';
$('#contact_form').submit(function() {
nom = $(this).find("#firstname").val();
prenom = $(this).find("#lastname").val();
email = $(this).find("#email").val();
object = $(this).find("#object").val();
message = $(this).find("#content").val();
$.ajax({
type: "POST",
data: {
nom:nom,
prenom:prenom,
email:email,
object:object,
content:content
},
url: 'http://www.projet-5.pauline-superweb.com/index.php?action=contact',
success: function(data) {
$("#contact_form").hide();
$('#msg-ok').fadeIn();
},
error: function() {
$('#msg-notok').fadeIn();
}
})
});
});
php code in my controller:
function contact()
{
if (isset($_POST['submit'])) {
$e = array();
$e['error'] = "Formulaire non valide";
if(isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['object']) && isset($_POST['content']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$e['email_invalide'] = "email_invalide";
} else {
$e['error'] = 'Ok';
$nom = $_POST['firstname'];
$prenom = $_POST['lastname'];
$email = $_POST['email'];
$object = $_POST['object'];
$content = $_POST['content'];
$to = 'contact.super.web#gmail.com';
$sujet = $object;
$message = $content;
$headers = 'From ' . $nom . ' ' . $prenom . ' ' . $email;
mail($to, $sujet, $message, $headers);
}
}
ob_start();
include('views/frontend/site/contactView.php');
$content = ob_get_clean();
require("views/frontend/site/template.php");
}
change this
<input class="envoyer form" type="submit" name="submit" value="Envoyer" id="submit">
to
<input class="envoyer form" type="button" name="submit" value="Envoyer" id="submit">
and change
$('#contact_form').submit(function() {
to
$('#submit').click(function() {

405 method not found. On localhost

So I'm making a form that puts info into my local mysql db. But I stuck when I try to POST it. I getting "405 method not found" when try to debbug. I'm sing xampp for my virtual DB, maybe it's because of that?
The code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Kasmetinių atostogų prašymas</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="title">
<h1>Kasmetinių atostogų prašymas</h1>
</div>
<div class="form">
<form id="requestForm" method="POST" target="_blank">
<input type="date" name="request_date" id="input_field" placeholder="Prašymo data" required></br></br>
<input type="text" name="first_name" placeholder="Vardas" id="input_field" required></br></br>
<input type="text" name="last_name" placeholder="Pavardė" id="input_field" ></br></br>
<input type="number" name="personal_code" placeholder="Asmens kodas" id="input_field" min="11" max="11" ></br></br>
<input type="text" name="p_address" placeholder="Jūsų adresas" id="input_field" ></br></br>
<input type="date" name="requestDateFrom" id="input_field" placeholder="Atostogos nuo" ></br></br>
<input type="date" name="requestDateTo" id="input_field" placeholder="Atostogos iki" ></br></br>
<input type="number" name="daysNumber" placeholder="Atostogų dienų skaičius" id="input_field" ></br></br>
</br>
<Input type="button" name="submit_button" id="buttonLast" value="Patvirtinti">
</form>
</div>
<script>
$(document).ready(function(){
$("#buttonLast").click(function(){
$.ajax({
url:"http://127.0.0.1:5500/insert.php",
type: "POST",
data:$("#requestForm").serialize(),
success:function(response)
{
alert("Well done!");
}
});
});
});
</script>
</body>
</html>
And this is php code to connect db and post info into specific columns.
For the purpose of test I trying to post just from the 3 cols.
PHP:
<?php
$con = mysqli_connect("localhost","root","","test");
if(!$con)
{
echo 'Connection problems';
}
else
{
echo 'Ok';
}
if(isset($_POST['submit'])){
$date = $_POST['requestDate'];
$name=$_POST['firstName'];
$lname = $_POST['lastName'];
$query = "insert into info (date,name,lname) values ('$date','$name','$lname')";
if($con->query($query) === true )
{
echo 'Duomenys išsaugoti!';
}
else{
echo 'Duomenų nepavyko išsaugoti!';
}
}
header("refresh:2; url=index.html");
?>
Change
type: "POST"
to
method:"POST"
Other error you might encounter:
You are using requestDate in php but request_date in html. Similar for other params.
Update:
Add cors header to Ajax call
url:"http://127.0.0.1:5500/insert.php",
method: "POST",
headers: {
'Access-Control-Allow-Origin': '*'
},
data:$("#requestForm").serialize(),
success:function(response)
{
alert("Well done!");
}
$(document).on("submit", "#requestForm", function (event) {$.ajax({
url:"https://127.0.0.1:5500/insert.php",
type: "POST",
data:$(this).serialize(),
success:function(response)
{
alert("Well done!");
}
});
});
Try this Jquery Code.

On form submission hide the form diva and send an email using jQuery

My objective is to send the form data as an email using php and the form div should get replaced by another div. I have done hiding the div part using jquery but not able to send and email. I have also written the code to send email but my issue is how to call the file which has email sending code.
My form code:
<form method="post" id="formsub">
<div id="form">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Name" required>
</div>
<div class="form-group">
<input type="text" name="email" class="form-control" id="email" placeholder="Email" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="form-control" id="phone" placeholder="Phone Number" required>
</div>
<div class="form-group">
<input type="button" id="addbut" name="submit" value="Submit" class="form-control">
</div>
</div>
</form>
My code to hide the div and tried form submission script:
<script>
$(document).ready(function() {
$("#addbut").on('click', function() {
$.ajax({
type: "POST",
url: "fromemail.php",
data: $(form).serialize(),
success: function(){
$("#form").hide();
$("#address").show();
}
});
});
});
</script>
My php email sending code:
<?php
if($_POST['submit']){
$to = "akhil#redd.xyz"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$phone = $_POST['phone'];
$subject = "Spots Contact";
$message = $first_name . ", with " . $phone . "has enquired for the service";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
if(mail($to,$subject,$message,$headers))
{
echo "<script>alert('We will contact you shortly');</script>";
}
}
?>
Give file name in form action attribute :
<form id="formsub" method="post" action="fromemail.php">
and do ajax code like this :
$(document).ready(function(){
var form=$("#formsub");
$("#addbut").click(function(){
$.ajax({
type:"POST",
url:form.attr("action"),
data:$("#formsub").serialize(),
success: function(response){
console.log(response);
}
});
});
});
#Rakhi..
Is this correct??
<script type="text/javascript" src="assets/js/jquery-2.2.1.min.js"></script>
<script>
$(document).ready(function() {
var form=$("#formsub");
var base_url = "www.3ding.in/spots/";
$("#addbut").on('click', function() {
$("#form").hide();
$("#address").show();
$.ajax({
type: "POST",
url: base_url + "fromemail.php",
data: $("#formsub").serialize(),
success: function(response){
alert(1);
console.log(response);
}
});
});
});

having trouble in showing php success message with ajax

Here is my below code I'm just trying to send a message form with php script but the message is submitted well. but when it comes to showing success message I'm having trouble page submits the data but shows no code.
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#send").click(function(event){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "process.php",
data:{
name: name,
email: email,
message: message,
},
success:function(data) {
$('#msg').html(data);
}
});
});
});
</script>
Below is php and html code:
<?php
include 'db.php';
$name=$_POST["name"];
$email=$_POST["email"];
$message=$_POST["message"];
$query = mysqli_query($con, "INSERT INTO test(name, email, message) VALUES ('$name', '$email', '$message')");
if($query){
echo "Your message has been sent successfully!";
}
else{
echo "Your message has been not sent successfully!";
}
mysqli_close($con);
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="text" class="form-control" id="name" name="name">
<input type="text" class="form-control" id="email" name="email">
<textarea class="form-control" rows="5" id="message" name="message"></textarea>
<button id="send" type="submit" class="btn btn-primary">Send</button>
</form>
<div id="msg" class="alert alert-success hidden"><strong></strong></div>
It is because your form will be submitted as the button has the type submit. By changing the type to button the ajax should be working.
Change type="submit" to type="button"
I hope this will help!

Can I call a php file on form submit, and call or echo a JS function from that?

So I'm basically trying to create an HTML form that will
process my login through php POST method
close my login lighbox with javascript, or display an error (right now I'm using JS to change an invisible form value under the login form.
HTML
if (isset($_GET['error'])) {
echo '<p class="error">Error Logging In!</p>';
}?>
<br />
<form action="process_login.php" method="post" name="login_form">
Email: <input class="searchform" type="text" name="email" size="20"/><br />
Password: <input class="searchform" type="password"
name="password"
id="password" size="20"/><br />
<input type="button" class="searchform"
value="Submit" size="40" style="height:45px; width:90px"
onclick="formhash(this.form, this.form.password);" />
<input type="text" id="errorbox" style="height:45px; width:180px" value=""><br>
</form>
here's the php file:
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p'];
if (login($email, $password, $mysqli) == true) {
// Login success
echo "<script>document.getElementById('light').style.display=
'none';document.getElementById('fade').style.display= 'none'</script>";
} else {
// Login failed
echo "<script>document.getElementById('errorbox').value='Error'</script>";
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
I know I'm not doing this right, I'm just not sure HOW to do it at all...
Well, yes, technically you can do that, but it is a VERY bad practice, and extremely not clean.
what you'd prefer to do is use Ajax, and do those JS actions in it's success callback:
Note: you will need to include the jQuery lib in your scripts.
Another none: if you don't have PHP 5.4 on your server, just remove the second callback function, and handle all the scenarios in the success callback
!(function($){
$(function() {
$('#submitBtn').on('submit', function(){
$.post('process_login.php', $('form[name="login_form"]').serialize(), function(data){
//data is a json object which contans the reponse
data = $.parseJSON(data);
$("fade").fadeOut();
$("light").fadeOut();
},
function(data){//error callback
data = $.parseJSON(data);
if(data.forbidden){
$("#errorBox").html("Error!");
}
else if(data.error){
$("#errorBox").html("Invalid request!");
}
});
});
});
})(window.jQuery);
HTML:
<form name="login_form">
<div>
<input type="text" name="email" placeholder="email">
</div>
<div>
<input type="password" name="p" placeholder="password">
</div>
<div>
<input type="button" id="submitBtn" value="Login">
</div>
</from>
PHP:
$response = array();
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p'];
if (login($email, $password, $mysqli) == true) {
http_response_code(200);//HTTP OK, requires php 5.4
$response['success'] = true;
} else {
// Login failed
$response['forbidden'] = true;
http_response_code(401);//HTTP forbidden
}
} else {
// The correct POST variables were not sent to this page.
$response['error'] = true;
http_response_code(400);//HTTP bad request
}
echo json_encode($response);
add onsubmit event attribute to the form:
<form onsubmit="return validate();">...
where validate() is a js function that closes lightbox and returns true if form is ok, or displays errors and returns false if form is bad.

Categories