jQuery script not writing values in database Mysql - javascript

My database has a table called utilizatori and has id,username,nume_prenume,parola,locatie,sambata columns.
Through the form, I am trying to add new entries in database but when I submit the form, it doesn`t add any entry.
A demo can be found HERE.
The update and delete operations are working fine.
HTML form:
<script src="js/jQuery/jquery.min.js"></script>
<!-- Include AngularJS library -->
<script src="lib/angular/angular.min.js"></script>
<!-- Include Bootstrap Javascript -->
<script src="js/bootstrap.min.js"></script>
<form class="form-horizontal alert alert-warning" name="empList" id="empForm" ng-submit="insertInfo(empInfo);" hidden>
<h3 class="text-center">Insert Employee Details Into Database</h3>
<div class="form-group">
<label for="Username">Nume utilizator:</label>
<input type="text" name="username" class="form-control" placeholder="Enter Employee Name" ng-model="empInfo.username" value="" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.username.$invalid && empList.username.$dirty">Name field is Empty!</p>
</div>
<div class="form-group">
<label for="Nume_prenume">Nume angajat:</label>
<input type="text" name="nume_prenume" class="form-control" placeholder="Enter Employee Email Address" ng-model="empInfo.nume_prenume" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.nume_prenume.$invalid && empList.nume_prenume.$dirty">Invalid Email!</p>
</div>
<div class="form-group">
<label for="Parola">Parola cont:</label>
<input type="text" name="parola" class="form-control" placeholder="Enter Employee Name" ng-model="empInfo.parola" value="" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.parola.$invalid && empList.parola.$dirty">Name field is Empty!</p>
</div>
<div class="form-group">
<label for="Rol_user">Rol:</label>
<input type="text" name="rol_user" class="form-control" placeholder="Enter Employee Address" ng-model="empInfo.rol_user" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.rol_user.$invalid && empList.rol_user.$dirty">Address field is Empty!</p>
</div>
<div class="form-group">
<button class="btn btn-warning" ng-disabled="empList.$invalid">Add Into Database</button>
</div>
</form>
<script src="js/angular-script.js"></script>
Angular JS script:
// Application module
var crudApp = angular.module('crudApp', []);
crudApp.controller("DbController", ['$scope', '$http', function($scope, $http) {
// Function to get employee details from the database
getInfo();
function getInfo() {
// Sending request to EmpDetails.php files
$http.post('databaseFiles/empDetails.php').success(function(data) {
// Stored the returned data into scope
$scope.details = data;
});
}
// Setting default value of gender
$scope.empInfo = {
'rol_user': 'Operator receptie'
};
// Enabling show_form variable to enable Add employee button
$scope.show_form = true;
// Function to add toggle behaviour to form
$scope.formToggle = function() {
$("#empForm").slideToggle();
$("#editForm").css('display', 'none');
}
$scope.insertInfo = function(info) {
$http.post('databaseFiles/insertDetails.php', {
"username": info.username,
"nume_prenume": info.nume_prenume,
"parola": info.parola,
"rol_user": info.rol_user
}).success(function(data) {
if (data == true) {
getInfo();
$("#empForm").css('display', 'none');
}
});
}
$scope.deleteInfo = function(info) {
$http.post('databaseFiles/deleteDetails.php', {
"del_id": info.id
}).success(function(data) {
if (data == true) {
getInfo();
}
});
}
$scope.currentUser = {};
$scope.editInfo = function(info) {
$scope.currentUser = info;
$('#empForm').slideUp();
$('#editForm').slideToggle();
}
$scope.UpdateInfo = function(info) {
$http.post('databaseFiles/updateDetails.php', {
"id": info.id,
"username": info.username,
"nume_prenume": info.nume_prenume,
"parola": info.parola,
"rol_user": info.rol_user
}).success(function(data) {
$scope.show_form = true;
if (data == true) {
getInfo();
}
});
}
$scope.updateMsg = function(emp_id) {
$('#editForm').css('display', 'none');
}
}]);
Insert info PHP script:
<?php
// Including database connections
require_once 'database_connections.php';
// Fetching and decoding the inserted data
$data = json_decode(file_get_contents("php://input"));
// Escaping special characters from submitting data & storing in new variables.
$username = mysqli_real_escape_string($con, $data->username);
$nume_prenume = mysqli_real_escape_string($con, $data->nume_prenume);
$parola = mysqli_real_escape_string($con, $data->parola);
$rol_user = mysqli_real_escape_string($con, $data->rol_user);
// mysqli insert query
$query = "INSERT into utilizatori (username,nume_prenume,parola,rol_user) VALUES ('$username','$nume_prenume','$parola','$rol_user')";
// Inserting data into database
mysqli_query($con, $query);
echo true;
?>
And database_connections.php script:
<?php
$con = mysqli_connect("localhost", "user", "pasword", "database");
?>

I found the issue. I was trying to write in 4 columns, but there are 6 (excluding id which is auto increment.
If I rewrite this query to write in all 6 or I remove the other 2 columns from database, will work.
// mysqli insert query
$query = "INSERT into utilizatori (username,nume_prenume,parola,rol_user) VALUES ('$username','$nume_prenume','$parola','$rol_user')";

Related

Has Post request a limited number of parameters?

I'm trying to send to my server 5 parameters:
Action: will contain the name of the form, in this case "signin"
Name: Name of the person who wants to signin
Surname: Surname of the person who wants to signin
Email: Email of the person who wants to signin
Password: Password of the person who wants to signin
the problem is that my server reads only 4 parameters: Name, Surname, Email and Password, and it don't see Action!
Here's the code:
Javascript:
function signin() {
alert("OK");
var action = $(this).attr('name'); // puts in action the name of the form (this case "signin")
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: document.getElementById('signin-name').value, // Name in the form
Surname: document.getElementById('signin-surname').value, // // Surname in the form
Email: document.getElementById('singin-email').value, // Email in the form
Password: document.getElementById('singin-password').value // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
PHP - Signin.php:
<!-- Signin Form -->
<?php
require('include/header.php');
?>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
<?php require('include/footer.php');?>
PHP - Submit.php:
<?php
#Detect AJAX and POST request, if is empty exit
if((empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') or empty($_POST)){
exit("Unauthorized Acces");
}
require('inc/config.php');
require('inc/functions.php');
# Check if Login form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-login'){
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$email = $_POST['Email'];
$password = $_POST['Password'];
/* Server side PHP input validation */
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Checking Email and Password existence in DB
# Selecting the email address of the user with the correct login credentials.
$query = $db->query("SELECT Email FROM USERS WHERE Email='$email' AND Password='$password'");
$result = $query->fetch(PDO::FETCH_ASSOC);
if($query->rowCount() == 1) {
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
} else {
# Failure: Set error message
$Return['error'] = 'Invalid Login Credential.';
}
output($Return);
}
# Check if Registration form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-signin') {
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$name = $_POST['Name'];
$surname = $_POST['Surname'];
$email = $_POST['Email'];
$password = $_POST['Password'];
# Server side PHP input validation
if($name === '') {
$Return['error'] = "Please enter Full name.";
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Check Email existence in DB
$result = $db->query("SELECT Email FROM USERS WHERE Name='$name' AND Surname='$surname' AND Email='$email'");
if($result->rowCount() == 1){
# Email already exists: Set error message
$Return['error'] = 'You have already registered with us, please login.';
}else{
# Insert the new user data inside the DB
try{
$db->query("INSERT INTO `users` (`ID_user`, `Name`, `Surname`, `Email`, `Password`) VALUES (NULL, '$name', '$surname', '$email', '$password')");
}
catch (PDOException $e) {
echo $e->getMessage();
}
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
}
output($Return);
}
PHP - Functions.php
# Function to set JSON output
function output($Return=array()){
header('Content-Type: application/json; charset=UTF-8');
#exit(json_encode($Return)); # Final JSON response
echo json_encode($Return);
}
here is a screenshot of the debugger:
Debug Screenshot
function signin() {
alert("OK");
var action = $('#form-signin').attr('name'); // puts in action the name of the form (this case "signin")
// alert(action);
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: $('signin-name').val(), // Name in the form
Surname: $('signin-surname').val(), // // Surname in the form
Email: $('singin-email').val(), // Email in the form
Password: $('singin-password').val() // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
The problem is with your scope for $this. Since your Javascript is called within a BUTTON element, $this has a scope relative to the button, not the form. In trying to check what $this returns by itself, it says [object Window].
function signin() {
console.log(this);
}
Console:
[object Window]
You need to either pass this via signin(this) and backtrack to the containing form element if you plan on reusing the Javascript for other forms or just use the form id in place of this.
HTML:
<button onclick="signin(this)">
JS:
function signin(element) {
var action = element.form.getAttribute("name");
}
or just simply change the this to the form's id as Lakmal pointed out:
function signin() {
var action = $("#form-signin").attr("name");
}

Html form refuses to be submitted via JQuery

So I was following an AJAX/JQuery tutorial for a registration script that will be acted upon by PHP/MySQL and will be submitted via JQuery.
Now the problem that I'm encountering is that the form submits directly to the action page, which should not be so, as it supposed to submit to script.js Here are the html code for the form.
<form method="post" id="register-form" action="transact-user.php">
<h2 class="form-signin-heading"></h2>
<div class="form-group">
<div class='row'>
<div class='col-sm-6'>
<input type='text' class='form-control' id='fname' name='fname' placeholder="First name">
</div>
<div class='col-sm-6'>
<input type='text' class='form-control' id='lname' name='lname' placeholder="Last name">
</div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Phone Number" name = "phone" id = "phone" >
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name = "email" id ="email">
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name = "password" id = "password">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password Again" name = "confirmpassword" id = "confirmpassword">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block btn-apply" type="submit" name="btn-save" id = "btn-submit"><span class="glyphicon glyphicon-log-in"></span> Register</button>
</div>
</form>
</div> <!-- /container -->
<div id = "ack"></div>
script.js
$("button#btn-submit").click(function()
{ /* validation */
/* form submit */
if ($("fname").val()=="" || $("lname").val()=="" )
$("div#ack").html("Please enter both your first name and your surname");
else
$.post($("#register-form").attr("action"),
$("#register-form: input").serializeArray(),
function(data){
$("div#ack").html(data);
});
$("#register-form").submit(function(){
return false;
})
/* form submit */
});
Finally, this is the action php script transact-user.php
<?php
if($_POST)
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$confirmpassword = $_POST['confirmpassword'];
if($email != '') {
$qry = "SELECT * FROM users WHERE email='$email'";
$result = mysqli_query($mysqli,$qry);
if($result) {
if(mysqli_num_rows($result) > 0) {
echo "Email already in use";
}
#mysqli_free_result($result);
}
else {
die("Query failed");
}
}
$activation = md5(uniqid(rand(), true));
if ($stmt = "INSERT INTO users(firstname, lastname, email, password, verification, phone)"
." values('$fname', '$lname', '$email', '$password', "
. "'$activation','$phone')" or
die("Could not perform query ".mysqli_error($mysqli))) {
$result = mysqli_query($mysqli, $stmt)
or die("The system could not register you"
. "".mysqli_error($mysqli) . "<br>" . $stmt);
if ($result){
echo "sent";
}
//echo "<a href=\"gethotel.php?hid=".$row['hotel_id'].
//
/* close statement */
//$stmt->close();
}
}
?>
The issue us because you are hooking to the click event of the submit button and are not preventing the event from completing.
Also note that your selector to build the querystring is incorrect, as there should be a space before the : and not between the : and input, eg $("#register-form :input")
To fix the issues hook to the submit event of the form and use preventDefault(). Try this:
$("#register-form").submit(function(e) {
e.preventDefault();
if ($("fname").val().trim() == "" || $("lname").val().trim() == "") {
$("div#ack").html("Please enter both your first name and your surname");
} else {
$.post(this.action, $(this).find(':input').serializeArray(), function(data) {
$("div#ack").html(data);
});
}
});

How to Update/Edit data in database with AngularJS

Working on a web app , I just added the below update code and it's not working .
The summary of all the below code is :
Click a Button called update
It brings out the FORM which should contain the values of the clicked/current product.
Now when I hit save in this form it should update the database but it is not.
I am using $_GET in PHP file (update.php) to get the current Product ID.And then getting all data of that product via that ID.
PS: There is no error in console.
UPDATE CODE:
<?php
include "includes/connection.php";
switch($_GET['action']) {
case 'update_entry' :
$data = json_decode(file_get_contents("php://input"));
$index = $data->id;
$productname = $data->pname;
$company = $data->company;
$price = $data->price;
$quantity = $data->quantity;
if(isset($productname) && !empty($productname) && isset($company) && !empty($company) && isset($price) && !empty($price) && isset($quantity) && !empty($quantity)){
$query = "UPDATE `product` SET `id`='$index',`name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $index";
if(mysqli_query($con, $query)) {
return true;
} else {
echo "Error: " . $sql . "<br />" . mysqli_error($con);
}
break;
}
}
?>
Controller :
myApp.controller("updateCtrl",['$scope','$http','$routeParams','$location',function($scope,$http,$routeParams,$location){
$scope.update = function(){
var currentId = $routeParams.id;
$http.post("update.php?action=update_entry",{'id':currentId})
.then(function(data){
$location.path('/viewproduct');
});
}
}]);
HTML:
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
Update Button:
<td ng-controller="updateCtrl"><a class="btn btn-primary" href="#/updateproduct/action={{product.id}}" >Update</a></td>
Do like below
your view part
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
<td><a class="btn btn-primary" ng-click="addProductData();" >Update</a></td>
Inside your controller do like below
$scope.addProductData=function(){
var updatedata=$.param({'action':'update','productname':$scope.productname,'company':$scope.company,'price':$scope.price,'quantity':$scope.quantity,'id':currentId});
$http({
method:'POST',
url:'update.php',
data:updatedata,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
alert(response.data['msg']);
},function errorCallback(response) {
alert(response.data['msg']);
});
}
your update.php file should like below.
<?php
include "includes/connection.php";
$result=array();
if(isset($_REQUEST["action"]) && $_REQUEST["action"] !=""){
if($_REQUEST["action"]=="update"){
$productname = $_POST['productname'];
$company = $_POST['company'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$id=$_POST['id'];
$query = "UPDATE `product` SET `name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $id";
if(mysqli_query($con, $query)) {
$result['msg']="updated successfully";
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg']="unable to updated";
}
echo json_encode($result);
}
}
?>
i think you may basic idea.now you can implement in your way.
Try to use ng-model="{{product.name}}}" and not the placeholder in HTML.
And in your controller pass that model:
$http.post("update.php?action=update_entry",$scope.product)
Then you should get some data in your PHP.
Have you checked your php alone to make sure that you can fetch and update data using the php without angular? I would use post as it is more friendly for retrieving and updating data.
I would also b separate your call to the php endpoint into a service (factory). I would also just pass the entire object back through to ensure that you aren't missing something unless you have a concern about bandwidth.
I would unit test php first. Then separate logic in angular. Then b step through in debug to see what's being passed from the view.
I think you should check this: https://github.com/eliarms/CustomerManagerApp
This is a simple customer management app using Angularjs and PHP. The goal of the application is to highlight a lot of the different features offered by AngularJS and demonstrate how they can be used together.

AJAX instant check with php and javascript

I am developing a little webiste where I need to handle User registration. As usual, if a user requests a username that is already being used, the system should not allow to proceed with the registration.
I want to verify that during the register as most modern websites do. How do I do that using AJAX?
Register form:
<div class="container">
<form id="register_form" action="actions/register_action.php" method="post">
<div class="form-group">
<label for="name_area">Name</label>
<input type="text" name="name" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<label for="username_area">Username</label>
<input type="text" name="username" class="form-control" id="username_id" placeholder="Username">
</div>
<div class="form-group">
<label for="email_area">Email</label>
<input type="email" name="email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<label for="pass_area">Password</label>
<input type="password" name="pass" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<label for="conf_pass_area">Confirm password</label>
<input type="password" name="conf_pass_area" class="form-control" placeholder="Confirm password">
</div>
<br>
<div class="form-group">
<input type="submit" class="btn btn-primary" id="button_area" placeholder="Submit">
<!--action to:register_action!-->
</div>
</div>
</form>
</div>
users.php (where I do my php function regarding users):
<?php
//checks if username inserted is already in use
function check_username($username_pretended) {
global $conn;
$stmt = $conn->prepare('SELECT * FROM CommonUsers WHERE username=?');
$stmt->execute(array($username_pretended));
$res = $stmt->fetch();
if($res['username'] == "") {
return false;
}
else return true;
}
//inserts an user in the database
function insertUser($name, $username, $email, $password) {
global $conn;
$stmt = $conn->prepare('INSERT INTO CommonUsers(name, username, email, password) VALUES (?, ?, ?, ?)');
$stmt->execute(array($name, $username, $email, $password));
}
?>
From top of my head:
$("#username_id").on("change", function()
{
$.ajax(
{
method: "get", // or maybe post?
url: "yoururlhere",
data:
{
username: $(this).val()
},
success: function(data)
{
if (data == "0")
{
// Hide warning
}
else
{
// Warn user that username is already taken
}
}
});
});
This is the most simple way of doing this. Its sending the username to a server url for checking. Of course you will need an element to show the warning(which I could not find in your DOM).
You can check the ajax() method docs for detailed options.
In your PHP file:
$username = $_GET["username"];
if (check_username($username))
{
return "1";
}
else
{
return "0";
}

Form with ajax: JS not executing

I've got one big problem on only 1 page of a web site: Javascript doesn't want to be executed.
I tried to copy and paste from another web site i've done where it works perfectly... but not here. Maybe you can help me to figure out why it doesn't work...
I tried many ways, no ajax seems to work here.
Here is one of them, when i try to send a mail, i got no alert but {"reponse":"Mail sent corretly!"} instead, and the mail is corretly sent.
The submit button works! The page is refreshing, so i think the js is not executed. (i'd like to have the information without refreshing the page, like a normal ajax request).
I've tried to put the script (and the link to librairies) in the head, nothing changed.
Here is my code:
<--! Some HTML -->
<form class="form-horizontal myForm" method="post" action="contact.php">
<div class="form-group col-md-6">
<input type="text" class="form-control" name="prenom" id="prenom" placeholder="First Name" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required>
</div>
<div class="form-group col-md-6" style="margin-left:14px">
<input type="text" class="form-control" name="nom" id="nom" placeholder="Name" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required>
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" name="email" id="email" placeholder="Mail" required >
</div>
<div class="form-group col-md-6" style="margin-left:14px">
<input type="text" class="form-control" name="objet" id="objet" placeholder="Object" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required >
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control" name="message" id="message" placeholder="Your message" required>
</div>
<div class="form-group">
<label for="captcha" class="col-xs-12 col-sm-2 control-label">Captcha</label>
<div class="col-xs-6 col-sm-2">
<input type="text" class="form-control" id="captcha" name="captcha" required>
</div>
<div class="col-xs-2 col-sm-1">
<img src="form.php">
</div>
</div>
<div class="form-group col-md-12">
<button type="submit" class="btn btn-default">Submit</button>
</div>
<div class="the-return"> </div>
</form>
<--! Some HTML -->
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script> <!-- Gem jQuery -->
<script>
$(document).ready(function() {
// On submit
$('.myForm').on('submit', function(e) {
e.preventDefault(); // Prevent default submit
var $this = $(this);
// Getting values
var name = $('#nom').val();
var fname = $('#prenom').val();
var objet = $('#objet').val();
var mail = $('#email').val();
var msg = $('#msg').val();
// Looking for errors
if(name === '' || fname === '' || objet === '' || mail === '' || msg === '') {
alert('Les champs doivent êtres remplis');
} else {
// Sending Ajax query
$.ajax({
url: $this.attr('action'), // form's action
type: $this.attr('method'), // form's method
data: $this.serialize(), // Serializing data
success: function(html) { // php's file response
alert(html); // Print the result
}
});
}
});
});
And my php file:
session_start();
if(isset($_GET['err']))
{
$reponse = 'Mail not sent corretly!';
echo json_encode(['reponse' => $reponse]);
echo 'An error occurred, please try again
<form .... /form>'; //Same form
}
if(isset($_POST["captcha"]) && $_POST["captcha"]!="" && $_SESSION["captcha"]==$_POST["captcha"])
{
if(isset($_POST["nom"]))
{
if(preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['nom']))
{
if(isset($_POST["prenom"]))
{
if (preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['prenom']))
{
if(isset($_POST["objet"]))
{
if (preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['objet']))
{
if(isset($_POST["email"]))
{
if (preg_match("/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/",$_POST['email']))
{
$passage_ligne = "\r\n";
$emailAdmin = 'benjamin#parisbeaute.fr';
// Subject
$subject = $_POST['objet'];
// Headers
$headers = 'FROM: "'.$_POST['nom'].' '.$_POST['prenom'].'" <'.$_POST['email'].'>'.$passage_ligne;
$headers .= 'MIME-Version: 1.0'.$passage_ligne;
$headers .= 'Content-type: text/html; charset=UTF-8'.$passage_ligne;
$message = $_POST['message'];
// Formulaire
// Fonction mail()
mail($emailAdmin, $subject, $message, $headers);
echo '<div>Thanks a lot !</div>';
$reponse = 'Mail sent corretly!';
echo json_encode(['reponse' => $reponse]);
}}}}}}}}}
?>
Thanks in advance, sorry for my poor English, it's not my native language as you can see in my code.
Not sure why it did't work, but If you want sending the data using the $.ajax request, then stick to click event. Try change the code into this :
$(document).ready(function() {
// On button click
$('#my_button').on('click', function(e) {
var $this = $('.myForm');
// Getting values
var name = $('#nom').val();
var fname = $('#prenom').val();
var objet = $('#objet').val();
var mail = $('#email').val();
var msg = $('#msg').val();
// Looking for errors
if(name === '' || fname === '' || objet === '' || mail === '' || msg === '') {
alert('Les champs doivent êtres remplis');
} else {
// Sending Ajax query
$.ajax({
url: $this.attr('action'), // form's action
type: $this.attr('method'), // form's method
data: $this.serialize(), // Serializing data
success: function(html) { // php's file response
alert(html); // Print the result
}
});
}
});
});
And change button type into :
<button type="button" class="btn btn-default" id="my_button">Submit</button>

Categories

Resources