send JSON or array to submit POST (jQuery -> PHP) - javascript

Good morning.
I'm stucked on this thing:
I'm doing a form (which send info to other page via submit button, post) which dynamically user can add some other form-groups with a button.
Ok, that's easy.
BUT the user is making something called "DPT" (work stuff) which have a table in my DB, and also have a "Function" (things to do) table. A DPT can have one or many Functions.
Function
---------
id int(4) AI
title VARCHAR(64) NOT NULL
description VARCHAR(256)
dpt int(4) --> FK
| 1..*
|
V 1
DPT
-----
id
name
(...)
So I have a <div> which I inflate with jQuery for making a panel and form inside it.
Why I did that? Because if a DPT can have one or many Functions I have to store the ID of the current Function I am creating.
Then I have a button for adding more functions, but I have to storage the ID of the function and the title and description of it.
So with jQuery I can dynamically add before the button of "Add function" a new form...
My idea was create a JSON and send it via PHP but have no idea where I have to send the info or where to return to...
I let you here my important code for doing the thing:
<div id="initialFunction" class="panel panel-default panel-body">
<?php
$nextID = mysqli_fetch_assoc(mysqli_query($con,"SELECT MAX(id_funcion) as siguiente_id from funcion"))['siguiente_id'];
?>
<button class="button btn-danger" type="button">
<span class="fa fa-minus">
</span>
</button>
</div>
<script>
var nextId = <?php echo $nextID?>
var arrayToPass = {}
$(function(){
$("#initialFunction").html('<div class="form-group">'+
'<label>Función a desarrollar <sup style="color:red">*</sup></label>'+
'<input class="form-control" name="funcion" type="text" placeholder="Función a desarrollar" maxlength="200" required>'+
'</div>'+
'<div class="form-group">'+
'<label>Tarea principal en esta función <sup style="color:red">*</sup></label>'+
'<textarea class="form-control" name="tarea" placeholder="Enumere las funciones de su puesto de trabajo comenzando por las más representativas, así como las tareas necesarias para el cumplimiento de las mismas" rows="3" required></textarea>'+
'</div>');
});
$("#bttn-add").click(function(){
$("#bttn-add-function").before(
'<div class="form-group">'+
'<label>Función a desarrollar <sup style="color:red">*</sup></label>'+
'<input class="form-control" name="funcion" type="text" placeholder="Función a desarrollar" maxlength="200" required>'+
'</div>'+
'<div class="form-group">'+
'<label>Tarea principal en esta función <sup style="color:red">*</sup></label>'+
'<textarea class="form-control" name="tarea" placeholder="Enumere las funciones de su puesto de trabajo comenzando por las más representativas, así como las tareas necesarias para el cumplimiento de las mismas" rows="3" required></textarea>'+
'</div>');
nextId++;
});
Can I return an array/json when I do click on the submit button and pass it through POST?
something like:
$("#guardar_dpt").click(function(){
return json_object
} )
?
I show you a what I am doing.
also the entire form:

It is possible. And simple. Here is example:
HTML:
<script src="https://unpkg.com/jquery"></script>
<form id="myForm" method="post">
<input type="text" name="first"><br>
<input type="text" name="last"><br>
<input type="submit" value="Send">
</form>
<p id="output"></p>
JS:
function parseAnswer (data) {
var content
content += 'Name: ' + data.first + '<br>'
content += 'Surname: ' + data.last
$('#output').text(Name)
}
$('#myForm').on( "submit", function (evt) {
var data = $(this).serialize()
evt.preventDefault()
$.post('any.php', data, parseAnswer)
})
PHP:
<?php
header("Content-type: application/json");
$first = $_POST['first'];
$last = $_POST['last'];
$arr = ['first' => $first, 'last' => $last];
echo json_encode($arr);
?>

Related

Wordpress Modal form ajax send

Let's see if you can help me, because I'm stuck because I can't get the ajax instruction to save the data to be executed
I have a modal window in the admin of my wordpress plugin, which I did via thickbox. The code for that modal is:
<p>Por favor, elija la configuración para <b><?php echo($_GET['title']);?></b>:</p>
<form method="post" id="ajax-form">
<label for="tipo">Introduzca el tipo de producto</label>
<select name="tipo" id="tipo">
<option value="Subscripción">Subscripción</option>
<option value="Sesion">Sesion</option>
</select><br><br>
<label for="cantidad">Introduzca el número de sesiones o de meses de subscripción</label>
<input name="cantidad" id="cantidad"></input>
<input id="id" name="id" type="hidden" value="<?php echo($_GET['id']);?>"><br>
<input type="submit">
<script type="text/javascript">
jQuery(document).ready(function(event) {
jQuery('#ajax-form').submit(ajaxSubmit);
function ajaxSubmit() {
var ajaxform = jQuery(this).serialize();
jQuery.ajax({
action: 'grabardatos_desde_modalform',
data: ajaxform,
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
success: function(data) {
alert("GUAYYYYYY");
}
});
}); }
</script>
</form>
The php code that should process the data is:
add_action('wp_ajax_grabardatos_desde_modalform' , 'grabardatos_desde_modalform');
add_action('wp_ajax_nopriv_grabardatos_desde_modalform','grabardatos_desde_modalform');
function grabardatos_desde_modalform(){
$datos=array(
$_POST['id'] => array(
'cantidad' => $_POST['cantidad'],
'tipo' => $_POST['tipo']
));
error_log(print_r($datos));
update_option('arrayproductos',$datos);
}
But I don't know why the query is not executed, because when I hit send it is as if the modal was reloaded.
On the other hand, I also need that after processing the data the main page is redirected.

How to create a form add-in at the click of a button?

Currently creating a site for a client during my internship end of study.
I am looking to create a button that will allow to add existing sections of my form.
I try to add it thanks to a function in Javascript however when I click on the button nothing happens, however when I do a console.log ('test') in the console hello
function dog_func ($atts) {
$list=array(
'Affenpinscher' => 'Affenpinscher',
'Airedale Terrier' => 'Airedale Terrier',
'Ariégeois' => 'Ariégeois',
'Barbet' => 'Barbet',
'Barbu Tchèque' => 'Barbu Tchèque' ,
'Berger de Russie' => 'Berger de Russie',
'Berger des Pyrénées' => 'Berger des Pyrénées',
'Berger des Shetland' => 'Berger des Shetland',
'Berger du Caucase' => 'Berger du Caucase',
'Berger du massif du Karst' => 'Berger du massif du Karst',
'Berger finnois de Laponie' => 'Berger finnois de Laponie',
'Berger Hollandais' => 'Berger Hollandais',
'Berger Islandais' => 'Berger Islandais',
'Bouvier de l\'Entlebuch' => 'Bouvier de l\'Entlebuch',
'Bouvier des Ardennes' => 'Bouvier des Ardennes',
'Bouvier des Flandres' => 'Bouvier des Flandres',
'Boxer' => 'Boxer',
'Autre' => 'Autre');
echo '<div id="divFields">';
echo '<label for="chien" class="breed">Race du chien:
</label>';
echo '<input id="chien" type="text" list="chiendata">';
echo '<datalist id="chiendata" name="chiendata" >';
echo '<label for="adresse">ou sélectionner dans la
liste</label>';
echo '<select name="adresse" class="selected" id="adresse"
onChange="AjoutOptionAuSelect(this)" style="width: -webkit-
fill-available;" size="1">';
foreach($list as $p => $row){
echo "<option value='".$p."'>" . $row ."</option>" ;
}
echo '</select>';
echo '</datalist>';
echo '<div>';
echo '<label for="name" class="breed">Si autre préciser :
</label>';
echo '</div>';
echo '<div>';
echo '<input type="text" name="dog">';
echo '</div>';
echo '</div>';
}
add_shortcode ('dog_api', 'dog_func');
function dog_shortcode(){
echo '<input type="button" class="add" value="Ajouter un chien" id="test" onClick="addField();">';
}
add_shortcode( 'dog_breed' , 'dog_shortcode');
function addField() {
var field = "<input type='text' name='' value=''/>";
document.getElementById('divFields').innerHtml += field;
console.log('test');
}
I explain I must create a form to add dogs for races, so I try to add with a button my select as much as needed to add the breed of 2 dogs, 3, 5 any matter,
My select is a shortcode to insert it in Elementor that the client wanted
In order to append html within a div.
function addField() {
var field = "<input type='text' name='' value=''/>";
// WITH JQuery
$("#divFields").append(field);
// WITH JS
document.getElementById('divFields').appendChild(field );
}
Life is a lot easier with jQuery, you may use JQuery

Ajax request only works one time [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I have a select option which is working perfectly but only one time, the request does not executes again.
I think it's because of the 'onchange' event.
This is my ajax code :
jQuery(document).ready(function($) {
$('#referenceProduit').change(function(){
//on recupere la valeur de l'attribut value pour afficher tel ou tel resultat
var req=$('#referenceProduit').val();
//requête ajax, appel du fichier function.php
$.ajax({
type: "POST",
url: "include/php.php",
data: "referenceProduit="+req,
dataType : "json",
//affichage de l'erreur en cas de problème
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
//function s'il n'y a pas de probleme
success:function(data){
//On affiche la réponse du serveur
$('.produit').empty();
$('.produit').prepend(data.produit);
$('input[name="designation"]').val(data.resDisplayForm.designation);
$('input[name="prix"]').val(data.resDisplayForm.prix);
}
});
});
});
HTML code :
<div class="form-group">
<label for="referenceProduit" class="col-sm-1 control-label">Reference</label>
<div class="col-sm-2">
<select class="form-control" name="referenceProduit" id="referenceProduit">
<option selected="selected" disabled="disabled">Choisir</option>
<?php foreach($lesProduits as $unProduit){?>
<option name="<?php echo $unProduit['id'];?>" value="<?php echo $unProduit['id'];?>"><?php echo $unProduit['reference']?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<div class="produit"></div>
</div><br/><br/>
You should map to
.on(eventType, selector, function)
example
$('#parentElement').on('change', '#referenceProduit', function)

javascript form validation with multiple field and display on site

So, hey, I know that there's more than someone could want of this type of question, but maybe I can present it with a little twist, i have try to mix different thing reader here and there, but when i submit the form the validation process don't run and it just submit directly the form. It's a one go script, and it go like this:
<script type="text/javascript">
var errors =[];
function printarray(array){
for (var i=0; i<array.lenght; i++){
document.write(array[i]);
}
}
function validate(){
document.getElementById("npostform").elements["contenidotext"].value=window.frames["contenido"].document.body.innerHTML;
document.getElementById("npostform").elements["resumentext"].value=window.frames["resumen"].document.body.innerHTML;
if (document.npostform.titulo.value=="" || document.npostform.titulo.value==null){
errors.push("Se debe especificar un titulo <br>");
}
if (document.npostform.contenidotext.value=="" || document.npostform.contenidotext.value==null){
errors.push("Se debe incluir un contenido <br>");
}
if (document.npostform.resumentext.value=="" || document.npostform.resumentext.value==null){
errors.push("Se debe incluir un resumen <br>");
}
if(errors.length >0){
for (var i=0; i<errors.lenght; i++){
document.getElementById("error").innerHTML=printarray(errors);
}
return false;
}else{
return true;
}
}
</script>
<div id="error"></div>
<form action="entradas.php" name="npostform" id="npostform" method="post" enctype="multipart/form-data" onsubmit="return validate();">
<label for="Titulo">Titulo:</label>
<input type="text" name="titulo" value="<?php if (isset($_SESSION['titulo'])) { echo $_SESSION['titulo'];} ?>">
<br>
<label for="Categoria">Categoria-Seccion:</label>
<select name="categoria" value= "<?php if(isset($_SESSION['categoria'])){echo $_SESSION['categoria'];} ?>">
<option value=""></option>
<?php
foreach (tomarcategorias() as $order =>$categorias){
$name = $categorias['name'];
$id = $categorias['id'];
$order =$categorias['order'];
if ($categorias['type'] == 'Articulos'){
echo "<optgroup label='", $name, "'>";
foreach(tomarsecciones('idcategoria', $id) as $ord => $secciones){
$ord = $secciones['order'];
echo "<option value='", $secciones['id'], "'><PRE>", $secciones['name'], "</option>";
}
}
}
?>
</select>
<br>
<textarea name="contenidotext" rows="15" cols="50" style="display:none;"></textarea>
<iframe name="contenido" id="contenido" style="width:300; height:100; background: white;"></iframe>
<br>
<label>Resumen del articulo</label>
<br>
<textarea name="resumentext" rows="5" cols="50" style="display:none;"></textarea>
<iframe name="resumen" id="resumen" style="background: white;"><?php if (isset($_SESSION['resumen'])) { echo $_SESSION['resumen'];}?></iframe>
<br>
<input type="submit" name="add_post" value="Subir post"/>
</form>
I have to be sincere, in the head there is a linked javascript but that contain functions for buttons for a simple wysiwyg and already try to make all the script together, in the same and different files, didn't change a thing.
Does anybody know where the bug is? and also,is there a way to view the errors of javascript script as in php?

AJAX mysqli interaction using PHP with MVC architecture

Today I'm facing another error related with AJAX.
I'm pretending to build a user registration system using ajax and php, with mvc architecture.
I built a login system without ajax and works without any problem, there is connectivity and interaction between all sides.
I'm almost sure that the error comes because of the JS file, I've passed my file through the JSHint to detect errors but nothing found, probably there is some mistake in the logic of the code.
First of all, before to post my code, I'll show you my data files structure to save you some headache thinking about the paths:
I'm going to paste the codes here and then I'll comment something about each piece of code.
View/register.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<link rel="stylesheet" href="../css/register.css">
<script src="../js/valReg.js"></script>
<section class="registerPage1">
<section class="registerPage2">
<form method="post" action="#" onsubmit="" id="regTopfit" name="regTopfit">
<ul>
<input type="button" value="Full Registration" id="advReg">
<li>Nombre:</li>
<li><input id="i_firstname" type="text" name="firstname" placeholder="Firstname"><input id="i_lastname" type="text" name="lastname" placeholder="Lastname"></li>
<br>
<li><input type="text" id="i_dni" placeholder="Your ID"></li>
<li><input id="i_username" type="text" name="username" placeholder="Username"><span id="user-result"></span></li>
<li><input id="i_email" type="email" name="email" placeholder="Email address"></li>
<span class="extraFieldsRegistration">
<li><input type="text" id="i_phone" placeholder="Phone number"></li>
<li><input type="text" id="i_address" placeholder="Address"></li>
<li><input type="text" id="i_city" placeholder="City"></li>
<li><input type="text" id="i_postal" placeholder="Postal Code"></li>
<li><input type="text" id="i_province" placeholder="Province"></li>
<li><input type="text" id="i_creditcard" placeholder="Credit Card number"></li>
</span>
<li><div id="regMailError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li>Crear contraseña:</li>
<li><input id="i_pass1" type="password" name="pass1" placeholder="6-20 caracteres" ></li>
error<li><div id="regPLenError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input id="i_pass2" type="password" name="pass2" placeholder="Repite la contraseña" ></li>
error<li><div id="regPMatchError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input type="checkbox" name="offers" value="Yes">Quiero recibir las últimas novedades de TopFIT</li>
<li><input id="i_conditions" type="checkbox" name="conditions" value="accepted" >He leído y acepto la política de privacidad.</li>
error<li><div id="regCondError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input type="button" id="register" value="Crea tu cuenta"></li>
<li><span id="result"></span></li>
</ul>
</form>
</section>
</section>
</body>
</html>
Nothing to say about the view.
Controller/register.php
<?php
//REGISTER controller
require "../model/backend.php";
$username = $_POST["#i_username"];
$email = $_POST["#i_email"];
$password = $_POST["#i_pass1"];
$firstname = $_POST["#i_firstname"];
$lastname = $_POST["#i_lastname"];
$dni = $_POST["#i_dni"];
$phone = $_POST["#i_phone"];
$address = $_POST["#i_address"];
$city = $_POST["#i_city"];
$postal = $_POST["#i_postal"];
$province = $_POST["#i_province"];
$creditcard = $_POST["#i_creditcard"];
$dbcom = new dbInteraction;
$dbcom->register($firstname, $lastname, $email, $dni, $phone, $address, $city, $postal, $province, $creditcard, $username, $password);
$dbcom->conclose();
?>
In that case, as you can see, I pick the values of my inputs and then I call my register function passing all the arguments to perform the registration. I think that everything is cool here too.
model/backend.php
<?php
//model!
class dbInteraction{
private $connection;
private $server = "127.0.0.1";
private $s_user = "root";
private $s_password ="";
private $db = "youtube";
private $dni;
private $firstname;
private $lastname;
private $username;
private $password;
private $phone;
private $address;
private $city;
private $postal;
private $province;
private $creditcard;
public function __construct(){
$this->connection = new mysqli($this->server, $this->s_user, $this->s_password, $this->db);
if($this->connection->connect_errno){
// echo $db->connect_error;
die('Sorry, we are having problems.');
}
}
public function conclose(){
$this->connection->close();
}
public function login($user, $password){
$this->user = $username;
$this->password = $password;
$query = "SELECT id, firstname, lastname, password FROM people WHERE username = '".$this->user."' AND password = '".$this->password."' ";
$myquery = $this->connection->query($query);
if ($row = mysqli_fetch_array($myquery)){// or die($this->connection->error)) {
session_start();
$_session['id'] = $row['id'];
$_session['firstname'] = $row['firstname'];
$_session['lastname'] = $row['lastname'];
echo 'Signed in.' , '<br>';
echo 'Welcome' , $_session['firstname'];
}else{
echo 'Check your data and try again.';
}
}
public function register($firstname, $lastname, $email, $dni, $phone, $address, $city, $postal, $province, $creditcard, $username, $password){
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->email = $email;
$this->dni = $dni;
$this->phone = $phone;
$this->address = $address;
$this->city = $city;
$this->postal = $postal;
$this->province = $province;
$this->creditcard = $creditcard;
$this->username = $username;
$this->password = $password;
$query = "INSERT INTO users (username, email, password, firstname, lastname, dni, phone, address, city, postal, province, creditcard) VALUES ('$username','$email','$password', '$firstname', '$lastname', '$dni', '$phone', '$address', '$city', '$postal', '$province', $creditcard)";
$myquery = $this->connection->query($query);
if ($row = mysqli_fetch_array($myquery)) {
session_start();
$_session['id'] = $row['id'];
$_session['firstname'] = $row['firstname'];
$_session['lastname'] = $row['lastname'];
echo 'You have been correctly registered. Welcome to TopFIT ', $_session['firstname'];
}else{
echo 'Something went wrong.';
}
}
public function newPassword($email){
$this->email = $email;
}
}
We have to focus in the register function, which is that simple as it looks. I think that I'm sure of the syntax that I used there.
JS File
$(document).ready(function(){
var showFull = $(".extraFieldsRegistration");
var fullReg = $("#advReg")
fullReg.click(function(){
showFull.css('display','inline');
});
$("#register").click(function(){
var mailValue = $("#i_email").val();
var usernameValue = $("#i_username").val();
var passwordValue = $("#i_pass1").val();
var passwordValue2 = $("#i_pass2").val();
var conditionsValue = $("#i_conditions").val();
var fnameValue = $("#i_firstname").val();
var lnameValue = $("#i_lastname").val();
var dniValue = $("#i_dni").val();
var phoneValue = $("#i_phone").val();
var addrValue = $("#i_address").val();
var cityValue = $("#i_city").val();
var postalValue = $("#i_postal").val();
var provValue = $("#i_province").val();
var ccValue = $("#i_creditcard").val();
var __mailError = document.getElementById('regMailError');
var __passLenError = document.getElementById('regPLenError');
var __passMatchError = document.getElementById('regMatchError');
var __condError = document.getElementById('regCondError');
if (mailValue === '' || passwordValue === '' || passwordValue2 === '' || usernameValue === ''){
alert('completa todos los campos');
}else{
if (passwordValue != passwordValue2){
alert('contraseñas distintas');
}else{
if (document.getElementById('conditions').checked){
$.ajax({
type: "POST",
url: "../controller/register.php",
data: {
username: usernameValue,
email: mailValue,
password: passwordValue,
firstname: fnameValue,
lastname: lnameValue,
dni: dniValue,
phone: phoneValue,
address: addrValue,
city: cityValue,
postal: postalValue,
province: provValue,
creditcard: ccValue
},
success: function(msg){
$("#result").html(msg);
},
error:function(){
alert('error');
}
});
}else{
alert('Debes aceptar las condiciones');
}
}
}
}); //click del register
}); //document ready
Ok, definitely I think that here there are mistakes.
In the beginning, there is a piece of code that pretends to modify the property of a view span, turning that property (display) from none to inline.
I previously used this code in other files and functions and it was working correctly, now I have no idea why it doesn't work.
Then there is the form validator and after that, if everything goes fine, inside an if, I try to perform the communication to the other mvc files passing the arguments that should be recorded to my db.
You'll notice that there are a lot of unused variables, I know, I'll use these ones to modify the css (in case of error) of some divs that I have in the view, but I decided to use alerts to debug. So where you see alert, there will be a css modifier.
I think that everything has logic but despite of my things, it doesn't work.
I've been looking for solutions and I saw that using JSON, probably I'll save time, code and problems but I have to do this without json, at least for now.
Did you find some error? Do you have a better idea to build this system?
As always, I'll appreciate your help.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- ADD / LOAD JQUERY HERE with the correct path -->
<script src="../js/jquery.js"></script>
</head>
<body>
<link rel="stylesheet" href="../css/register.css">
<script src="../js/valReg.js"></script>
<section class="registerPage1">
<section class="registerPage2">
<form method="post" action="#" onsubmit="" id="regTopfit" name="regTopfit">
<ul>
<input type="button" value="Full Registration" id="advReg">
<li>Nombre:</li>
<li><input id="i_firstname" type="text" name="firstname" placeholder="Firstname"><input id="i_lastname" type="text" name="lastname" placeholder="Lastname"></li>
<br>
<li><input type="text" id="i_dni" placeholder="Your ID"></li>
<li><input id="i_username" type="text" name="username" placeholder="Username"><span id="user-result"></span></li>
<li><input id="i_email" type="email" name="email" placeholder="Email address"></li>
<span class="extraFieldsRegistration">
<li><input type="text" id="i_phone" placeholder="Phone number"></li>
<li><input type="text" id="i_address" placeholder="Address"></li>
<li><input type="text" id="i_city" placeholder="City"></li>
<li><input type="text" id="i_postal" placeholder="Postal Code"></li>
<li><input type="text" id="i_province" placeholder="Province"></li>
<li><input type="text" id="i_creditcard" placeholder="Credit Card number"></li>
</span>
<li><div id="regMailError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li>Crear contraseña:</li>
<li><input id="i_pass1" type="password" name="pass1" placeholder="6-20 caracteres" ></li>
error<li><div id="regPLenError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input id="i_pass2" type="password" name="pass2" placeholder="Repite la contraseña" ></li>
error<li><div id="regPMatchError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input type="checkbox" name="offers" value="Yes">Quiero recibir las últimas novedades de TopFIT</li>
<li><input id="i_conditions" type="checkbox" name="conditions" value="accepted" >He leído y acepto la política de privacidad.</li>
error<li><div id="regCondError">Debes introducir una dirección de correo electrónico válida.</div></li>
<li><input type="button" id="register" value="Crea tu cuenta"></li>
<li><span id="result"></span></li>
</ul>
</form>
</section>
</section>
</body>
</html>

Categories