chained select with php mysql jQuery - php

I have a problem with chained selected script in my mvc structure
I have the form view and it contain this:
<div class="col-md-6 col-md-offset-3">
<form action="" method="post" role="form">
<div class="form-group">
<label>Nom de l'annonce:</label>
<input class="form-control input-lg" type="text" name="reg_name">
</div>
<div class="form-group">
<label>Choisi une catégorie:</label>
<select id="first_drop" class="form-control input-lg" name="categories">
<option disabled="disabled" selected="selected">choisi une categorie</option>
<?php
for ($i = 0; $i < count($dispalyCat); $i++) {
echo'<option value="' . $dispalyCat[$i]['id'] . '">' . $dispalyCat[$i]['categorieName'] . '</option>';
}
?>
</select>
</div>
<span id="loading" style="display: none;">
<img alt="Loading..." src="resources/images/loader.gif"/>
</span>
<div class="form-group" id="result" style="display: none">
<label>Choisi une sou-catégorie:</label>
<select id="second_drop" class="form-control input-lg" name="subCategories">
<?php
for ($i = 0; $i < count($dispalySubCat); $i++) {
echo'<option>' . $dispalySubCat[$i]['subCategorieName'] . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label>Prix:</label>
<input class="form-control input-lg" name="reg_pass2" type="text"/>
</div>
<div class="form-group">
<label>Surface:</label>
<input class="form-control input-lg" name="reg_pass2" type="text"/>
</div>
<div class="form-group">
<label>Description:</label>
<textarea class="form-control input-lg"></textarea>
</div>
<div class="form-group">
<label>Images:</label>
<input type="file" value="Ajouter l'annonce" class="form-control input-lg" multiple="" />
</div>
<div class="form-group">
<input type="submit" value="Ajouter l'annonce" class="btn btn-danger btn-lg" />
</div>
<input type="hidden" name="do" value="register"/>
</form>
</div>
and then the information was manipulated in the controller and this is the code:
<?php
$display = new Display('categories');
$dispalyCat = $display->getAllData();
$func = $_POST['func'];
$drop_val = $_POST['drop_val'];
if (isset($_POST['drop_val'])) {
$display2 = new Display('subcategories');
$dispalySubCat = $display2->getAllDataFromParentId($drop_val, 'categorieId');
}
include 'views/ajouterAnnonce.php';
?>
and the jquery script is:
$(document).ready(function () {
"use strict";
$('#loading').hide();
$('#first_drop').change(function () {
$('#loading').show();
$('#result').hide();
$.post('addAds.php', {
drop_val: $('select[name=categories]').val()
}, function (response) {
$('#result').fadeOut();
setTimeout("finishAjax('result', '" + escape(response) + "')", 400);
});
return false;
});
});
function finishAjax(id, response) {
"use strict";
$('#loading').hide();
$('#' + id).html(unescape(response));
$('#' + id).fadeIn();
}
when I tested this codes and I choose an option from the first select but I had an error message that the class Display not found in line 3 (in 2nd code) although it work in the first select and show me all the categories in the database
where is the problem ?

Divide the problem in 2 parts:
1.- Server side:
//In your file php
<?php
// get values from url, because for a query from a select, is not necessary use request POST
// then
echo $.GET['value'];
// Here you use queries or you do procedures for obtain data related with $.GET['value']
// Last you return data on format Json
?>
// This file php, has a url, for example: get_data_select.php
// Then whitout jquery or javascript, you should test the url, on the browser.
// http://somedomain/get_data_select.php?value=12
// If it return data with header json. server side works good.
2.- Client side: you change selected
$('#idselect').on("change", function(){
var values = '?value=' + $('#idselect').val();
$.get('http://somedomain/get_data_select.php' + values, function(res){
console.log("response", res);
callFunctionRender(res);
});
});
function callFunctionRender(data) {
// here You have data from server
// then you should rendered
};

Related

How to fix Parameter must be an array or an object that implements Countable

I have question, Why does I encounter this error on my response, I have module where I need to upload multiple using Ajax and php as backend.
Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\PSMID\Function\mediaAddFunction.php on line 17
9
Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\PSMID\Function\mediaAddFunction.php on line 17
I will share to you guys my sample code that I already made.
Front End:
var storeFile =[];
$('#media_file').on('change',function(e){
var files = e.target.files;
$.each(files, function(i, file) {
storeFile.push(file);
})
})
$('.news_media_button').on('click',function(){
const media_pages = $('#media_pages').val();
const media_title = $('#media_title').val();
//const media_content = $('#media_content').val();
const ck_editor_content = CKEDITOR.instances['media_content'].getData();
const media_link = $('#media_link').val();
const media_file = $('#media_file').prop('files')[0];
const hidden_auth_user = $('#hidden_auth_user').val();
const data = new FormData();
data.append('media_pages',media_pages);
data.append('media_title',media_title);
data.append('media_content',ck_editor_content);
data.append('media_link',media_link);
data.append('files',storeFile[0]);
data.append('hidden_auth_user',hidden_auth_user);
Swal.fire({
title: 'Are you sure to save this data?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#008B74',
confirmButtonText: 'Okay'
}).then((result) => {
if (result.value) {
$.ajax({
url:'./Function/mediaAddFunction.php',
data:data,
type:'POST',
dataType:'JSON',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success:function(response){
console.log(response);
// Swal.fire(
// 'Success!',
// 'Data Saved.',
// 'success'
// )
// if(response.status == 'Success') {
// location.reload();
// }
},
error:function(response) {
console.log(response);
}
});
}
})
});
Back End:
for($i=0;$i<count($_FILES["files"]["name"]);$i++)
{
echo $_FILES["files"]["name"][$i];
}
Html:
<div class="container-fluid">
<div class="jumbotron" style="background-color:white">
<div class="container-fluid">
<input type="hidden" value="" id="hidden_auth_user" name="">
<div class="container">
<div class="row">
<h2 class="col-md-10">News Media</h2>
<button class="btn btn-primary news_media_button col-md-2 form-control" id="custom_button">Save Data</button>
</div>
<hr>
<br><br>
<div class="row">
<div class="col-md-6">
<label style="font-weight: 500; font-size:14px;">Choose Media Page</label>
<select class="form-control" id="media_pages">
<option value="announcement">Announcement</option>
<option value="news_online">News Online</option>
<option value="info_graphics">Info Graphics</option>
</select>
</div>
<div class="col-md-6">
<label style="font-weight: 500; font-size:14px;">Title</label>
<input type="text" name="media_title" id="media_title" placeholder="Title" class="form-control">
</div>
</div>
<br><br>
<div class="row">
<div class="col-md-6">
<label style="font-weight: 500; font-size:14px;">File Upload</label>
<div class="custom-file">
<input type="file" name="files[]" multiple placeholder="Title" id="media_file" value="" class="custom-file-input form-control">
<label class="custom-file-label" for="inputGroupFile04"></label>
</div>
</div>
<div class="col-md-6">
<label style="font-weight: 500; font-size:14px;">File Link</label>
<input type="text" name="" placeholder="Link" id="media_link" value="" class=" form-control">
</div>
</div>
<br><br>
<div class="row">
<div class="col-md-12">
<label style="font-weight: 500; font-size:14px;">Content</label>
<textarea cols="12" name="content_article" class="form-control" id="media_content"></textarea>
<script>
CKEDITOR.replace('content_article');
</script>
</div>
</div>
<br><br>
<div class="row">
<div class="col-md-12">
</div>
</div>
</div>
</div>
</div>
</div>
Solved your issue:
You have posted your php code exactly like below:
Back End:
for($i=0;$i<count($_FILES["files"]["name"]);$i++)
{
echo $_FILES["files"]["name"][$i];
}
Using your code I have:
Notice: Undefined index: files in D:\Web\test\files\files-2.php on
line 6
Warning: count(): Parameter must be an array or an object that
implements Countable in D:\Web\test\files\files-2.php on line 6
To fix your code you have to change your Back End with:
if (isset($_FILES["files"]["name"])) {
for ($i = 0; $i < count($_FILES["files"]["name"]); $i++) {
echo $_FILES["files"]["name"][$i];
}
}
This will solve your issue... the magic code is:
if (isset($_FILES["files"]["name"])) {
...
}
Just tested my files-1.php file and there is no warning or error, it works fine on real servers with PHP/7.3.6 (64it) and PHP/7.2.17 (64bit)... also tested on my localhost with same PHP versions...
files-1.php:
<?php
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
<label for="files1">File:</label> <input type="file" id="files1" name="files[]" size="35"><br>
<label for="files2">File:</label> <input type="file" id="files2" name="files[]" size="35"><br>
<input type="submit" value="Send">
</form>
<?php
if (isset($_FILES['files']['name'])) {
for ($index = 0; $index < count($_FILES['files']['name']); $index++) {
if ($_FILES['files']['name'][$index] != "") {
echo $_FILES['files']['name'][$index];
}
}
}
?>
This my example below (files-2.php) has a very little change according to your example, and here I have no warning or error... working on PHP/7.3.6 and PHP/7.2.17 on real servers... also tested on my localhost with same PHP versions...
files-2.php:
<?php
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
<label for="files">File:</label> <input type="file" id="files" name="files[]" size="35" multiple><br>
<input type="submit" value="Send">
</form>
<?php
if (isset($_FILES['files']['name'])) {
for ($index = 0; $index < count($_FILES['files']['name']); $index++) {
if ($_FILES['files']['name'][$index] != "") {
echo $_FILES['files']['name'][$index];
}
}
}
?>
Source html generated on fly by PHP:
<form action="/files/files-2.php" enctype="multipart/form-data" method="post">
<label for="files">File:</label> <input type="file" id="files" name="files[]" size="35" multiple><br>
<input type="submit" value="Send">
</form>
test.zip
As you can see there is no error or warning...
Online testing:
https://3v4l.org/tqgUp
http://sandbox.onlinephpfunctions.com/code/4e0a5326fc2508e1ca4db90051061b4584b86eae
Hope this helps.

Get data from database and PHP using Ajax

I want to send data from text input and set result (from database) into another inputs using Ajax
I've tried to parse result into JSON using json_encode(), for some reason it didn't work and as solution I created a div in the result PHP page which with it I get the div with content
index.php
<div class="form-group col-4">
<label for=""> Code:<span style="color:red;">*</span></label>
<input type="text" class="form-control form-control-sm" id="codecli" name="codecli" onkeyup="showinfoclient()" required>
</div>
<div class="form-group col-8 " id="mess">
</div>
</div>
<div class="minfoclient">
<div class="form-row">
<div class="form-group col-6">
<label for=""> Lastname:<span style="color:red;">*</span></label>
<input type="text" class="form-control form-control-sm" id="lastname" name="lastname" value="" required>
</div>
<div class="form-group col-6">
<label for=""> Firstname:<span style="color:red;">*</span></label>
<input type="text" class="form-control form-control-sm" id="firstname" name="firstname" value="" required>
</div>
</div>
client.php
if ($_REQUEST['idcli']) {
$idcli = strip_tags($_POST['idcli']);
$iduser = $_SESSION['user_id'];
$clients = $conn->query("SELECT * FROM `client` WHERE
`Current_user`=$iduser AND `id_client`='$idcli'");
while($client = $clients->fetch_assoc()){
?>
<div class="minfoclient">
<div class="form-row">
<div class="form-group col-6">
<label for=""> Lastname:<span style="color:red;">*</span></label>
<input type="text" id="nom" class="form-control form-control-sm namm" name="lastname" value="<?=$client['lastname'];?>">
</div>
<div class="form-group col-6">
<label for=""> Firstname:<span style="color:red;">*</span></label>
<input type="text" id="prenom" class="form-control form-control-sm" name="firstname" value="<?=$client['firstname'];?>">
</div>
</div> ...
this code worked but not as expected because it blocks other tasks
function showeinfoclient(){
var iDClient = $('#codecli').val();
if (iDClient) {
$.ajax({
type:'POST',
url:'client.php',
data:'idcli='+iDClient,
success:function(data){
$('.minfoclient').html(data);
}
});
}
}
as solution I hope you provide a simple code (AJAX, JSON, and PHP)
In client.php
$response=array();
while($client = $clients->fetch_assoc()){
$response[]=$client;
}
echo json_encode($response);
After that inside ajax response you have to make for loop for each the client info create input elements.
ajax response:-
success:function(data){
var clients=$.parsJSON(data);
var htmlData="";
if(client.length>0){
for(i=0;i<client.length;i++){
htmlData += "<input type='text' name='firstname' value='"+client[i].firstname+"'><br>";
htmlData += "<input type='text' name='lastname' value='"+client[i].lastname+"'><br>";
}
$('.minfoclient').html(htmldata);
}
}
please update JS code and PHP code.
JS Code :
function showinfoclient(){
var iDClient = $('#codecli').val();
if (iDClient) {
$.ajax({
type:'POST',
url:'client.php',
data:JSON.stringify(iDClient),
dataType:'json',
})
.done(function( json ) {
$('#lastname').val(json.lastname);
$('#firstname').val(json.firstname);
})
.fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
});
}
}
PHP Code (client.php):
$input = urldecode(file_get_contents('php://input'));
$iDClient = json_decode($input,true);
// code to fetch firstname and lastname from database
$client = array('firstname' => 'John', 'lastname' => 'Doe'); // raw data
echo json_encode($client);

2 forms with 1 single submit button

I am looking to submit 2 forms with 1 single submission button. So 2 lines that will be added in my database at the time of submission.
here's what i started doing:
HTML:
<form enctype="multipart/form-data" method="POST" action="{$link->getModuleLink('blocksouhaits', 'create', ['action' => 'create'], true)|escape:'html'}">
<div class="col-md-6">
<h1>{l s='Souhait N°1' mod='blocksouhaits'}</h1>
<input type="hidden" name="souhait[]" value="1">
<div class="form-group row">
<label for="nbVoyager_1"
class="col-sm-10 col-form-label">{l s='Nombre de voyageurs' mod='blocksouhaits'}</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="nbVoyager_1">
</div>
</div>
<div class="infos-voyager_1"></div>
<div class="form-group row">
<label class="col-sm-4 col-form-label" for="locationVoyager_1">{l s='Votre location' mod='blocksouhaits'}</label>
<div class="col-sm-8">
<select class="form-control" name="locationVoyager_1" id="locationVoyager_1">
{foreach $productLoc as $pl}
<option value="{$pl.id_product}">{$pl.name}</option>
{/foreach}
</select>
</div>
</div>
</div>
<div class="col-md-6">
<h1>{l s='Souhait N°2' mod='blocksouhaits'}</h1>
<input type="hidden" name="souhait[]" value="2">
<div class="form-group row">
<label for="nbVoyager_2"
class="col-sm-10 col-form-label">{l s='Nombre de voyageurs' mod='blocksouhaits'}</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="nbVoyager_2">
</div>
</div>
<div class="infos-voyager_2"></div>
<div class="form-group row">
<label class="col-sm-4 col-form-label" for="locationVoyager_2">{l s='Votre location' mod='blocksouhaits'}</label>
<div class="col-sm-8">
<select class="form-control" name="locationVoyager_2" id="locationVoyager_2">
{foreach $productLoc as $pl}
<option value="{$pl.id_product}">{$pl.name}</option>
{/foreach}
</select>
</div>
</div>
</div>
<div class="col-sm-12">
<button class="btn btn-primary float-xs-right" type="submit" name="submitSouhaits">
{l s='Envoyer la demande de souhait' mod='customerannonces'}
</button>
</div>
</form>
PHP:
public function postProcess()
{
if (Tools::getValue('action') == 'create') {
if (Tools::isSubmit('submitSouhaits')) {
$submit = $_POST;
dump($submit);
}
}
}
JS:
$(document).ready(function () {
$("#nbVoyager_1").change(function () {
var i = 0;
var rows = $(this).val();
$(".infos-voyager_1").empty();
for (i = 0; i < rows; i++) {
$(".infos-voyager_1").append(
'<div class="form-group row">' +
'<div class="col-sm-6">' +
'<input type="text" class="form-control" id="firstnameVoyager_1" name="firstnameVoyager_1[]" placeholder="Prénom">' +
'</div>' +
'<div class="col-sm-6">' +
'<input type="text" class="form-control" id="lastnameVoyager_1" name="lastnameVoyager_1[]" placeholder="Nom">' +
'</div>' +
'</div>');
}
});
$("#nbVoyager_2").change(function () {
var j = 0;
var rows = $(this).val();
$(".infos-voyager_2").empty();
for (j = 0; j < rows; j++) {
$(".infos-voyager_2").append(
'<div class="form-group row">' +
'<div class="col-sm-6">' +
'<input type="text" class="form-control" id="firstnameVoyager_2" name="firstnameVoyager_2[]" placeholder="Prénom">' +
'</div>' +
'<div class="col-sm-6">' +
'<input type="text" class="form-control" id="lastnameVoyager_2" name="lastnameVoyager_2[]" placeholder="Nom">' +
'</div>' +
'</div>');
}
});
});
in the form there is:
a field to define the number of people, this will automatically add X fields according to this number and another fields to choose the location. The 2 forms are identical.
The result of the var_dump to the submission.
But I do not see how to do the submission properly in PHP. Do you have a solution to submit to me?
Thanks for help.

AJAX POST Object return partial data

I'm using wamp64 webserver and I'm try to post some values to a PHP script to create a PDF (with TCPDF library).
I've a lot (more or less 80) of field to pass (POST) with AJAX and the problem seems to be the amount of variable (or memory, I don't know).
If I try to pass less variable everything it is OK, but when I try to POST the complete set of fields PHP returns an error regarding indexing of Object I'm passing.
This is what I'm try to POST:
$('#btnGeneraPDF').click(function() {
var campi = {
//DATI RICHIESTA VERIFICA
dataCompilazione: $('#data-compilazione').val(),
dataAccettazione: $('#data-accettazione').val(),
rifPreventivo: $('#cod-preventivo').val(),
codRichiesta: $('#cod-rdv').val(),
//DATI UTENTE METRICO
UMragSociale: $('#UM-ragSociale').val(),
UMpiva: $('#UM-piva').val(),
UMrea: $('#UM-rea').val(),
//DATI REFERENTE
REFnominativo: $('#ref-nominativo').val(),
REFtelefono: $('#ref-telefono').val(),
REFemail: $('#ref-email').val(),
REFindirizzo: $('#ref-indirizzo').val(),
REFcomune: $('#ref-comune').val(),
REFprovincia: $('#ref-provincia').val(),
REFcap: $('#ref-cap').val(),
REFnote: $('#ref-note').val(),
STRtipo1: $('#STRtipo1 :selected').text(),
STRmarca1: $('#STRmarca1').val(),
STRmodello1: $('#STRmodello1').val(),
STRmatricola1: $('#STRmatricola1').val(),
STRpistole1: $('#STRpistole1').val(),
STRportata1: $('#STRportata1').val(),
STRprePostPay1: $('#STRprePostPay1 :checked').val(),
STRnote1: $('#STRnote1').val(),
STRtipo2: $('#STRtipo2 :selected').text(),
STRmarca2: $('#STRmarca2').val(),
STRmodello2: $('#STRmodello2').val(),
STRmatricola2: $('#STRmatricola2').val(),
STRpistole2: $('#STRpistole2').val(),
STRportata2: $('#STRportata2').val(),
STRprePostPay2: $('#STRprePostPay2 :checked').val(),
STRnote2: $('#STRnote2').val(),
STRtipo3: $('#STRtipo3 :selected').text(),
STRmarca3: $('#STRmarca3').val(),
STRmodello3: $('#STRmodello3').val(),
STRmatricola3: $('#STRmatricola3').val(),
STRpistole3: $('#STRpistole3').val(),
STRportata3: $('#STRportata3').val(),
STRprePostPay3: $('#STRprePostPay3 :checked').val(),
STRnote3: $('#STRnote3').val(),
STRtipo4: $('#STRtipo4 :selected').text(),
STRmarca4: $('#STRmarca4').val(),
STRmodello4: $('#STRmodello4').val(),
STRmatricola4: $('#STRmatricola4').val(),
STRpistole4: $('#STRpistole4').val(),
STRportata4: $('#STRportata4').val(),
STRprePostPay4: $('#STRprePostPay4 :checked').val(),
STRnote4: $('#STRnote4').val(),
STRtipo5: $('#STRtipo5 :selected').text(),
STRmarca5: $('#STRmarca5').val(),
STRmodello5: $('#STRmodello5').val(),
STRmatricola5: $('#STRmatricola5').val(),
STRpistole5: $('#STRpistole5').val(),
STRportata5: $('#STRportata5').val(),
STRprePostPay5: $('#STRprePostPay5 :checked').val(),
STRnote5: $('#STRnote5').val(),
STRtipo6: $('#STRtipo6 :selected').text(),
STRmarca6: $('#STRmarca6').val(),
STRmodello6: $('#STRmodello6').val(),
STRmatricola6: $('#STRmatricola6').val(),
STRpistole6: $('#STRpistole6').val(),
STRportata6: $('#STRportata6').val(),
STRprePostPay6: $('#STRprePostPay6 :checked').val(),
STRnote6: $('#STRnote6').val(),
STRtipo7: $('#STRtipo7 :selected').text(),
STRmarca7: $('#STRmarca7').val(),
STRmodello7: $('#STRmodello7').val(),
STRmatricola7: $('#STRmatricola7').val(),
STRpistole7: $('#STRpistole7').val(),
STRportata7: $('#STRportata7').val(),
STRprePostPay7: $('#STRprePostPay7 :checked').val(),
STRnote7: $('#STRnote7').val(),
STRtipo8: $('#STRtipo8 :selected').text(),
STRmarca8: $('#STRmarca8').val(),
STRmodello8: $('#STRmodello8').val(),
STRmatricola8: $('#STRmatricola8').val(),
STRpistole8: $('#STRpistole8').val(),
STRportata8: $('#STRportata8').val(),
STRprePostPay8: $('#STRprePostPay8 :checked').val(),
STRnote8: $('#STRnote8').val(),
note: $('#rdv-note').val()
};
//GENERAZIONE PDF
$.ajax({
type: 'POST',
url: 'mysite/pdf/save.php',
async: true,
cache: false,
data: {data: campi},
beforeSend: function(){
},
success: function(response) {
console.log (campi);
setTimeout( function() {
console.log("AJAX SUCCESS");
}, 10 );
if (!response.status) {
alert("Error calling save");
return;
}
if (response.status != 'OK') {
alert(response.status);
return;
}
// We had a response and it was "OK". We're good.
window.open("mysite/pdf/pdfTest.php");
},
error: function( XMLHttpRequest, textStatus, errorThrown ) {
console.log("AJAX ERROR: \n" + errorThrown);
console.log("AJAX ERROR: \n" + textStatus);
}
});
})
This is save.php
<?php // this is save.php
session_start();
// DO NOT just copy from _POST to _SESSION,
// as it could allow a malicious user to override security.
// Use a disposable variable key, such as "data" here.
if (array_key_exists('data', $_POST)) {
$_SESSION['data'] = $_POST['data'];
$_SESSION['data.timestamp'] = time();
// Let us let the client know what happened
$msg = 'OK';
} else {
$msg = 'No data was supplied';
}
Header('Content-Type: application/json; charset=utf8');
die(json_encode(array('status' => $msg)));
?>
The HTML code is:
<div class="tab-pane fade in active" id="tab1">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="STRtipo" class="control-label sr-only">Tipo</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<select name="select2" id="STRtipo1" class="form-control">
<option value=" "> </option>
<option value="NAZ">NAZ</option>
<option value="MID">MID</option>
</select>
</div>
</div>
<label for="STRmarca" class="control-label sr-only">Marca</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<input type="text" class="form-control" id="STRmarca1" placeholder="Marca">
</div>
</div>
<label for="STRmodello" class="control-label sr-only">Modello</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<input type="text" class="form-control" id="STRmodello1" placeholder="Modello">
</div>
</div>
<label for="STRmatricola" class="control-label sr-only">Matricola</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<input type="text" class="form-control" id="STRmatricola1" placeholder="Matricola">
</div>
</div>
<label for="STRpistole" class="control-label sr-only">Pistole</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<input type="text" class="form-control" id="STRpistole1" placeholder="Pistole">
</div>
</div>
<label for="STRportata" class="control-label sr-only">Pistole</label>
<div class="col-sm-2">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<input type="text" class="form-control" id="STRportata1" placeholder="Portata">
</div>
</div>
</div>
</form>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-sm-2 fancy-checkbox">
<input type="checkbox" id="STRprePostPay1" value="1">
<span>Pre / Post Pay</span>
</label>
<label for="STRnote" class="col-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-book"></i></span>
<input type="text" class="form-control" id="STRnote1" placeholder="Note">
</div>
</label>
</div>
</form>
</div>
And it is made for each of 8 instruments, using jQuery:
var tabContent=$('#tab1').clone();
for (i=2;i<=nTab;i++){
$('#tab' + i).append(tabContent.html());
}
for (i=2;i<=nTab;i++){
$('#tab'+i+' select').attr('id','STRtipo' + i);
$('#tab'+i).find('#STRmarca1').attr('id','STRmarca' + i);
$('#tab'+i).find('#STRmodello1').attr('id','STRmodello' + i);
$('#tab'+i).find('#STRmatricola1').attr('id','STRmatricola' + i);
$('#tab'+i).find('#STRpistole1').attr('id','STRpistole' + i);
$('#tab'+i).find('#STRportata1').attr('id','STRportata' + i);
$('#tab'+i).find('#STRprePostPay1').attr('id','STRprePostPay' + i);
$('#tab'+i).find('#STRnote1').attr('id','STRnote' + i);
}
This code doesn't work... but if i comment some field in the object 'campi', everything works fine. In particular the problem returned from PHP is on 'STRprePostPay1' variable... It tell that is not passed, and if I put a print_r function, I see that that variable is not passed.
Can someone help me?
THanks

Jquery ajax posts twice

I got an ajax issue I can't get my head around. I'm using a ajax post method to send an email. But everytime I send one the post happens 2 times. I've tried adding preventDefault and stopPropagation but it doesn't seem to do the trick.
Jquery
$(document).ready(function()
{
$("#submit_btn").click(function(event)
{
event.preventDefault();
event.stopPropagation();
var proceed = true;
var submit = $('#submit_btn');
$("#contact_form input, #contact_form textarea").each(function () {
$(this).closest("div").removeClass('has-error');
if(!$.trim($(this).val())) {
$(this).closest("div").addClass('has-error');
proceed = false;
}
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).closest("div").addClass('has-error');
proceed = false;
}
});
if(proceed){
post_data = {
'user_name' : $('input[name=name]').val(),
'user_email' : $('input[name=email]').val(),
'subject' : $('select[name=subject]').val(),
'msg' : $('textarea[name=message]').val()
};
$.ajax({
type: 'POST',
url: "./mail.php",
data: post_data,
beforeSend: function() {
submit.html('Sending...');
},
success: function(data){
output = '<div class="alert alert-success" role="alert">Hi ' + $('input[name=name]').val() + ' Thank you for your email</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
},
error: function(){
output = '<div class="alert alert-danger" role="alert">Something went wrong. Please try again</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
}
});
return false;
}
else{
output = '<div class="alert alert-danger" role="alert">Please fill in the required fields so I can get back to you !</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
}
});
$("#contact_form input, #contact_form textarea").keyup(function() {
$(this).closest("div").removeClass('has-error');
$("#contact_form").find("#contact_results").slideUp();
});
});
HTML
<div class="clear" id="contact">
<h3>Contact Me</h3>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<form role="form" id="contact_form" action="">
<div class="form-group">
<label for="name">Name</label><input name="name" type="text" placeholder="Name" class="form-control" id="name" />
</div>
<div class="form-group">
<label for="email">Email address</label>
<input name="email" type="email" placeholder="E-Mail" class="form-control" id="email" />
</div>
<div class="form-group">
<label for="subject">Subject</label>
<select name="subject" class="form-control" id="subject">
<option value="General Question">General Question</option>
<option value="Hire me!">Hire me !</option>
<option value="Partner with me!">Partner with me !</option>
</select>
</div>
<div class="form-group">
<label for="message">Message</label><textarea name="message" placeholder="Message" id="message" class="form-control" rows="5"></textarea>
</div>
<button type="submit" class="btn btn-default" id="submit_btn">Send</button>
<div id="contact_results"></div>
</form>
</div>
</div>
</div>
</div>
If someone could point me in the right direction that would be much appreciated.
Try changing $("#submit_btn").click(function(event) to $("#submit_btn").one('click',function(event)
If that doesn't work, check that the JS is not being loaded twice

Categories