In my eagerness to continue with my project, I am learning how to use jQuery and Ajax to send the data. In this case, I am trying to send the data from a form by Ajax to a php script, which inserts everything into the database and then returns the inserted data as a response to be able to fill another part of the page with that data entered.
What I am doing is:
<?php
// First of all, we must check if the session exists
session_start();
$response = array();
if(isset($_SESSION["addingResume"]["resumeId"])){
// TODO modify data
modifyAddingInitialData($_SESSION["addingResume"]["resumeId"]);
}else{
addInitialResumeData();
}
function modifyAddingInitialData($resumeId){
unset($_SESSION["addingResume"]["resumeId"]);
}
function addInitialResumeData(){
// In this case, we will create
// Create a new Resume
include('dbConfig.php');
$sql = $mysqli->prepare("INSERT INTO `cv` (`id`, `name`, `firstSurname`, `secondSurname`,
`phone`, `secondPhone`, `address`, `mail`,`birthdate`)
VALUES(NULL,?,?,?,?,?,?,?,?);");
if(!(empty($_POST["cvName"]) && empty($_POST["surname1"]) && empty($_POST["phone1"])
&& empty($_POST["cvMail"]) && empty($_POST["birthdate"]))){
// Check now if we have extra data
$name = $_POST["cvName"];
$surname1 = $_POST["surname1"];
$phone1 = $_POST["phone1"];
$cvMail = $_POST["cvMail"];
$surname2 = " ";
$phone2 = " ";
$address = " ";
$birthdate = $_POST["birthdate"];
if(!empty($_POST["surname2"])){
$surname2 = $_POST["surname2"];
}
if(!empty($_POST["phone2"])){
$phone2 = $_POST["surname2"];
}
if(!empty($_POST["address"])){
$address = $_POST["surname2"];
}
// Preparing the sql
if ($sql == false) {
$response["status"] = "Error while trying to create the SQL";
}
$result = $sql->bind_param("ssssssss", $name, $surname1,$surname2, $phone1,$phone2,$address,$cvMail, $birthdate);
if ($result == false) {
$response["status"] = "Error while trying to create the SQL";
}
$result = $sql->execute();
if ($result == false) {
$response["status"] = "Error while trying to execute the SQL";
}else{
// All worked fine
$lastid = mysqli_insert_id($mysqli);
$_SESSION["addingResume"]["resumeId"] = $lastid;
showModifiedForm($lastid);
}
}else{
$response["status"] = "Error while trying recieve the data";
}
$mysqli->close();
}
function showModifiedForm($formId){
include('dbConfig.php');
if($_SESSION["addingResume"]["resumeId"] === $formId){
// Obtain data
$sql = "SELECT `name`, `firstSurname`,`SecondSurname`,
`phone`,`secondPhone`,`address`,`mail`,`birthdate`
FROM cv WHERE id = '$formId'";
if($result = $mysqli->query($sql)){
if($row = $result->fetch_assoc()){
// Return all data in a json
$response["status"] = "ok";
$response["body"] = $row;
header('Content-type: application/json; charset=utf-8');
print_r(json_encode($response));
}
}else{
$response["status"] = "Failure at creating SQL";
}
}
$mysqli->close();
}
?>
This php script that will do a json_encode as response
$(document).ready(function() {
$('#initialFormError').fadeOut();
$('form[id=\'initialCVDataForm\']').on('submit', function(e) {
e.preventDefault();
$("#initialFormError").fadeOut();
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: '../php/initialCVDataFormProcess.php',
data: data,
dataType: 'json',
beforeSend: function() {
$('#initialFormError').fadeOut();
$('#btnSaveInitialData').html('Saving ...');
},
success: function(response) {
if (response["status"] === 'ok') {
$('#btnSaveInitialData').html('Save data');
$('#cvName').val(response.name);
$('#aditionalCVDataForm').show();
setTimeout(' window.location.href = "../models/addResume.php#aditionalCVDataForm"; ', 3000);
} else {
$('#initialFormError').fadeIn(1000, function() {
$('#initialFormError').html(response['status']);
$('#btnSaveInitialData').html('Save data');
});
}
},
});
return false;
});
});
and it will be sent to the above script to be used.
My idea was to create an array which had the status and on the other hand the body, which would then be encoded to json but I don't understand how I can return the json object by Ajax or how to manipulate it.
edit:
The purpose is to be able to use the data returned by jSon to display the data obtained from the database in the value of the form.
On the other hand, from what I read in the answers, it shouldn't show multiple outputs.
After displaying a single output, the button stays on Sending... (sends the data to the DB) but the response does not arrive.
edited
After looking at the code again, it seems that I had some programming errors that I have resolved.
The issue now is that the response is sent (sometimes I have to double click the button for it to take effect) but the form control loses its value as soon as I try to assign a new one to it.
Code of the form in question:
<form id="initialCVDataForm" method="post">
<div class="formDataContainer">
<div class="personalDataCategory"><h2 class="categoryTitle">Initial data</h4>
<div id="initialFormError"><!-- Error will be shown here ! --></div>
<label for="cvName"><span class="labelText">Name</span></label>
<input type="text" id="cvName" placeholder="Name" name="cvName" minlength="2" maxlength="100" required value=''>
<label for="surname1"><span class="labelText">Surname 1</span></label>
<input type="text" class='formInputLeft' placeholder="Surname 1" name="surname1" minlength="2" maxlength="100" required value=''>
<label for="surname2"><span class="labelText">Surname 2</span></label>
<input type="text" placeholder="Surname 2" name="surname2" minlength="2" maxlength="100" value=''>
<label for="phone1"><span class="labelText">Phone number</span></label>
<input type="number" placeholder="phone" name="phone1" minlength="2" required value=''>
<label for="phone2"><span class="labelText">Phone number 2</span></label>
<input type="number" placeholder="phone" name="phone2" minlength="2" autocapitalize="off" value=''>
<label for="address"><span class="labelText">Address</span></label>
<input type="text" placeholder="address" name="address" minlength="10" maxlength="300" autocapitalize="off" value=''>
<label for="cvMail"><span class="labelText">Email</span></label>
<input type="email" placeholder="Enter email" id="cvMail" name="cvMail" autocapitalize="off" required value=''>
<label for="birthdate"><span class="labelText">Birthdate</span></label>
<input type="date" id="birthdate" name="birthdate" required value=''>
<button id="btnCancel" name="btnReturnHomeInitialDataForm" onclick="location.href = 'userPanel.php';">Return to home</button>
<button type="submit" id="btnSaveInitialData" name="btnSaveInitialData">Save data</button>
</div>
</form>
Thanks for everything.
An example of receiving data from a php in JSON format is this:
An example of sending data is this:
Receive php data: