POST Request doesnt get received - php

So I have this form to add a person to a database:
<div id="formDiv">
<form id="form1" method="post" action="#">
<input type="text" name="title" placeholder="Title">
<br>
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="group" placeholder="Group">
<br>
<input type="text" name="company" placeholder="Company">
<br>
<select name="sex" required>
<option value="" disabled selected>Sex/option>
<option value="male">male</option>
<option value="female">female</option>
</select>
<br>
<button type="submit" id="insert" name="insert">Insert</button>
</form>
</div>
And a php File that handles inserting the data into the database:
<?php
include($_SERVER['DOCUMENT_ROOT'].'/website/dbConnection.php');
include($_SERVER['DOCUMENT_ROOT'].'/website/administrator/components/com_backend/backend.php');
if(isset($_POST['insert'])){
$title = $_POST['title'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$group = $_POST['group'];
$company = $_POST['company'];
$sex = $_POST['sex'];
if ($sex == "male"){
$sex = 0;
}
else{
$sex = 1;
}
$query = "INSERT INTO members (Title, Firstname, Lastname, Group, Company, Sex)
VALUES('$title', '$firstname', '$lastname', '$group', '$company', '$sex')";
mysqli_query($GLOBALS['connect'], $query);
}
I know that theres a problem between the 2 files communicating. Because the 2nd File does not receive the POST from the 1st file.
When I use the first file and press the submit Button, it reloads the page and enters nothing into the database.
When I navigate directly to the 2nd file, I can use the form since I include the first file. So I fill out the form, press the submit button and like magic, it works there!
I have checked the path, when including the 1st file 100 times. Its correct. I have checked the path when including the databse connection 100 times. Its correct. I have run the query directly in my database. Its correct.
I am assuming that I made a small mistake, that I cant spot, but the code is so small and simple thats just impossible.

<form id="form1" method="post" action="your_php_file.php">
This will point to your php file and proceed the POST request from your front-end to the back-end. According to your code you don't send anything to your php file. So the code you have there may work but your request is never made to your php file, so nothing is put inside the database.
Edit
In order not to reload the page as you requested then you shouldn't submit the form but you must make an ajax call to the backend side.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<div id="formDiv">
<input type="text" name="title" placeholder="Title">
<br>
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="group" placeholder="Group">
<br>
<input type="text" name="company" placeholder="Company">
<br>
<select name="sex" required>
<option value="" disabled selected>Sex/option>
<option value="male">male</option>
<option value="female">female</option>
</select>
<br>
<button type="button" id="insert" name="insert">Insert</button>
</div>
<script>
$( "#insert" ).click(function() {
let title = $("input[name=title]").val();
let firstname = $("input[name=firstname]").val();
let lastname = $("input[name=lastname]").val();
let group = $("input[name=group]").val();
let company = $("input[name=company]").val();
let sex = $("input[name=sex] option:selected").text();
$.ajax({
method: 'POST',
url: 'your_php_file.php',
data: {'title': title, 'firstname': firstname, 'lastname': lastname, 'group': group, 'company': company, 'sex': sex},
success: function (response) {
console.log(works)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
})
</script>
That way the data will be send to your backend and you can handle it the same like you did. It's in json format so don't forget to decode if needed.

<div id="formDiv">
<form id="form1" method="post" action="#">
<input type="text" name="title" placeholder="Title">
<br>
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="group" placeholder="Group">
<br>
<input type="text" name="company" placeholder="Company">
<br>
<select name="sex" required>
<option value="" disabled selected>Sex/option>
<option value="0">male</option>
<option value="1">female</option>
</select>
<br>
<button type="submit" id="insert" name="insert">Insert</button>
</form>
</div>
<script>
$('#form1').submit(function (e) {
e.preventDefault();
var senddata = $(this).serializeArray();
var sendto = $(this).attr("action");
$.ajax({
url: sendto,
type: 'POST',
data: senddata,
success: function (data) {
$('.messages').html(data);
},
error: function (error) {
$('.messages').html(error);
}
});
});
</script>

Related

data is updated on database but Ajax is not successful

I would like to update information on database. It is updated when i use this line of codes. Unfortunately it is telling me that my ajax is not successfull since it didnt proceed to success function. please help.
HTML CODE
<form class="EditEmployees" method="POST">
<span>Employee ID:</span><span id="employeeid"></span>
<span>First Name</span>
<input type="text" id="editfirstname" name="editfirstname" placeholder="" class="tb-style">
<span>Last Name</span>
<input type="text" id="editlastname" name="editlastname" placeholder="" class="tb-style">
<span class="label" for="">Gender</span>
<select class="tb-style" name="editgender" id="editgender">
<option>Please Select</option>
<option value = "male">Male</option>
<option value="female">Female</option>
</select>
<span class="label" for="dob">Date of Birth</span>
<input type="date" id="editdob" name="editdob" class="tb-style">
<div class='input-group date' id='datetimepicker1' >
<div class="input-group-addon">
<span class="label" for="dob">Date Hired</span>
<input type="date" id="editdatehired" name="editdatehired" class="tb-style">
<button type="" class="btn-EditSave w-100" name="">Save Changes</button>
</form>
JQuery code.
$('.btn-EditSave').click(function(){
// alert($('#editfirstname').val())
$.ajax({
url:'ajax.php',
data:{id:id,
type:'update-records-via-id',
FirstName:$('#editfirstname').val(),
LastName:$('#editlastname').val(),
dob:$('#editdob').val(),
datehired:$('#editdatehired').val(),
gender:$('#editgender').val()
},
dataType:'JSON',
type:'POST',
success: function(data){
alert("data saved")
}
})
})
PHP CODE: update data on database
function updaterecordviaid($id,$FirstName,$LastName,$gender,$dob,$datehired,$position){
$conn = mysqli_connect("localhost","root","","test");
$result = "update employees set FirstName = '$FirstName', LastName='$LastName', Gender = '$gender', DateOfBirth = '$dob', DateHired= '$datehired', PositionId='$position' where EmployeeId='$id'";
if(mysqli_query($conn,$result)){
echo json_encode(array('message'=>'Record Succesfully Updated!','FirstName'=>$FirstName,'LastName'=>$LastName));
return;
}
echo json_encode(array('message'=>'Something went wrong'));
return;
}

Send html form data to database through php without switching page

Hey guys so i have a form:
<form action="signup.php" method="post" class="cd-form">
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="First Name" name="primeiro_nome" />
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="Last Name" name="segundo_nome">
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="email" required maxlength="50" placeholder="E-mail" name="o_email">
</p>
<p class="fieldset">
<input class="full-width" type="submit" value="Sign Up!">
</p>
</form>
And you may notice that the action is calling "signup.php" :
<?php
$con=new mysqli ("localhost","root","","chroniclemark");
mysqli_set_charset($con, 'utf8mb4');
if($con->connect_error)
{
echo $con->connect_errno;
die("Database Connection Failed");
}
if(($_POST['primeiro_nome']) != ""){
$sql = "INSERT INTO users (nome, sobrenome, email)
VALUES('{$con->real_escape_string($_POST['primeiro_nome'])}', '{$con->real_escape_string($_POST['segundo_nome'])}', '{$con->real_escape_string($_POST['o_email'])}')";
$insert = $con->query($sql);
}
?>
And this is working. The data from the form is getting inserted into my database. The problem i have is that the main page closes when the form is submitted and the "signup.php" page opens instead of it.
How do i fix this? I would very much like to have a "Thank you for signing up" popping up on the same page instead of it switching to another one.
You can use AJAX to save data to database and show user a message in same page. Clicking on button a request is sent to server, data is saved into database, on success or failure a response is returned then show a message to user.
Form
First Give ids to input types in you form and add a message div.
<form method="post" class="cd-form">
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="First Name" id="primeiro_nome" />
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="Last Name" id="segundo_nome">
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="email" required maxlength="50" placeholder="E-mail" id="o_email">
</p>
<p class="fieldset">
<input class="full-width" id='saverecords' type="button" value="Sign Up!">
</p>
jQuery Code to send AJAX request to server
Add a script tag include jQuery and inside click event get values of fields and then post to php page:
<script src=”http://code.jquery.com/jquery-3.1.1.min.js”></script>
<script type=”text/javascript”>
$(function(){
$("#saverecords").on('click', function(){
var pnome = $("#primeiro_nome").val();
var sname = $("#segundo_nome").val();
var email = $("#o_email").val();
$.ajax({
method: "POST",
url: "saverecords.php",
data: {"pname": pname, "sname": sname, "email": email},
}).done(function( data ) {
var result = $.parseJSON(data);
var str = '';
if(result == 1) {
str = 'Signup successfull.';
}else{
str = 'Data could not be saved. Please try again';
}
$("#message").html(str);
});
});
</script>
php server side code:
Please change it according to your requirement
Create a php page: saverecords.php
In saverecords.php you can insert data into database.
$conn = new mysqli($host, $username, $password, $dbname);
$pname = $_POST['pname'];
$sname = $_POST['sname'];
$email = $_POST['email'];
$sql = "insert into tablename (pname, sname, email) values (?, ?, ?) ";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sss', $pname, $sname, $email);
if($stmt->execute()){
$result = 1;
}
}
echo $result;
$conn->close();
If you still face issue please visit this link you can find a detailed tutorial on how to use jQuery Ajax with php mysqli
You have to use AJAX instead of directly submitting the form
You send POST request with JS XMLHttpRequest or Fetch_API to signup.php, get the response and show the "Thank you for signing up" popup
There are mainly two ways you can do this.
1. You can use Jquery $.ajax method to send data, get a response and display your message.
2. Or you can simply let the php page it self do the processing. Add a submit button.
Change your <form action="signup.php" method="post" class="cd-form">to
<form action="" method="post" class="cd-form">
Add below after the form.
<?php
if (isset($_POST["submit"]){
//do your processing here
//at the end of processing you can use echo or HTML to display a thank you message
}
?>
You can make action page run inside an iframe so your form page remains on top
just like that:
<form action="signup.php" method="post" class="cd-form" target="my_iframe">
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="First Name" name="primeiro_nome" />
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="text" required maxlength="15" placeholder="Last Name" name="segundo_nome">
</p>
<p class="fieldset">
<input class="full-width has-padding has-border" type="email" required maxlength="50" placeholder="E-mail" name="o_email">
</p>
<p class="fieldset">
<input class="full-width" type="submit" value="Sign Up!">
</p>
</form>
<iframe id="my_iframe" name="my_iframe" style="display:none"></iframe>
Also you can send form data to your PHP page by using jquery:
$(document).on('submit','.cd-form',function(e){
e.preventDefault();
$.ajax( {
url: "signup.php",
type: 'POST',
data: new FormData( this ),
cache: false,
dataType: "json",
success: function(r){
alert("data sent successfully");
}
} );
} );

AJAX code not updating table

Here is my form, from which i want to update the values. When i try this with simple php+html it works perfectly!! But when i try to post values through ajax call it doesn't work.Any suggestions please.
HTML
<form class="form-block" role="form" action="" method="post">
<div class="form-group">
<?php
$email=$_SESSION["login_email"];
$query=mysqli_query($con,"select * from customers where email='$email'");
while($row=mysqli_fetch_array($query,MYSQLI_ASSOC))
{
?>
<label for="name">Full Name</label>
<input type="text" name="name" class="form-control" id="name" value="<?= $row["name"]; ?>" placeholder="Full Name">
<label for="comment">Address</label>
<textarea class="form-control" name="address" id="address" rows="5" id="comment" ></textarea>
<label for="telephone">Telephone</label>
<input type="tel" class="form-control" name="phone" id="phone" placeholder="Enter Mobile Number" value="" >
<label for="city">City</label>
<input type="text" class="form-control" name="city" id="city" placeholder="Enter City" value="<?= $row["city"]; ?>" >
</div>
<?php
}?>
<input type="submit" class="btn btn-default" name="add" id="add" value="Update"/>
<span class='msg'></span>
<div id="error"></div>
</form>
AJAX
$(document).ready(function() {
$('#add').click(function()
{
$.ajax({
url: "address_update.php",
type: "POST",
async: true,
data: { Name:$("#name").val(),Address:$("#address").val(), Phone:$("#phone").val(), City:$("#city").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
if(data)
{
//$('#output').html(data);
$("body").load("index.php?page=form");//.hide();//.fadeIn(1500).delay(6000);
}
else
{
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}}});
});});
PHP
<?php
include ("db/db.php");
session_start();
$name=$_POST['Name'];
$address=$_POST['Address'];
$phone=$_POST['Phone'];
$city=$_POST['City'];
$email=$_SESSION['login_email'];
$sql=mysqli_query($con,"Update customers set name='$name',address='$address',phone='$phone',city='$city' where email='$email'");
if($sql)
{
echo "updated";
}
This selector:
$('#add')
doesn't find anything. Because there is no HTML element in your markup with id="add".
You do have an element with name="add". So either add an id to that element:
<input id="add" type="submit" class="btn btn-default" name="add" value="Update"/>
or change your selector to target the existing element:
$('input[name="add"]')
Note: The same is also true of $('#address') and $('#phone'). No such elements exist in your markup. Take a look at the jQuery documentation for selectors.
Remove the IF loop mentioned under
if(isset($_SESSION["login_email"]))
Additionally, you nee to change the button type from submit to button
<input type="submit" class="btn btn-default" name="add" value="Update"/>
Above sends the form, whatever you add to the click event is done in parralel.
<input type="button" class="btn btn-default" name="add" value="Update"/>
only executes your JavaScript, when using:
$('input [name="add"]').click(function(){
// your improved ajax call here
}
Try this:
$.ajax({
.
.
data: {
'Name': $name,
'address': $address,
.
.
}
});

Using jQuery ajax to upload file and form data with formData()

I want upload a file with jquery ajax and php using forData() with this code:
var data = new FormData();
data.append('image',document.getElementById('uFile').files[0]);
data.append('tag','saveDocument');
data.append('data',$('#saveDocument').serializeArray());
$.ajax({
url: url,
type: 'post',
data: data,
cache: false,
contentType:false,
dataType: 'json',
processData: false,
success: function (data) {
setAlert("Documento guardado correctamente!",success);
}, error: function() {
setAlert("Ha ocurrido un error al guardar!",error);
}
});
return false;
This line contains all data of fields in my form:
data.append('data',$('#saveDocument').serializeArray());
But in PHP I can't access to that data and I want access to data of form to insert on a table, do you know what's the problem?
Html Form
<form id="saveDocument" enctype="multipart/form-data" method="post">
<p><i>Todos los campos son requeridos!</i></p>
<p>
<input id="uName" class="uName span5" name="uName" type="text" placeholder="Nombre completo" required/>
</p>
<p>
<input id="uEmail" class="uEmail span5" name="uEmail" type="email" placeholder="E-mail" required/>
</p>
<p>
<select id="uDept" class="uDept span5" name="uDept" type="text" required>
<option value="0">Seleccione departamento</option>
<option value="1">Dirección</option>
<option value="2">Recursos Humanos</option>
<option value="3">Oficina</option>
</select>
</p>
<p>
<input id="uIssue" class="uIssue span5" name="uIssue" type="text" placeholder="Asunto" required/>
</p>
<p>
<textarea id="uComment" class="uComment" name="uComment" placeholder="Comentario (Máximo 30 caracteres)" required></textarea>
</p>
<p>
<select id="uUrgency" class="uUrgency span5" name="uUrgency" type="text" required>
<option value="0">Seleccione urgencia</option>
<option value="1">Normal</option>
<option value="2">Alta</option>
<option value="3">Urgente</option>
</select>
</p>
<p>
<input id="uFile" class="uFile span5" name="uFile" type="file" required/>
<input id="nameFile" class="nameFile span5" name="nameFile" type="text" placeholder="Click para seleccionar el archivo" onClick="$('.uFile').click();"/>
</p>
<p>
<input class="btn btn-danger" type="reset" value="Limpiar"/>
<input id="sendFile" class="btn btn-primary" type="submit" value="Guardar"/>
</p>
The below image is taken from developers tool of chrome:
You can pretty easy. Take a look at these posts:
specially for images with demo
just all file type uploads with validation

Jquery .serialize() not processing value of dropdown list?

I think this should be a simple thing but for some reason all my form values are being serialized fine except for the selected value of the dropdown list, the form is below:
<form id="contactform">
<label for="name">Name</label>
<input type="text" id=name name=name placeholder="First and last name" tabindex="1" />
<label for="phonenumber">Phone Number</label>
<input type="text" id=phonenumber name=phonenumber placeholder="Please enter your phone number" tabindex="2" />
<label for="email">Email</label>
<input type="text" id=email name=email placeholder="example#domain.com" tabindex="3" />
<label for="dropdown">Please Confirm:</label>
<select>
<option value="question" selected="selected">I have a question</option>
<option value="attending">I am attending</option>
<option value="not-attending">I am not attending</option>
</select>
<label for="comment">Your Message</label>
<textarea name="comment" id=comment name=comment placeholder="Enter something here, can't think" tabindex="5"></textarea>
<input name="submit" type="submit" id="submit" tabindex="6" value="Send Message"/>
</form>
and this is how I am serializing it:
$('#contactform').submit(function() {
var query = $(this).serialize();
$.ajax({
type: "POST",
url: "send.php",
data: query,
success: function(data) { // rest of function
and finally the bit of PHP I'm using to set the value as a variable is:
$dropdown = $_POST['dropdown'];
AN example header is name=sgrggr&phonenumber=55555555555&email=me%40me.com&comment=quick+test so I'm stuck as to why the dropdown value isn't being picked up.
Thanks for your help.
Your dropdownlist needs a name attribute to be included by the submit.
<select name="dropdown">
<option value="question" selected="selected">I have a question</option>
<option value="attending">I am attending</option>
<option value="not-attending">I am not attending</option>
</select>
hope this helps!
I was facing the similar situation. SELECT tag has an attribute named form. Define the form="#ID_OF_THE_FORM_YOU_WANT_YOUR_SELECT_TO_ATTACH_TO". Don't forget to define an ID for your FORM as well.

Categories