Ajax form isn't submitted correctly - javascript

I am having this next issue with an Ajax form which is not submitted correctly.
I have 3 forms, one for desktop, one for mobile, and a form which is located inside a modal.
The first form for desktop version works perfectly and registers all data that I need through Cakephp.
The second one, which is for the mobile version displays an error which is coming from a function I developed for error handling with Jquery.
Both the mobile-version form and the modal form are appearing to have the same problem.
I send the query through ajax, but the problem persists in displaying the same error.
This is the Jquery code for the form which is working correctly.
$('#nueva_normalidad_form').on('submit', function(e){
e.preventDefault();
$('#errorMain').html('');
var formContainer = $('#form_container');
var errorArea = $('#errorMain');
if(!validateDocApplication(errorArea)){
return;
}
var data = $('#nueva_normalidad_form').serialize();
var beforeSend = function () {
$('#sendDataButton').attr("disabled", true);
};
var error = function (a) {
$('#errorMain').html('<div class="alert alert-danger">' + info.txt + '</div>');
return a;
};
var success = function(info) {
info = $.parseJSON(info);
if (info.id === 200) {
formContainer.animate({
display: "none"
}, {
duration: 600,
complete: function () {
formContainer.css("display", "none");
$('div#successText').css("display", "block");
}
});
$('#successText').animate({
display: "block"
}, {duration: 700,
complete: function () {
$('#successText').css("display", "block");
}
});
dataLayer.push({'eventcategory': 'Conversion', 'event': 'submitForm'});
} else {
$('#errorMain').html('<div class="alert alert-danger">' + error.txt + '</div>');
}
};
saveNewNormDoctor(data, beforeSend, success, error);
});
This is the function for the error handling of the field inputs.
//Validates the field inputs of Desktop Form
function validateDocApplication(errorArea) {
var noError = true;
if(!$('input[name="name"]').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el nombre</div>');
noError = false;
}
if(!$('input[name="surname"]').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el apellido</div>');
noError = false;
}
if(!$('input[name="email"]').val()){
noError = false;
errorArea.html('<div class="alert alert-danger">Por favor, inserte su correo</div>');
}else{
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
noError = re.test($('input[name="email"]').val());
}
if(!$('input[name="phone"]').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de teléfono</div>');
noError = false;
}
if(!$('input[name="colegiado"]').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de colegiado</div>');
noError = false;
}
var valorSpec = $('#spec option:selected').val();
if(!valorSpec){
errorArea.html('<div class="alert alert-danger">Seleccione una especialidad</div>');
noError = false;
}
return noError;
}
This is the function which sends the request and saves the data to the database.
function saveNewNormDoctor(data, beforeSend, success, error) {
$.ajax({
type: "POST",
url: "/staticpages/save_doc_new_norm",
data: data,
beforeSend: beforeSend,
success: success,
error: error
});
}
For my modal-version form I am using this submit function:
$('#sendDataNewNorm').on('submit', function (e) {
e.preventDefault();
$('#errorModal').html('');
var errorArea = $('#errorModal');
var formContainer = $('#formNewnorm');
var successArea = $('#successTextModal');
if(!validateDocApplication(errorArea)){
return;
}
var data = $('#sendDataNewNorm').serialize();
var beforeSend = function () {
$('#sendDataNewNormButton').attr("disabled", true);
};
var error = function (a) {
errorArea.html('<div class="alert alert-danger">' + info.txt + '</div>');
return a;
};
var success = function (info) {
info = $.parseJSON(info);
if (info.id === 200) {
formContainer.animate({
display: "none"
}, {
duration: 600,
complete: function () {
formContainer.css("display", "none");
successArea.css("display", "block");
}
});
successArea.animate({
display: "block"
}, {duration: 700,
complete: function () {
successArea.css("display", "block");
}
});
} else {
errorArea.html('<div class="alert alert-danger">' + info.txt + '</div>');
}
};
saveNewNormDoctor(data, beforeSend, success, error);
});
All inputs in 3 forms have the same name attributes such as name, surname, email,phone, colegiado and the value that it gets through the #spec select element.
This is the HTML markup of my modal's form. The same thing occurs in my mobile-version form.
I am at a dead-end. My Cakephp function for the server-side process is correct as my main form is being submitted correctly. Any hint on how to resolve the problem would be appreciating. The error is this one. While in the other form I always get all values correctly, in this ones, every one of these values come up empty.
errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de colegiado</div>');
Thanks you.
<form id="sendDataNewNorm">
<div class="text-centers">
<h4 class="h4 font_Conv_Roboto-Regular text-center top_margin">
<?= __('Rellene el siguiente formulario <br>y nos pondremos en contacto con usted.'); ?>
</h4>
</div>
<div id="formNewnorm" class="bottom_margin">
<div class="col-md-12 col-sm-12 form-group top_margin no_side_paddings">
<div class="col-sm-6 col-md-6 no_padding_left">
<input name="name" id="name" class="desesc form-control" type="text" placeholder="<?= __('Nombre'); ?> *">
</div>
<div class="col-sm-6 col-md-6 no_side_paddings">
<input name="surname" id="surname" class="desesc form-control" type="text" placeholder="<?= __('Apellidos'); ?> *">
</div>
</div>
<div class="form-group">
<input name="email" id="email" class="desesc form-control" type="email" placeholder="<?= __('e-mail');?> *">
</div>
<div class="form-group">
<input name="phone" id="tel" class="desesc form-control" type="number" placeholder="<?= __('Número de contacto');?> *">
</div>
<div class="form-group">
<select class="desesc form-control" name="especialidad" id="spec">
<option value="0"><?= __('Seleccione su especialidad'); ?></option>
<?php foreach ($specs AS $k => $v) { ?>
<option value="<?= $k; ?>"><?= $v; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<input name="colegiado" id="collegiate" class="desesc form-control" type="text" placeholder="<?= __('Número de colegiado'); ?> *">
</div>
<div class="form-group">
<div class="radio radio_highlight">
<input type="radio" name="condiciones" id="condiciones_1" value="1" required="">
<label class="text-primary" for="condiciones_1">
<?= __('He leído y acepto las');?> <a target="_blank" href="http://topdoctors.local/terminos-legales">
<u><?= __('Condiciones de Uso'); ?></u></a>
</label>
</div>
<input type="hidden" name="created" value="<?php echo date('Y-m-d'); ?>" >
</div>
<div class="form-group">
<div id="errorModal"></div>
<button id="sendDataButton" class="btn btn-block btn-primary btn_md">
<?= __('Solicitar información'); ?>
</button>
</div>
</div>
<div id="successTextModal" class="top_margin_md bottom_margin_md top_padding_md bottom_padding bg_light text-center" style="display:none;">
<img class="top_padding_md img-responsive" src="/css/quironsalud/check.png" style="margin: 0 auto" />
<div class="box-success top_padding_md bottom_padding_md">
<span class="top_margin text-success font_Conv_Roboto-Regular ">
<?= __('Tu solicitud ha sido enviada correctamente'); ?>
</span>
</div>
</div>
</form>

Finally, I found the solution to my problem.
By assigning new ids for every input field which I needed, I came to this function:
function validateDocApplicationForm(errorArea) {
var noError = true;
if(!$('#name_form').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el nombre</div>');
noError = false;
} else {
name = $('#name_form').val();
return name;
}
if(!$('#surname_form').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el apellido</div>');
noError = false;
} else {
surname = $('#surname_form').val();
return surname;
}
if(!$('#email_form').val()){
noError = false;
errorArea.html('<div class="alert alert-danger">Por favor, inserte su correo</div>');
} else {
email = $('#email_form').val();
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
noError = re.test(email);
return email;
}
if(!$('#tel_form ').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de teléfono</div>');
noError = false;
}else {
phone = $('#tel_form').val();
return phone;
}
if(!$('#collegiate_form').val()){
errorArea.html('<div class="alert alert-danger">Por favor, inserte el número de colegiado</div>');
noError = false;
} else {
colegiado = $('#collegiate_form').val();
return colegiado;
}
var valorSpec = $('#spec_form option:selected').val();
if(!valorSpec){
errorArea.html('<div class="alert alert-danger">Seleccione una especialidad</div>');
noError = false;
}
return noError;
}
The changes I had to make on my markup were these:
<div id="formNewnorm" class="bottom_margin">
<div class="col-md-12 col-sm-12 form-group top_margin no_side_paddings">
<div class="col-sm-6 col-md-6 no_padding_left">
<input name="name" id="name_form" class="desesc form-control" type="text" placeholder="<?= __('Nombre'); ?> *">
</div>
<div class="col-sm-6 col-md-6 no_side_paddings">
<input name="surname" id="surname_form" class="desesc form-control" type="text" placeholder="<?= __('Apellidos'); ?> *">
</div>
</div>
<div class="form-group">
<input name="email" id="email_form" class="desesc form-control" type="email" placeholder="<?= __('e-mail');?> *">
</div>
<div class="form-group">
<input name="phone" id="tel_form" class="desesc form-control" type="number" placeholder="<?= __('Número de contacto');?> *">
</div>
<div class="form-group">
<select class="desesc form-control" name="especialidad" id="spec_form">
<option value="0"><?= __('Seleccione su especialidad'); ?></option>
<?php foreach ($specs AS $k => $v) { ?>
<option value="<?= $k; ?>"><?= $v; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<input name="colegiado" id="collegiate_form" class="desesc form-control" type="number" placeholder="<?= __('Número de colegiado'); ?> *">
</div>
<div class="form-group">
<div class="radio radio_highlight">
<input type="radio" name="condiciones_form" id="condiciones_form" value="1" required="">
<label class="text-primary" for="condiciones_form">
<?= __('He leído y acepto las');?> <a target="_blank" href="http://topdoctors.local/terminos-legales">
<u><?= __('Condiciones de Uso'); ?></u></a>
</label>
</div>
<input type="hidden" name="created" value="<?php echo date('Y-m-d H:i:s'); ?>" >
</div>
<div class="form-group">
<div id="errorModal"></div>
<button id="sendDataButton" class="btn btn-block btn-primary btn_md">
<?= __('Solicitar información'); ?>
</button>
</div>
</div>
With this approach, I was able to re-assign the values to every input with each respective name and new id. Therefore passing the new values through the ajax request, I was able to register my data to the database.

Related

Why do I have no client-side response after my Ajax request?

I am working on sending data from a form in ajax with a return of an alert box in case of success or failure.
I already made a topic because my data in $ _POST did not seem to be sent to my php script and the Ajax request did not work. Now the request is well recognized by the server as shown by the network panel :
datasent
I've also made a var_dump($_SERVER) and the $_SERVER['HTTP_X_REQUESTED_WITH'] value is "XML HTTPREQUEST" which indicates that the Ajax request has been launched. Now I have an other problem : I don't have a client-side response: currently the program seems to validate the condition if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') and I have an echo($encoded) in JSON format as shown below :
JSON echo php.
Therefore I should have a client-side response, which is not the case actually.
Here are my codes : the form
<form id="contactformpage">
<div class="messages"></div>
<div class="form-group row">
<label for="societepage" class="col-sm-6 col-form-label">Société</label>
<div class="col-sm-6 champ">
<input type="text" name="societe" class="form-control" id="societepage" placeholder="Nom de la société"
aria-describedby="indicsocietepage">
<small id="indicsociete" class="form-text text-muted"> * Obligatoire </small>
</div>
</div>
<div class="form-group row">
<label for="adressepage" class="col-sm-6 col-form-label">Adresse</label>
<div class="col-sm-6 champ">
<input type="text" name="adresse" class="form-control" id="adressepage" placeholder="Adresse">
</div>
</div>
<div class="form-group row">
<label for="codepostaletvillepage" class="col-sm-6 col-form-label">Code postal & ville</label>
<div class="col-sm-6 champ">
<input type="text" class="form-control" name="codepostaletville" id="codepostaletvillepage"
placeholder="Code postal & ville">
</div>
</div>
<div class="form-group row">
<label for="contactpage" class="col-sm-6 col-form-label">Nom du contact</label>
<div class="col-sm-6 champ">
<input type="text" class="form-control" name="contact" id="contactpage" placeholder="Nom du contact">
</div>
</div>
<div class="form-group row">
<label for="telephonepage" class="col-sm-6 col-form-label">Téléphone</label>
<div class="col-sm-6 champ">
<input type="text" class="form-control" name="téléphone" id="telephonepage" placeholder="Numéro de téléphone"
aria-describedby="indictelephonepage">
<small id="indictelephonepage" class="form-text text-muted"> * Obligatoire </small>
</div>
</div>
<div class="form-group row">
<label for="mailpage" class="col-sm-6 col-form-label">Adresse mail</label>
<div class="col-sm-6 champ">
<input type="email" class="form-control" name="mail" id="mailpage" placeholder="Entrez votre adresse mail"
aria-describedby="indicmailpage">
<small id="indicmailpage" class="form-text text-muted"> * Obligatoire </small>
</div>
</div>
<div class="form-group row">
<label class="col-sm-6 col-form-label" for="selecmarque" aria-describedby="indicmarquepage"> Marque du véhicule
</label>
<div class="col-sm-6 champ">
<select class="form-control" name="marque" style="height:20px;padding-bottom:0;padding-top:1;"
onchange="generechoixmodele('selecmarque','apreschoixmarquepage','apreschoixmodelepage','nommodelepage','choixmodelepage','choixtypepage');"
id="selecmarque">
<option selected> Séléctionnez </option>
</select>
</div>
</div>
<div class="form-group row" id="apreschoixmarquepage" style="display:none;">
<!-- Liste déroulante qui apparait après le choix de la marque -->
<label class="col-sm-6 col-form-label" for="apreschoixmarquepage" aria-describedby="indicmarque"
id="nommodelepage"></label>
<div class="col-sm-6 champ">
<select class="form-control" name="modele" style="height:20px;padding-bottom:0;padding-top:1;"
id="choixmodelepage"
onchange="generechoixtype('selecmarque','choixmodelepage','apreschoixmodelepage','nomtypepage','choixtypepage');">
</select>
</div>
</div>
<div class="form-group row" id="apreschoixmodelepage" style="display:none;">
<!-- Liste déroulante qui apparait après le choix du modèle -->
<label class="col-sm-6 col-form-label" for="apreschoixmodelepage" aria-describedby="indicmarque"
id="nomtypepage"></label>
<div class="col-sm-6 champ">
<select class="form-control" name="type" style="height:20px;padding-bottom:0;padding-top:1;" id="choixtypepage">
</select>
</div>
</div>
<p> Je souhaite recevoir les catalogues suivants (dynamique)</p>
<div id="choixcataloguepage">
</div>
<div class="form-group row">
<label class="col-sm-6 col-form-label" for="commentairepage">Commentaire</label>
<div class="col-sm-6 champ">
<textarea class="form-control" name="commentaire" id="commentairepage" rows="1"></textarea>
</div>
</div>
<div class="form-group row">
<label for="mail" class="col-sm-6 col-form-label">Captcha</label>
<div class="col-sm-6 champ">
<h6> Captcha à rajouter après </h6>
</div>
</div>
<input type="submit" class="btn" id="submitpage">
</form>
My jQuery script :
$(document).ready(function(){
$("#submitpage").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: 'sendform.php',
data: {
societe : $("#societepage").val(),
adresse : $("#adressepage").val(),
codepostaletville : $("#codepostaletvillepage").val(),
contact : $("#contactpage").val(),
telephone : $("#telephonepage").val(),
mail : $("#mailpage").val(),
marqueclient : $("#selecmarque").val(),
modeleclient : $("#choixmodelepage").val(),
typeclient : $("#choixtypepage").val(),
commentaire : $("#commentairepage").val()
},
dataType: "json",
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contactformpage').find('.messages').html(alertBox);
// empty the form
$('#contactformpage')[0].reset();
}
}
})
});
});
And my PHP script that returns JSON data when the request has been done :
<?php
/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
AND ALSO SMTP TO SEND THE EMAILS
*/
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer/PHPMailer-master/src/Exception.php';
require 'PHPMailer/PHPMailer-master/src/SMTP.php';
require 'PHPMailer/PHPMailer-master/src/OAuth.php';
require 'PHPMailer/PHPMailer-master/src/POP3.php';
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$fromEmail = 'lyes.tifoun#hotmail.fr';
$fromName = 'Demo contact form';
// an email address that will receive the email with the output of the form
$sendToEmail = 'lyestfn#gmail.com';
$sendToName = 'Lyes Tifoun';
// subject of the email
$subject = 'New message from contact form';
// smtp credentials and server
$smtpHost = 'smtp.gmail.com';
$smtpUsername = 'nom_utilisateur';
$smtpPassword = 'mdp';
$fields = array('societe' => 'Société', 'adresse' => 'Adresse', 'codepostaletville' => 'Code postal et ville', 'contact' => 'Nom du contact', 'téléphone' => 'Numéro de téléphone', 'mail' => 'Adresse mail', 'marque' => 'Marque du véhicule', 'modele' => 'Modèle du véhicule', 'type' => 'Type du véhicule', 'commentaire' => 'Commentaire');
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
error_reporting(E_ALL & ~E_NOTICE);
try {
if (count($_POST) == 0) {
throw new \Exception('Form is empty');
}
$emailTextHtml = "<h1>You have a new message from your contact form</h1><hr>";
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
}
}
$emailTextHtml .= "</table><hr>";
$emailTextHtml .= "<p>Have a nice day,<br>Best,<br>Ondrej</p>";
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = gethostbyname($smtpHost);
$mail->Port = 587;
$mail->isHTML(true);
$mail->SMTPOptions = array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true));
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName); // you can add more addresses by simply adding another line with $mail->addAddress();
$mail->addReplyTo($from);
$mail->Subject = $subject;
$mail->Body = 'test'; //$emailTextHtml;
$mail->msgHTML($emailTextHtml); // this will also create a plain-text version of the HTML email, very handy
$mail->Debugoutput = 'html';
if (!$mail->send()) {
throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
} catch (\Exception $e) {
// $responseArray = array('type' => 'danger', 'message' => $errorMessage);
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
Thanks a lot for your responses and sorry for my bad english.

Send data-attribute ID in JS to PHP on same index page using ajax?

I am not sure how to word this title. Feel free to edit it.
Intro I am doing a datatables.net library server-side table using JSON and PHP. I am basically done except for the edit form.
My first problem was solved. I had a while loop instead of an if statement.
My second problem is now going to be transferring this Javascript code near before the AJAX call:
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
to here which is php:
$edit_id = $_POST['edit_id'];
They are both on the same page, index.php so I do not think I can use ajax for this.
Index.php
<script type="text/javascript">
$(document).on('click', '.edit_btn', function() {
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
$("#form2").show();
//console.log(edit_id[0]);
$.ajax({
type: 'POST',
url: 'edit.php',
data: {
edit_id: edit_id,
first_name: $("#edit2").val(),
last_name: $("#edit3").val(),
position: $("#edit4").val(),
updated: $("#edit5").val(),
},
success: function(data) {
alert(data);
if (data == 'EDIT_OK') {
alert("success");
} else {
// alert('something wrong');
}
}
})
});
</script>
<?php
$sql="select * from employees WHERE id=$edit_id";
$run_sql=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($run_sql)){
$per_id=$row[0];
$per_first=$row[1];
$per_last=$row[2];
$per_position=$row[3];
//$per_date=$row[4];
$per_updated=$row[5];
?>
<form id="form2" class="form-horizontal">
<label class="col-sm-4 control-label" for="txtid">ID</label>
<input id="edit1" type="text" class="form-control" name="txtid" value="<?php echo $per_id;?>" readonly>
<div class="form-group">
<label class="col-sm-4 control-label" id="edit2" for="txtname">First Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="txtname" name="txtname" value="<?php echo $per_first;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtsalary">Last Name</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit3" name="txtsalary" value="<?php echo $per_last;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Position</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit4" name="txtage" value="<?php echo $per_position;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Updated</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit5" name="txtage" value="<?php echo $per_updated;?>">
</div>
<button type="button" class="close" value="Cancel" data-dismiss="modal">×</button>
<button type="button" class="update" value="Update"></button>
</form>
edit.php
$edit_id = $_POST['edit_id'];
$stmt = $conn->prepare("UPDATE employees SET first_name=?, last_name=?, position=?, updated=? WHERE id=?");
$stmt->bind_param('ssssi', $_POST['first_name'], $_POST['last_name'], $_POST['position'], $_POST['updated'], $_POST['edit_id']);
$confirmUpdate = $stmt->execute();
if($confirmUpdate) {
echo "EDIT_OK";
}else {
trigger_error($conn->error, E_USER_ERROR);
return;
}
?>
I eventually figured it out:
<script type="text/javascript">
$(document).on('click','.edit_btn',function (){
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row( id ).data();
var edit_id = edit_id[0];
alert(edit_id);
$.ajax({
url: 'index.php',
data: { edit_id : edit_id },
contentType: 'application/json; charset=utf-8',
success: function(result) {
//alert(result);
}
});
});
</script>

Uncaught SyntaxError: Unexpected token C in JSON at position 0

This is my code for a form. I am asking user to input email and password and checking if user is registered or not. If he is registered then I alert success:
<form role="form" class="legacy-form" action="" method="POST" id="myform1">
<div class="col-xs-12 col-sm-6 col-md-6 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="email" name="email" id="loginemail" class="form-control" placeholder="Email Address" required>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="password" name="password" id="loginpassword" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="row" style="padding:15px">
<div class="col-xs-6 col-sm-3 col-md-3 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="submit" value="Log In" class="btn btn-primary" id="loginbtn">
</div>
</div>
<div class="col-xs-6 col-sm-3 col-md-3">
<div class="form-group">
<input type="submit" value="Cancel" class="btn btn-danger" data-dismiss="modal">
</div>
</div>
</div>
</form>
This is the php code wherein the connection is placed in another file 'init.php'
<?php
include('init.php');
if(isset($_POST))
{
$loginemail=$_POST["loginemail"];
$loginpassword=$_POST["loginpassword"];
$sql = "select count(*),fname from users where password='$loginpassword' and email='$loginemail'";
$result=mysqli_query($con,$sql);
if($result) {
$response =array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("Count"=>$row[0],"name"=>$row[1]));
}
echo json_encode(array("server_response"=>$response));
} else {
echo "error";
}
mysqli_close($con);
}
?>
this is my js file. On printing info in console I get Connection sucess{"server_response":[{"Count":"1","name":"sagar"}]}
$("#loginbtn").click(function(e) {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
check_for_user(loginemail, loginpassword);
function check_for_user(loginemail, loginpassword) {
console.log("in check_for_user");
var i = 0;
console.log(i);
i++;
var c = "";
var x = "1";
var user = "";
var formdata = {
loginemail: loginemail,
loginpassword: loginpassword
}
$.ajax({
url: 'getData.php',
type: "POST",
data: formdata,
dataType: 'text',
success: handle_success,
error: handle_error
});
function handle_success(info) {
console.log(info);
var obj = jQuery.parseJSON(info);
console.log(obj);
$(obj.server_response).each(info, function(index, value) {
user = value.name;
c = value.Count;
});
console.log(c);
console.log(user);
if (x == c) {
alert("Welcome");
//document.location='online.html';
} else {
alert("Enter valid username and password");
}
}
function handle_error() {
alert("error");
}
}
});
The flow of the code is like when the #loginbtn is clicked it posts loginemail and loginpassword on php and then it checks in database whether there is an identical entry in database, if yes it alerts "welcome". I have searched a lot on StackOverflow I found that it says there is error in either parsing JSON or in decoding it.
It looks like you are echoing "Connection success" in init.php although we can't see that.
A json response should have no other content in response ... just the json.

Custom AJAX form not working async

I have a contact from that uses PHP mailer that I have integrated into my Wordpress blog. The script sends emails no problem - the issue is that it does not work async so once the form is submitted I am taken to another page with the following text on it: {"message":"Your message was successfully submitted from PHP."}. The script works as expected when used outside of wordpress - I have no idea whats going on.
PHP
<?php
/**
* Sets error header and json error message response.
*
* #param String $messsage error message of response
* #return void
*/
function errorResponse ($messsage) {
header('HTTP/1.1 500 Internal Server Error');
die(json_encode(array('message' => $messsage)));
}
/**
* Pulls posted values for all fields in $fields_req array.
* If a required field does not have a value, an error response is given.
*/
function constructMessageBody () {
$fields_req = array("name" => true, "description" => true, "email" => true, "number" => true);
$message_body = "";
foreach ($fields_req as $name => $required) {
$postedValue = $_POST[$name];
if ($required && empty($postedValue)) {
errorResponse("$name is empty.");
} else {
$message_body .= ucfirst($name) . ": " . $postedValue . "\n";
}
}
return $message_body;
}
//header('Content-type: application/json');
//attempt to send email
$messageBody = constructMessageBody();
require 'php_mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->addAddress("example#example.com");
$mail->Subject = $_POST['name'];
$mail->Body = $messageBody;
//try to send the message
if($mail->send()) {
echo json_encode(array('message' => 'Your message was successfully submitted from PHP.'));
} else {
errorResponse('An expected error occured while attempting to send the email: ' . $mail->ErrorInfo);
}
?>
(function($) {
$('#form').on('submit', function(){
event.preventDefault();
var contactFormUtils = {
clearForm: function () {
grecaptcha.reset();
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").append('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
}
};
$('#submit-email').prop('disabled', true).html("sending");
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log('success');
$('#form').fadeOut(400)
contactFormUtils.addAjaxMessage(data.message, false);
contactFormUtils.clearForm();
},
error: function(response) {
console.log('error');
contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
$('#submit-report').prop('disabled', false).html("Send message");
contactFormUtils.clearForm();
},
complete: function() {
console.log('complete');
}
});
return false;
});
})( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-8 site-block">
<form id="form" method="post" class="form-horizontal ajax" action="<?php echo get_template_directory_uri(); ?>/assets/php/process-contact.php" data-toggle="validator">
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input name="name" type="text" class="form-control" id="inputName" placeholder="Enter your full name and title here" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10">
<input name="number" type="number" class="form-control" id="inputEmail3" placeholder="Enter your preferred telephone number here" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="Enter your preferred email address here" required>
</div>
</div>
<div class="form-group">
<label for="inputMessage" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea name="description" class="form-control" id="inputMessage" placeholder="Type your message here" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="submit-email" name="submit" type="submit" class="btn btn-danger">Submit</button>
</div>
</div>
</form>
<div id="feedbackSubmit"></div>
</div>
change
jQuery('#form').on('submit', function(){
to
jQuery('.ajax').on('submit', function(event){
and replace ALL $ with jQuery
and
wrap your code in document ready function
jQuery(function(){});

user profile update via ajax

hi guys im trying to update user details via ajax but its not updating my users table and just stop executing when possessing... appear here is my code please help if possible
edit_profile.php
<?php
if(isset($_POST["la"])){
$firstname = strip_tags(preg_replace('#[^a-z0-9]#i', '', $_POST['fi']));
$lastname = strip_tags(preg_replace('#[^a-z]#', '', $_POST['la']));
$age = strip_tags(preg_replace('#[0-9]#', '', $_POST['ag']));
$gender = strip_tags(preg_replace('#[^a-z]#', '', $_POST['g']));
// FORM DATA ERROR HANDLING
if($gender == "" || $firsname == "" || $lastname == "" || $age == ""){
echo "some account info is empty.";
exit();
}else{
$sql = "UPDATE users SET gender='$gender', age='$age', lastname='$lastname, firstname='$firstname' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo "account_success";
exit();
}
}
?>
ajax and js
<script type="text/javascript" language="javascript">
function _(x){
return document.getElementById(x);
}
function toggleElement(x){
var x = _(x);
if(x.style.display == 'block'){
x.style.display = 'none';
}else{
x.style.display = 'block';
}
}
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "firstname"){
rx = /[^a-z0-9]/gi;
} else if(elem == "lastname"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function update_profile() {
var fi = _("firstname").value;
var la = _("lastname").value;
var g = _("gender").value;
var ag = _("age").value;
var status2 = _("status_profile");
if(fi == "" || la == "" || ag == "" || g == ""){
status2.innerHTML = "Fill out all of the form data";
status2.style.color = "red";
}else {
_("profilebtn").style.display = "none";
status2.innerHTML = 'processing ...';
var ajax = ajaxObj("POST", "edit_profile.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "account_success"){
_("profilebtn").style.display = "block";
}
}
}
ajax.send("&fi="+fi+"&la="+la+"&g="+g+"&ag="+ag);
}
}
</script>
the html
<div class="row profile-classic">
<div class="col-md-12 m-t-20">
<form name="updateform" id="updateform" onsubmit="return false;">
<div id="profile_form" class="panel">
<div class="panel-title line">
<div class="caption"><i class="fa fa-phone c-gray m-r-10"></i>ACCOUNT</div>
</div>
<div class="panel-body">
<div class="row">
<div class="control-label c-gray col-md-3">Username:</div>
<div class="col-md-6">
<input type="text" class="form-control" value="<?php echo $uname; ?>" disabled="disabled">
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Firstname: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="firstname" contenteditable="true" value="<?php echo $firstname; ?>">
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Lastname: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="lastname" placeholder="your lastname" value="<?php echo $lastname; ?>" >
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Age: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="age" value="<?php echo $age; ?>">
</div>
</div><br />
<div class="row">
<div class="col-md-6">
<select class="form-control" onfocus="emptyElement('status_profile')" id="gender" class="form-control">
<option value="<?php echo $gender; ?>"><?php echo $sex; ?></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</div>
<button id="profilebtn" onclick="update_profile()" class="btn btn-sm btn-default"><i class="fa fa-floppy-o"></i> Save</button><span id="status_profile"></span>
</div><br />
</div>
</div></form>
</div></div>
You can use mysqli_error($db_conx) to determine what the error is... just have your javascript display it nicely for you.
But also - the variable in your WHERE clause ( $log_username ) is undefined.

Categories