Error loading data with AJAX - javascript

Each time I press the button to load the AJAX, I load the start screen with everything (header, menu and footer) apart from not loading the data from the table I request. I get this warning in the console:
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check.
I tried to put async: true and also the script at the end of the document, but nothing.
INDEX.PHP
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Sistema de Administración de Envíos - Pedidos</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/main.js"></script>
<script src="js/jquery.slim.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/popper.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</head>
<body>
<?php
require('components/menu.php');
?>
<div class="main">
<div id="top-pedidos">
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<div class="input-group-addon"><button id="buttonFechaPedido" type="submit"><i class="fa fa-calendar"></i></button></div>
<input type="date" class="form-control" id="inputFechaPedido" name="fecha">
</div>
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<div class="input-group-addon"><button id="buttonNumeroPedido"><i class="fa fa-search"></i></button></div>
<input type="text" class="form-control" id="inputNumeroPedido" name="npedido" placeholder="Nº pedido">
</div>
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<div class="input-group-addon"><button id="buttonEstadoPedido"><i class="fa fa-check-square"></i></button></div>
<select class="custom-select mb-2 mr-sm-2 mb-sm-0" id="inputEstadoPedido" name="estado">
<option value="vacio" selected></option>
<option value="Pendiente">Pendiente</option>
<option value="Aceptado">Aceptado</option>
<option value="Rechazado">Rechazado</option>
</select>
</div>
<button class="newPedido btn btn-primary">Nuevo Pedido</button>
</div>
<div class="tables">
<?php
require('sql/sql-pedidos.php');
?>
<div id="tablaPedido">
<p id="emptyFecha" class="mistake red">Debes poner una fecha</p>
<p id="errorFecha" class="mistake red">Ha ocurrido un error con la fecha</p>
<p id="emptyNumero" class="mistake red">Debes poner un número de pedido</p>
<p id="errorNumero" class="mistake red">Ha ocurrido un error con el número de pedido</p>
<p id="emptyEstado" class="mistake red">Debes seleccionar un estado</p>
<p id="errorEstado" class="mistake red">Ha ocurrido un error con el estado</p>
</div>
</div>
</div>
<?php
require('components/footer.php');
?>
</body>
</html>
loadAjax.php
<?php
//Tabla inicial sin parámetros de búsqueda
require('conexionbd.php');
$general = 'SELECT * FROM pedidos';
$result = mysql_query($general) or die('Consulta fallida: ' . mysql_error());
echo "<table class='table table-striped table-pedidos-g'>\n";
echo "<tr class='superior'>
<td>Nº pedido</td>
<td>Fecha</td>
<td>Descuento</td>
<td>Cliente</td>
<td>Estado</td>
</tr>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
?>
<script>
$('#buttonFechaPedido').click(function() {
$('.table-pedidos-g').hide();
$('.table-pedidos-n').hide();
$('.table-pedidos-e').hide();
var valorFecha = $('#inputFechaPedido').val();
if (valorFecha.length == 0){
$('#emptyFecha').removeClass('mistake');
}
else{
$(document).ready(function() {
$.ajax({
data: valorFecha,
url: 'pedidos/pfechas.php',
type: 'post',
beforeSend: function () {
$("#tablaPedido").html("Procesando, espere por favor...");
},
error:function (){
$('#errorFecha').removeClass('mistake');
},
success: function (response) {
$("#tablaPedido").html(response);
}
});
});
}
});
</script>
<script>
$('#buttonNumeroPedido').click(function() {
$('.table-pedidos-g').hide();
$('.table-pedidos-f').hide();
$('.table-pedidos-e').hide();
var valorNumero =$('#inputNumeroPedido').val();
if (valorNumero.length == 0){
$('#emptyNumero').removeClass('mistake');
}
else{
$(document).ready(function() {
$.ajax({
data: valorNumero,
url: 'pedidos/pnumero.php',
type: 'post',
beforeSend: function () {
$("#tablaPedido").html("Procesando, espere por favor...");
},
error:function (){
$('#errorNumero').removeClass('mistake');
},
success: function (response) {
$("#tablaPedido").html(response);
}
});
});
}
});
</script>
<script>
$('#buttonEstadoPedido').click(function() {
$('.table-pedidos-g').hide();
$('.table-pedidos-n').hide();
$('.table-pedidos-f').hide();
var valorEstado =$('#inputEstadoPedido').val();
if (valorEstado == 'vacio'){
$('#emptyEstado').removeClass('mistake');
}
else{
$(document).ready(function() {
$.ajax({
data: valorEstado,
url: 'pedidos/pestado.php',
type: 'post',
beforeSend: function () {
$("#tablaPedido").html("Procesando, espere por favor...");
},
error:function (){
$('#errorEstado').removeClass('mistake');
},
success: function (response) {
$("#tablaPedido").html(response);
}
});
});
}
});
</script>
pfechas.php
<?php
require('../conexionbd.php');
// Realizar una consulta MySQL
$fechas = 'SELECT * FROM pedidos WHERE fecha_pdo = $_POST["valorFecha"]';
$result = mysql_query($fechas) or die('Consulta fallida: ' . mysql_error());
// Imprimir los resultados en HTML
echo "<table class='table table-striped table-pedidos-f'>\n";
echo "<tr class='superior'>
<td>Nº pedido</td>
<td>Fecha</td>
<td>Descuento</td>
<td>Cliente</td>
<td>Estado</td>
</tr>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Liberar resultados
mysql_free_result($result);
// Cerrar la conexión
mysql_close($link);
?>
pnumero.php
<?php
require('../conexionbd.php');
// Realizar una consulta MySQL
$numeros = 'SELECT * FROM pedidos WHERE numero_pdo = $_POST["valorNumero"]';
$result = mysql_query($fnumeros) or die('Consulta fallida: ' . mysql_error());
// Imprimir los resultados en HTML
echo "<table class='table table-striped table-pedidos-n'>\n";
echo "<tr class='superior'>
<td>Nº pedido</td>
<td>Fecha</td>
<td>Descuento</td>
<td>Cliente</td>
<td>Estado</td>
</tr>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Liberar resultados
mysql_free_result($result);
// Cerrar la conexión
mysql_close($link);
?>
pestado.php
<?php
require('../conexionbd.php');
// Realizar una consulta MySQL
$estados = 'SELECT * FROM pedidos WHERE estado = $_POST["valorEstado"]';
$result = mysql_query($estados) or die('Consulta fallida: ' . mysql_error());
// Imprimir los resultados en HTML
echo "<table class='table table-striped table-pedidos-e'>\n";
echo "<tr class='superior'>
<td>Nº pedido</td>
<td>Fecha</td>
<td>Descuento</td>
<td>Cliente</td>
<td>Estado</td>
</tr>";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Liberar resultados
mysql_free_result($result);
// Cerrar la conexión
mysql_close($link);
?>

Related

CAPTCHA existing and working but not active on contact form

i'm trying to add IconCaptcha (https://github.com/fabianwennink/IconCaptcha-Plugin-jQuery-PHP#installation) to a contact form.
I managed to implement it with success on the web page. But whenever i hit the SUBMIT button (with the other fields well filled) the form is sent. Even if i hit the wrong captcha... Or no captcha at all.
Here is the contact.php page code :
<?php
session_start();
require('IconCaptcha-PHP/src/captcha-session.class.php');
require('IconCaptcha-PHP/src/captcha.class.php');
IconCaptcha::setIconsFolderPath('../assets/icons/');
IconCaptcha::setIconNoiseEnabled(true);
if(!empty($_POST)) {
if(IconCaptcha::validateSubmission($_POST)) {
$captchaMessage = 'Le message a bien été envoyé!';
} else {
$captchaMessage = json_decode(IconCaptcha::getErrorMessage())->error;
}
}
?>
<!doctype html>
<!--
* IconCaptcha Plugin: v2.5.0
* Copyright © 2017, Fabian Wennink (https://www.fabianwennink.nl)
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
-->
<html>
<head>
<!--FORMAT-->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!--STYLES-->
<link href="css/styles.css" rel="stylesheet" type="text/css">
<link href="css/bootstrap-4.3.1.css" rel="stylesheet" type="text/css">
<!-- IconCaptcha stylesheet -->
<link href="IconCaptcha-PHP/assets/css/icon-captcha.min.css" rel="stylesheet" type="text/css">
<script src="http://use.edgefonts.net/montserrat:n4:default.js" type="text/javascript"></script>
<!--SCRIPTS BOOTSTRAP-->
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap-4.3.1.js"></script>
<body>
<section id="contact" class="section-orange">
<div class="container-fluid" justify-content="center" style="width: 90%">
<!-- DEBUT FORMULAIRE CONTACT -->
<?php
if(isset($captchaMessage)) {
echo '<b>Captcha Message: </b>' . $captchaMessage;
}
?>
<form id="reused_form" role="form" method="post" action="envoiformulaire.php">
<div class="row">
<div class="col-md-6 form-group">
<label for="first_name"></label>
<input id="firstname" name="first_name" type="text" class="form-control" placeholder="Prénom" required="required">
</div>
<div class="col-md-6 form-group">
<label for="last_name"></label>
<input id="lastname" name="last_name" type="text" class="form-control" placeholder="NOM" required="required">
</div>
</div>
<div class="row">
<div class="col-md-6 form-group">
<label for="email"></label>
<input id="email" name="email" type="email" class="form-control" placeholder="Courriel" required="required">
</div>
<div class="col-md-6 form-group">
<label for="telephone"></label>
<input id="telephone" type="tel" name="telephone" onkeyup="formatte(this,2)" onkeypress="return isNumberKey(event)" class="form-control" placeholder="Téléphone" required="required" minlength="14" maxlength="14">
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="comments"></label>
<textarea id="message" name="comments" class="form-control" placeholder="Message (400 caractères maximum)" maxlength="400" rosws="4" required="required"></textarea>
</div>
<div class="col-md-12 form-group">
<div class="captcha-holder"></div>
</div>
<div class="col-md-12 form-group">
<br> <input type="submit" id="btnContactUs" class="btn btn-success btn-send" value="Envoyer le message">
</div>
</div>
</form>
<script src="IconCaptcha-PHP/assets/js/icon-captcha.min.js" type="text/javascript"></script>
<!-- Initialize the IconCaptcha -->
<script async type="text/javascript">
$(window).ready(function() {
$('.captcha-holder').iconCaptcha({
theme: ['light'],
fontFamily: '',
clickDelay: 500,
invalidResetDelay: 3000,
requestIconsDelay: 1500,
loadingAnimationDelay: 1500, // How long the fake loading animation should play.
hoverDetection: true,
showCredits: 'show',
enableLoadingAnimation: false,
validationPath: 'IconCaptcha-PHP/src/captcha-request.php',
messages: {
header: "Vous devez choisir, « …but, choose wiesly! »",
correct: {
top: "« You have chosen… wisely. »",
bottom: "Félicitations! Vous n'êtes pas un robot."
},
incorrect: {
top: "« You chose poorly! »",
bottom: "Oups! Mauvaise image."
}
}
})
.bind('init.iconCaptcha', function(e, id) {
console.log('Event: Captcha initialized', id);
}).bind('selected.iconCaptcha', function(e, id) {
console.log('Event: Icon selected', id);
}).bind('refreshed.iconCaptcha', function(e, id) {
console.log('Event: Captcha refreshed', id);
}).bind('success.iconCaptcha', function(e, id) {
console.log('Event: Correct input', id);
}).bind('error.iconCaptcha', function(e, id) {
console.log('Event: Wrong input', id);
});
});
</script>
<!-- FIN FORMULAIRE CONTACT -->
</div>
</section>
</body>
</html>
Here is the PHP function envoiformulaire.php to send the form :
<?php
header('Content-Type: text/html; charset=utf-8');
if(isset($_POST['email'])) {
$email_to = "mail#mail.com";
$email_subject = "Nouveau message web";
function died($error) {
echo "Oups! Une ou plusieurs erreurs se trouvent dans votre formulaire.<br>";
echo $error."<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('Oups! Un problème est survenu avec votre formulaire.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp ='/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'Le courriel saisi ne semble pas valide.<br />';
}
$phone_exp = "/^(\d\d\s){4}(\d\d)$/";
if(!preg_match( $phone_exp,$telephone)) {
$error_message .= 'Le numéro de téléphone saisi ne semble pas valide.<br />';
}
$string_exp = "/^[A-Za-z àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ.'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'Le prénom saisi ne semble pas valide.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'Le nom saisi ne semble pas valide.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'Le message saisi ne semble pas valide.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Ci-après le formulaire complété.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Prénom: ".clean_string($first_name)."\n";
$email_message .= "NOM: ".clean_string($last_name)."\n";
$email_message .= "Courriel: ".clean_string($email_from)."\n";
$email_message .= "Téléphone: ".clean_string($telephone)."\n";
$email_message .= "Message: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'Content-Type: text/plain; charset="utf-8"'.
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>
My guess is that on the contact page when i hit the SUBMIT button it activates the PHP to send the form without the CAPTCHA (method=post action="envoiformulaire.php").
I may have to add "something" to make the SUBMIT button available only with the captcha completed. But i haven't figured how to do it.
Could someone give me a hint ?
Best regards,
Frédéric.
I was in contact with the creator of icon captcha. He helped me a lot, actually more than i expected.
First mistake, i put a part of the PHP validation code page on the contact form :
if(!empty($_POST)) {
if(IconCaptcha::validateSubmission($_POST)) {
$captchaMessage = 'Le message a bien été envoyé!';
} else {
$captchaMessage = json_decode(IconCaptcha::getErrorMessage())->error;
}
}
It should to go from contact.php to envoiformulaire.php .
After that he helped me with my numbnuts php skills...
On the top of the contact page, the following code should be added :
<?php
session_start();
require('IconCaptcha-PHP/src/captcha-session.class.php');
require('IconCaptcha-PHP/src/captcha.class.php');
IconCaptcha::setIconsFolderPath('../assets/icons/');
IconCaptcha::setIconNoiseEnabled(true);
?>
And add this code (ADD) in the envoiformulaire.php :
<?php
session_start(); // ADD THIS
header('Content-Type: text/html; charset=utf-8');
require('IconCaptcha-PHP/src/captcha-session.class.php'); // ADD THIS
require('IconCaptcha-PHP/src/captcha.class.php'); // ADD THIS
IconCaptcha::setIconsFolderPath('../assets/icons/'); // ADD THIS
IconCaptcha::setIconNoiseEnabled(true); // ADD THIS
if(isset($_POST['email'])) {
$email_to = "mail#mail.com";
$email_subject = "Nouveau message web";
function died($error) {
echo "Oups! Une ou plusieurs erreurs se trouvent dans votre formulaire.<br>";
echo $error."<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('Oups! Un problème est survenu avec votre formulaire.');
}
// ADD THIS
if(!IconCaptcha::validateSubmission($_POST)) {
died('ADD YOUR ERROR MESSAGE HERE');
}
...
And now, it works great, thank you Fabian !
I hope this post will help someone in the futur.
Frédéric.

How to call Ajax in tpl(template) file OpenCart version 2.3

How to call ajax call in tpl template opencart version 2.3
I have api controller with data and that data I need to post in template(tpl) file. Template file is tpl extension , I need open script tag but I don't know how do it in tpl file and how to target endpoint with function? I provide my code. In controller I have api folder and file reifenmontage and function get_marka_data()...How I target this data in tpl file? I know tpl is only for show data but I must do on this way :/
public function get_marka_data() {
$query = $this->db->query("
SELECT mo.marka
FROM " . DB_PREFIX . "model mo
GROUP BY mo.marka
")->rows;
$data = array_map(function($row){
return array('value'=>$row['marka'],'label'=>$row['marka']);
}, $query);
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($data));
var_dump($data);
}
<script type="text/javascript"><!--
$('#button-getdata').on('click', function() {
$.ajax({
url: 'index.php?route=extension/module/reifenmontage/get_marka_data',
type: 'post',
data: $('#reifenmontage-input select, #reifenmontage-input input'),
dataType: 'json',
beforeSend: function() {
$('#reifenmontage-input').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" /> <?php echo $text_wait; ?></div>');
},
success: function(json) {
$('.success, .warning, .attention, information, .error').remove();
if (json['success']) {
html = "<!-- Retrieved data -->\n";
for (i in json['success']) {
var element = json['success'][i];
console.log(element);
html += "\t<tr><td>" + element['label'] + "</td><td align=\"right\">" + element['value'] + "</td></tr>\n";
}
$('#reifenmontage-output').html(html);
}
}
});
});
//--></script>
<?php if($heading_title) { ?>
<h2><?php echo $heading_title; ?></h2>
<?php } ?>
<h2><?php echo $description_title; ?></h2>
<?php echo $description; ?>
<div id="reifenmontage-input" class="reifenmontage-input">
<form id="reifenmontage-input" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="control-label" for="datum"><?php echo $entry_begin_period; ?></label>
<div class="input-group date">
<input type="text" name="datum" value="<?php echo $current_day . '-' . $current_month . '-' . $current_year; ?>" data-date-format="DD-MM-YYYY" id="datum" class="form-control" />
<span class="input-group-btn">
<button class="btn btn-default" type="button"><i class="fa fa-calendar"></i></button>
</span></div>
</div>
<div class="form-group">
<label class="control-label" for="entry-cyclus"><?php echo $entry_cyclus; ?></label>
<select name="cyclus" id="entry-cyclus" class="form-control">
<option value=""><?php echo $text_select; ?></option>
<?php
for ($i=20;$i<43;$i++) {
if ($i == 28) {
?>
<option value="<?php echo $i; ?>" selected="selected"><?php echo $i; ?></option>
<?php
} else {
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
?>
</select>
</div>
<div class="buttons">
<div class="pull-right">
<input type="button" value="<?php echo $button_create; ?>" id="button-getdata" class="btn btn-default" />
</div>
</div>
</fieldset>
</form>
</div>
<div id="reifenmontage-output"></div>
And for de php-function, change te last part into:
$json = array();
if ($data) {
$json['succes'] = $data;
} else {
$json['error'] = 'Sorry, no data !';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
Example for form, output id and script to retrieve data from controller in extension/module
In controller/api/reifenmontage.php:
<?php
class ControllerApiReifenmontage extends Controller {
private $error = array();
public function get_marka_data() {
$json = array();
if (isset($this->request->post['marka'])) {
$marka_data_query = $this->db->query("SELECT mo.model FROM " . DB_PREFIX . "model mo WHERE mo.marka='" . $this->request->post['marka'] . "'");
$marka_data = $marka_data_query->rows;
$json['succes'] = $marka_data;
} else {
$json['error'] = 'Sorry, no data !';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
Form with script:
<div id="reifenmontage-input" class="reifenmontage-input">
<form id="reifenmontage-input" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group required">
<label class="col-sm-4 control-label" for="input-marka">Marka</label>
<div class="input-group col-sm-8">
<select name="marka" id="input-marka" class="form-control">
<option value="0">Select ...</option>
<option value="AJP">AJP</option>
<option value="APOLO">APOLO</option>
<option value="APRILIA">APRILIA</option>
<!-- All stored marka's -->
</select>
</div>
</div>
</fieldset>
<div class="buttons">
<div class="pull-right">
<button type="button" class="btn btn-primary" id="button-getdata" data-loading-text="Loading ...">Get Data</button>
</div>
</div>
</form>
</div>
<div class="col-xs-12 col-sm-3" style="margin-right:30px;">
<div class="row">
<select class="form-control" id="result">
</select>
</div>
</div>
<script type="text/javascript"><!--
$('#button-getdata').on('click', function() {
$.ajax({
url: 'index.php?route=api/reifenmontage/get_marka_data',
type: 'post',
data: $('#reifenmontage-input select'),
dataType: 'json',
beforeSend: function() {
$('.success, .warning, .attention, information, .error').remove();
$('#result').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" />Please wait ...</div>');
},
success: function(json) {
if (json['error']) {
$('#result').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" />' + json['error'] + '</div>');
}
if (json['success']) {
for (i in json['success']) {
var element = json['success'][i];
//console.log(element);
html = "\t<option value=\""+ element['model'] + "\">" + element['model'] + "</option>\n";
$('#result').append(html);
}
}
}
});
});
//--></script>
New controller/api/reifenmontage.php
<?php
class ControllerApiReifenmontage extends Controller {
private $error = array();
public function get_markas() {
$json = array();
$markas_query = $this->db->query("SELECT marka FROM " . DB_PREFIX . "model GROUP BY marka");
$markas_data = $markas_query->rows;
if ($markas_data) {
$json['success'] = $markas_data;
} else {
$json['error'] = 'Sorry, no data !';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function get_marka_data() {
$json = array();
if (isset($this->request->post['marka'])) {
$marka_data_query = $this->db->query("SELECT mo.model FROM " . DB_PREFIX . "model mo WHERE mo.marka='" . $this->request->post['marka'] . "'");
$marka_data = $marka_data_query->rows;
$json['success'] = $marka_data;
} else {
$json['error'] = 'Sorry, no data !';
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
And new script on template / form:
<script type="text/javascript"><!--
function getMarkaData() {
$.ajax({
url: 'index.php?route=api/reifenmontage/get_marka_data',
type: 'post',
data: $('#reifenmontage-input select'),
dataType: 'json',
beforeSend: function() {
$('.success, .warning, .attention, information, .error').remove();
},
success: function(json) {
if (json['error']) {
$('#result').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" />' + json['error'] + '</div>');
}
if (json['success']) {
$('#result2').html('');
for (i in json['success']) {
var element = json['success'][i];
//console.log(element);
html = "\t<option value=\""+ element['model'] + "\">" + element['model'] + "</option>\n";
$('#result2').append(html);
}
}
}
});
}
function getMarkas() {
$.ajax({
url: 'index.php?route=api/reifenmontage/get_markas',
dataType: 'json',
type: 'post',
beforeSend: function() {
$('.success, .warning, .attention, information, .error').remove();
},
success: function(json) {
if (json['success']) {
for (i in json['success']) {
var element = json['success'][i];
html = "\t<option value=\""+ element['marka'] + "\">" + element['marka'] + "</option>\n";
$('#result').append(html);
}
getMarkaData();
}
}
});
}
//--></script>
<script type="text/javascript">
let selectItem = document.getElementById('pneu');
let additionalRow = document.getElementById('additionalRow');
function checkSelected() {
if (selectItem.selectedIndex == "1") {
additionalRow.style.display = 'none';
} else {
additionalRow.style.display = 'flex';
getMarkas();
}
}
$('#result').on('change', function() {
getMarkaData();
});
if ($('#pneu').val() != '1') {
getMarkas();
}
</script>

javascript function is supposed to display php SESSION data but isn't called

I'm trying to make a regular old registration form for a website; and I'm trying to display the name of the logged-in user(if any) at the top of the page. However, the function that is supposed to update that field doesn't seem o be called at all, and I can't make heads or tails of it, nor of the error messages my console displays:
"Uncaught SyntaxError: Unexpected token < -- pagina_registrazione.php:36"
"Uncaught ReferenceError: update_name is not defined
onload -- pagina_registrazione.php:10"
here is the code:
<?php
require './config_db.php';
?>
<!DOCTYPE HTML>
<html lang = "it" >
<head>
<meta charset="utf-8">
<meta name = "keywords" content = "catcher, profilo, registrazione, utente">
<meta name="author" content="Luca Ballarati">
<link rel="stylesheet" href="./../stile/sottopagine.css" type="text/css" media="screen">
<title>pagina di registrazione</title>
</head>
<body onload=update_name>
<section>
<p id="spia_connessione">NOMEUTENTEQUI</p>
<p>Se hai già un'account <strong>clicca qui</strong> per accedere.</p>
<p>Altrimenti <strong>registrati</strong> compilando i campi qui sotto</p>
</section>
<div id="login_form">
<form name="registra" action="./pagina_registrazione.php" method="post">
<div>
<label><p>Nome Utente</p></label>
<input type="text" placeholder="nome_utente" name="username" required autofocus>
</div>
<div>
<label><p>Password</p></label>
<input type="password" placeholder="password" name="password" required>
</div>
<div>
<label><p>Conferma Password</p></label>
<input type="password" placeholder="conferma_password" name="passwordconfirm" required>
</div>
<input name="pulsante_invio" type="submit" value="Invia">
<?php
if(isset($_POST['pulsante_invio'])) {
$nomeutente = $_POST['username'];
$password = $_POST['password'];
$cpassword = $_POST['passwordconfirm'];
if ($password==$cpassword) {
$query = "SELECT * FROM utenti WHERE NomeUtente='$nomeutente'";
$esegui_query = mysqli_query($con,$query);
if(mysqli_num_rows($esegui_query)>0) {
echo '<script type="text/javascript">
window.alert("Nome Utente già usato: registrarsi con un diverso Nome Utente");
</script>';
}
else {
$query = "INSERT INTO utenti (NomeUtente,Password,Record,Partite)
VALUES('$nomeutente','$password',0,0)";
$esegui_query = mysqli_query($con,$query);
if ($esegui_query) {
$nome = $_SESSION['username'];
//porta l'utente alla pagina di login
echo '<script type="text/javascript">
window.alert("Utente registrato correttamente");
</script>';
//echo '<script type="text/javascript">
//document.getElementById("spia_connessione").innerHTML = "'$nome'";
//</script>';
}
else {
echo '<script type="text/javascript">
window.alert("Errore durante la registrazione");
</script>';
}
}
}
else {
echo '<script type="text/javascript">
window.alert("Password e Password di conferma devono essere uguali");
</script>';
}
}
?>
</form>
</div>
<script type="text/javascript">
function update_name() {
window.alert("nome utente aggiornato");
var nm = <?php echo $_SESSION['username']; ?>;
document.getElementById("spia_connessione").innerHTML = nm;
}
</script>
</body>
Please write this code on the top of your php file.
<?php
ob_start();
session_start();
?>

Ajax-submitted form is not being saved to the database

I have a form with different inputs. On submit i use Ajax to send the data to a MySQL table. If the inputs are blank the jQuery validate plugin stops the submit action.
The POST submit works because i use Firebug and the response Ajax tells me that; but the data doesn't save in my database.
I don't know which part is causing the problem because in JS it doesn't tell me any issue.
My HTML/JS code looks like this:
$(document).ready(function() {
$("#ok").hide();
$("#formula").validate({
rules: {
nombre: {required: true},
mail: {required: true},
estado: {required: true},
imagen: {required:true,
extension:'jpeg|png|jpg|gif'},
checa:{required:true}
},
messages: {
nombre: "Debe introducir su nombre.",
mail:"Introduce una dirección de e-mail válido.",
estado : "Debes seleccionar tu estado donde resides.",
imagen : "Selecciona una imagen válida, jpg, jpeg, png o gif.",
checa: "Debes aceptar los terminos de uso y la política de privacidad"
},
submitHandler: function(form){
var dataString = 'nombre='+ nombre
+ 'mail=' + mail
+ '&estado=' + estado
+ '&imagen=' + imagen
+ '&checa=' + checa
$("#ok").show();
$.ajax({
type: "POST",
url:"envia.php",
data: dataString,
success: function(msg){
$("#ok").html("<strong>Mensaje enviado existosamente, nos pondremos en contacto a la brevedad.</strong>");
document.getElementById("nombre").value="";
document.getElementById("mail").value="";
document.getElementById("estado").value="";
document.getElementById("imagen").value="";
document.getElementById("checa").value="";
setTimeout(function() {$('#ok').fadeOut('fast');}, 3000);
}
});
}
});
});
<section class="wrapper">
<form method="post" name="formulario" id="formula" enctype="multipart/form-data">
<div id="ok"></div>
<label>Nombre:</label>
<input type="text" name="nombre" id="nombre" />
<label>Email:</label>
<input type="email" name="mail" id="mail" />
<label>Estado:</label>
<!--<div class="styled-select">-->
<select name="estado" id="estado">
<option value="">Selecciona tu estado:</option>
<option>Aguascalientes</option>
<option>Baja California</option>
<option>Baja California Sur</option>
<option>Campeche</option>
<option>Chiapas</option>
<option>Chihuahua</option>
<option>Coahuila</option>
<option>Colima</option>
<option>Distrito Federal</option>
<option>Durango</option>
<option>Guanajuato</option>
<option>Guerrero</option>
<option>Hidalgo</option>
<option>Jalisco</option>
<option>México</option>
<option>Michoacán</option>
<option>Morelos</option>
<option>Nayarit</option>
<option>Nuevo León</option>
<option>Oaxaca</option>
<option>Puebla</option>
<option>Querétaro</option>
<option>Quintana Roo</option>
<option>San Luis Potosí</option>
<option>Sinaloa</option>
<option>Sonora</option>
<option>Tabasco</option>
<option>Tamaulipas</option>
<option>Tlaxcala</option>
<option>Veracruz</option>
<option>Yucatán</option>
<option>Zacatecas</option>
</select>
<!--</div>
<div id="file">Chose file</div>-->
<input type="file" name="imagen" id="imagen" class="upload" />
<input type="checkbox" name="checa" id="checa" value="Acepto">Acepto los terminos y condiciones y la politica de privacidad
<input name="URLBack" type="hidden" id="URLBack" value="<?php echo "hhtp://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>" />
<input name="input" id="enviar" type="submit" value="Enviar" />
</form>
</section>
And my PHP file looks like this:
include 'conexion.php';
$con = conexion();
$nombre=substr($_POST['nombre'],0,2);
$sql= "SELECT MAX(id) FROM base_de_datos";
$rs=mysql_query($sql);
if(isset($rs) && mysql_num_rows($rs)>0)
{
$row=mysql_fetch_row($rs);
$num=$row;
mysql_free_result($rs);
}
$tumb = implode($num);
$sumando = $tumb + 1;
if ($_FILES["imagen"]["error"] > 0){
echo "ha ocurrido un error";
} else {
$permitidos = array("image/jpg", "image/jpeg", "image/gif", "image/png");
$limite_kb = 2000;
if (in_array($_FILES['imagen']['type'], $permitidos) && $_FILES['imagen']['size'] <= $limite_kb * 2048){
$ruta = "imagenes/" . $_FILES['imagen']['name'];
if (file_exists($ruta)){
echo $_FILES['imagen']['name'] . ", este archivo existe";
}
else{
$temp = explode(".", $_FILES["imagen"]["name"]);
$newfilename = 'contest'. $sumando . '.' . end($temp);
move_uploaded_file($_FILES["imagen"]["tmp_name"], "imagenes/" . $newfilename);
}
}
}
$caracteres = "AABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
$numerodeletras=10;
$cadena = "";
for($i=0;$i<$numerodeletras;$i++)
{
$cadena .= substr($caracteres,rand(0,strlen($caracteres)),1);
}
$serie=$nombre.$sumando;
$este= date("Y/m/d");
echo $serie;
$_GRABAR_SQL = "INSERT INTO base_de_datos (nombre,email,estado,imagen,condiciones_de_uso,clave,fecha) VALUES ('$_POST[nombre]','$_POST[mail]','$_POST[estado]','$newfilename','$_POST[checa]','$serie','$este')";
mysql_query($_GRABAR_SQL);
$query=mysql_insert_id();
$headers = "MIME-Version: 1.0\r \n";
$headers .= "Content-type: text/html; charset=utf-8 \r \n";
$headers .= "Return-Path: ".$_POST['nombre']." <".$_POST['mail']."> \r \n";
$headers .= "From: OMA Plaza <noreply#example.com> \r \n";
$headers .= "Reply-To: ".$_POST['nombre']." <".$_POST['nombre']."> \r \n";
$headers .= "X-Priority: 1\r\n";
$mail = mysql_real_escape_string($_POST['mail']);
if ( function_exists( 'mail' ) )
{
echo 'mail() is available';
}
else
{
echo 'mail() has been disabled';
}
$asunto = "";
$confir = "Su mensaje fue enviado exitosamente, nos pondremos en contacto con usted a la brevedad";
$mensage = "---------------------------------- \n";
$mensage.= " Contacto \n";
$mensage.= "---------------------------------- \n";
$mensage.= "Nombre: ".$_POST['nombre']."\n";
$mensage.= "Clave Confirmación: ".$serie."\n";
$mensage.= "Email: ".$_POST['mail']."\n";
mail ($mail, $asunto, $mensage, $headers);

Form should not reload

I built a Feedback form with PHP. There is a Popup from Foundation 5 included.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style type="text/css">
.auto-style1 {
margin-left: 1px;
}
.auto-style2 {
margin-left: 0px;
}
.auto-style3 {
text-align: center;
}
.auto-style4 {
text-align: center;
font-size: x-large;
}
.auto-style5 {
color: #FF0000;
}
.auto-style6 {
color: #000000;
}
.auto-style7 {
text-align: left;
}
</style>
<title>Rating</title>
<!-- Sterne Scripts -->
<script src='jquery.js' type="text/javascript"></script>
<script src='jquery.MetaData.js' type="text/javascript" language="javascript"></script>
<script src='jquery.rating.js' type="text/javascript" language="javascript"></script>
<!-- Popup Scripts -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/foundation.css">
<!-- If you are using the gem version, you need this only -->
<link rel="stylesheet" href="css/app.css">
<script src="js/vendor/modernizr.js"></script>
<link rel="stylesheet" href="css/app.css">
<script src="js/vendor/modernizr.js"></script>
<link href='jquery.rating.css' type="text/css" rel="stylesheet"/>
</head>
<body style="background-image: url('img/body-bg.jpg')">
<?php
$send = false;
$error = $text = '';
if ($_SERVER['REQUEST_METHOD'] === "POST") {
$to = 'kontakt#schoenholz.eu';
$subject = "Feedback vom ".date("d.m.Y");
$antispam = $_POST['access'];
$name = $_POST['star1'];
$select = $_POST['Select'];
$text = $_POST['TextArea1'];
$message = "Bewertung: ".$name. "\r\n" . "Warum die Bewertung?: " .$text . "\r\n" . "Woher kennen Sie uns?: " .$select;
$success = true;
if ($antispam != 'irregeheim') {
$success = false; //Fehlerflag setzen
$error .= 'Kein Spam erwünscht!<br>'; // Fehlertext
}
if ($name == '') {
$success = false;
$error .= '"<em>Wie bewerten Sie uns</em>" wurde nicht ausgefüllt';
}
if ($select == "- Bitte auswählen -") {
$success = false; //Fehlerflag setzen
$error .= '<br>"<em>Wie haben Sie uns gefunden</em>" wurde nicht ausgefüllt</br>'; // Fehlertext
}
// ist alles ok ? dann senden
if($success === true) {
if (#mail($to,$subject,$message)) {
$send = true;
echo 'Danke für Ihr Feedback!';
} else {
$error .= 'Ihr Feedback konnte leider nicht gesendet werden. Bitte versuchen sie es später erneut';
}
}
}
if ($send === false) {
?>
Feedback<br/>
<div id="firstModal" class="reveal-modal small" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p class="auto-style4" style="width: 477px"><strong>Feedback </strong></p>
<p class="auto-style7" style="width: 477px">Bitte füllen Sie alle mit
<span class="auto-style6">*</span> gekennzeichneten Felder aus</p>
<label id="Label1"></label>
<fieldset style="width: 476px"><legend>Wie bewerten Sie uns?
<span class="auto-style5">*</span></legend>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Sehr schlecht") echo "checked";?> value="Sehr schlecht"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Schlecht") echo "checked";?> value="Schlecht"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Durchschnittlich") echo "checked";?> value="Durchschnittlich"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Gut") echo "checked";?> value="Gut"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Hervorragend") echo "checked";?> value="Hervorragend"/> </fieldset>
<p style="height: 36px"> Grund Ihrer Bewertung?</p>
<textarea class="auto-style1" name="TextArea1" style="width: 505px; height: 105px"><?php echo htmlspecialchars($text, ENT_QUOTES);?></textarea>
<p>Wie haben Sie uns gefunden? <span class="auto-style5">*</span></p>
<p>
<select name="Select" style="width: 151px">
<option <?php if($select== "- Bitte auswählen -") echo "selected"; ?>>- Bitte auswählen -</option>
<option <?php if($select== "Familie/Freunde") echo "selected"; ?>>Familie/Freunde</option>
<option <?php if($select== "Suchmaschinen (Google etc.)") echo "selected"; ?>>Suchmaschinen (Google etc.)</option>
<option <?php if($select== "Zeitungen") echo "selected"; ?>>Zeitungen</option>
<option <?php if($select== "Örtliche") echo "selected"; ?>>Örtliche</option>
<option <?php if($select== "Werbung") echo "selected"; ?>>Werbung</option>
<option <?php if($select== "Sonstiges") echo "selected"; ?>>Sonstiges</option>
</select>
</p>
<input type="hidden" name="access" value="irregeheim">
<p class="auto-style3" style="width: 498px">
<input class="auto-style2" name="Submit1" type="submit" value="Senden"></p>
</form>
<?php
}
if (!empty($error)) {
echo $error;
}
?>
<a class="close-reveal-modal" aria-label="Close">×</a>
</div>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
$(document).foundation();
</script>
</body>
</html>
The problem is that if I push the Feedback button and miss a field, the page reloads and I have to push the Feedback Button again. I already figured out that I have to use ajax and Javascript to handle this but I dont know how I should rewrite my script so it works. Can somebody help me with that?
I use this approach:
1) Create the form on html and put an id on each input element, then I put a span or something to display error message, like this:
<input type="text" name="email" id="email">
<span id="email-message" class="hidden"></span>
2) On your php script, you need to create an array, validate each input and send json data. My array looks like this:
$data = array(
'message' => null,
'form' => array(
'has_errors' => false, // put true if there are input errors
'email' => array(
error => false,
message => null
);
);
);
header("Content-Type: application/json");
echo json_encode($data);
exit;
on this way, you add inputs to $data['form'] as you need. $data['message'] it's a general error like 'Impossible to save now. Try again'.
3) And finally, on your javascript file on success method (after json request to validate form), you check if "data.message" has a general error and if not you use a for each of the data.form to check each input and show the error message if it's necessary:
$('#my-form').on("submit", function(event){
event.preventDefault();
var $form = $(this);
$.ajax({
url: $form.attr("action"),
type: 'POST',
data: $form.serialize(),
dataType: 'json',
cache: false
}).done(function(data) {
if(data.message) {
// show general error
} else if(data.form.has_errors){//Si hay errores de formulario
//Recorremos todos los errores
$.each(data.form, function(key, value){
if(value.error) {
$('#' + key + '-msg').html(value.message).removeClass('hidden');
} else {
$('#'+key+'-msg').html('').addClass('hidden');
}
});
} else {
// no errors on form so show info message or whatever you need
}
});
});

Categories