I have problem with POST data from array in dynamically generating inputs fields.
I am using jquery for generate and would like to send from ajax, i know how to do it probably.
Everytime when i POST data, i had only one value in array. Could you help me with that?
Many thanks.
<div class = "col-md-4">
<div class="form-group multiple-form-group input-group">
<select class = "form-control" name = "cargos[]" required>
<option value = "#" selected disabled>Wybierz ładunek</option>
<?php
$sql = mysqli_query($conn, "SQL Code");
while($row = mysqli_fetch_assoc($sql)){ ?>
<option value = "<?php echo ?>"><?php echo ?></option>
<?php } ?>
</select>
<input type="number" name="values[]" class="form-control">
<span class="input-group-btn">
<button type="button" class="btn btn-success btn-add">+</button>
</span>
</div>
</div>
Code from jQuery to generating multiple fields
(function ($) {
$(function () {
var addFormGroup = function (event) {
event.preventDefault();
var $formGroup = $(this).closest('.form-group');
var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
var $formGroupClone = $formGroup.clone();
$(this)
.toggleClass('btn-success btn-add btn-danger btn-remove')
.html('–');
$formGroupClone.find('input').val('');
$formGroupClone.find('.concept').text('Phone');
$formGroupClone.insertAfter($formGroup);
var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
if ($multipleFormGroup.data('max') <= countFormGroup($multipleFormGroup)) {
$lastFormGroupLast.find('.btn-add').attr('disabled', true);
}
};
var removeFormGroup = function (event) {
event.preventDefault();
var $formGroup = $(this).closest('.form-group');
var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
if ($multipleFormGroup.data('max') >= countFormGroup($multipleFormGroup)) {
$lastFormGroupLast.find('.btn-add').attr('disabled', false);
}
$formGroup.remove();
};
var selectFormGroup = function (event) {
event.preventDefault();
var $selectGroup = $(this).closest('.input-group-select');
var param = $(this).attr("href").replace("#","");
var concept = $(this).text();
$selectGroup.find('.concept').text(concept);
$selectGroup.find('.input-group-select-val').val(param);
}
var countFormGroup = function ($form) {
return $form.find('.form-group').length;
};
$(document).on('click', '.btn-add', addFormGroup);
$(document).on('click', '.btn-remove', removeFormGroup);
$(document).on('click', '.dropdown-menu a', selectFormGroup);
}); })(jQuery);
For importing data to database i am using:
$cargo = $_POST['cargo'];
$tonnages = $_POST['tonnages'];
for($x = 0; $x < count($cargos); $x++) {
mysqli_query($conn, "INSERT INTO cargos_specialOrder (specialOrder_ID, cargo_ID, tonnages) VALUES ('$index', '$cargos[$x]', '$tonnages[$x]')");
}
$("form").submit(function(e) {
e.preventDefault();
var formData = new FormData($("form")[0]);
$.ajax({
type: 'POST',
url: 'php/newSpecialOrder.php',
data: formData,
success: function(response) {
if(response == 'done') {
$.confirm({
title: 'Gotowe',
content: 'Zgłoszenie zostało wysłane',
type: 'green',
typeAnimated: true,
buttons: {
close: function(){
location.href = "index.php"
}
}
});
}
},
cache: false,
contentType: false,
processData: false
});
});
you have a problem in this section of the code:
<?php
$sql = mysqli_query($conn, "SQL Code");
while($row = mysqli_fetch_assoc($sql)){ ?>
<option value = "<?php echo ?>"><?php echo ?></option>
<?php } ?>
echo must have a parameter to be printed on screen, so fix this part and you should be able to submit.
Related
I am trying to add products with AJAX into the cart from the products page with the quantity field. the addition of the first item is working fine with desired quantity but when I try to add a second product with a different quantity it keeps sending the first product quantity into the database.
here is my code
HTML
<div class="pro-quantity">
<div class="quantity">
<button class="decrement-btn">-</button>
<input type="text" id="sqty" maxlength="2" max="10" value="1" class="qty-input">
<button class="increment-btn">+</button>
</div>
</div>
<div class="pro-id-2">
<div class="tw-flex tw-justify-between tw-items-center">
<button class="pro-id-link" value="<? echo $id; ?>" id="add-deposit">Add to Cart</button>
<input type="hidden" name="" id="cus_id" value="<? echo $_SESSION['u_id']; ?>">
</div>
</div>
JS (for increment and decrement quantity)
$(document).ready(function () {
$('.increment-btn').click(function (e) {
e.preventDefault();
var incre_value = $(this).parents('.quantity').find('.qty-input').val();
var value = parseInt(incre_value, 10);
value = isNaN(value) ? 0 : value;
if (value < 10) {
value++;
$(this).parents('.quantity').find('.qty-input').val(value);
}
});
$('.decrement-btn').click(function (e) {
e.preventDefault();
var decre_value = $(this).parents('.quantity').find('.qty-input').val();
var value = parseInt(decre_value, 10);
value = isNaN(value) ? 0 : value;
if (value > 1) {
value--;
$(this).parents('.quantity').find('.qty-input').val(value);
}
});
});
JS (AJAX code)
$(document).ready(function () {
$(document).on("click", "#add-deposit", function (e) {
e.preventDefault();
var element = $(this);
var id = $(this).val();
var cus_id = $('#cus_id').val();
var sqty = $('#sqty').val();
$.ajax({
url: "add_deposit_script.php",
type: "POST",
data: {
id: id,
cus_id: cus_id,
sqty: sqty
},
success: function (data) {
if (data === 'success') {
Swal.fire({
icon: 'success',
title: 'Success.',
text: 'Success! This product has been added into Deposit.'
})
}
if (data === 'error') {
Swal.fire({
icon: 'error',
title: 'Error.',
text: 'Error! This Product is already in your deposit.'
})
}
element.prop('disabled', true);
element.html('Added');
getcartnumber();
}
});
});
});
I'm using a filter based on jQuery ajax. Filter is working quite perfectly but the issue is because it's using the ajax call due to yearly based search so it's a bit slow , I mean when user selects year he/she have to wait for next option to enable and as options are based on year so they take some time to load in filter.
I need to sort this out quickly can you please help me out here ?
Below is the php and jQuery code for that please see and help me out . Thanks
Here is code for form which is working as filters:
<form id="search-product" method="GET" action="<? bloginfo('url') ?>/product/">
<div class="search-field">
<select id="select-yr" name="yr" required="">
<option value="">Year</option>
<?php foreach(get_data_yrs() as $yr) { ?>
<option<?= (isset($_GET['yr']) && $_GET['yr'] == $yr ? " selected" : "") ?>><?= $yr ?></option>
<?php } ?>
</select>
</div>
<div class="search-field">
<select id="select-make" name="make" required="" data-selected="<?= (isset($_GET['make']) ? $_GET['make'] : "") ?>">Select make</select>
</div>
<div class="search-field">
<select id="select-model" name="model" required data-selected="<?= (isset($_GET['model']) ? $_GET['model'] : "") ?>">Select model</select>
</div>
<div class="search-field">
<select id="select-qualifier" name="qualifier" data-selected="<?= (isset($_GET['qualifier']) ? $_GET['qualifier'] : "") ?>">Select qualifier</select>
</div>
<div class="search-sub">
<input type="submit" name="srh" value="Search">
<input type="reset" value="Reset">
</div>
</form>
And here is the jQuery :
$("#select-yr").on("change", onYearChange);
$("#select-make").on("change", onMakeChange);
$("#select-model").on("change", onModelChange);
$("#select-yr").each(function() {
if($(this).val() != "") {
$(this).trigger("change");
}
});
function onYearChange() {
var $selectors = $("#select-make, #select-model, #select-qualifier");
var $selector = $("#select-make");
var $yr = $("#select-yr").val();
var $selected = $selector.data("selected");
$selectors.empty();
$selector.append('<option>Please wait</option>');
// $selector.attr('disabled', 'disabled');
$.ajax({
url: ajax_url,
data: {
action: 'get_data_makes',
yr: $yr
},
dataType: 'JSON',
success: function(data) {
$selectors.empty();
$selector.append('<option value="">Select Make</option>');
if(data.length > 0) {
for(var i in data) {
$selector.append('<option'+(data[i] == $selected ? " selected" : "")+'>'+data[i]+'</option>');
}
}
if($selected) {
$selector.trigger('change');
}
$selector.removeAttr('disabled');
}
});
}
function onMakeChange() {
var $selectors = $("#select-model, #select-qualifier");
var $selector = $("#select-model");
var $make = $("#select-make").val();
var $yr = $("#select-yr").val();
var $selected = $selector.data("selected");
$selectors.empty();
$selector.append('<option>Please wait</option>');
$selector.attr('disabled', 'disabled');
$.ajax({
url: ajax_url,
data: {
action: 'get_data_models',
make: $make,
yr: $yr
},
dataType: 'JSON',
success: function(data) {
$selectors.empty();
$selector.append('<option value="">Select Model</option>');
if(data.length > 0) {
for(var i in data) {
$selector.append('<option'+(data[i] == $selected ? " selected" : "")+'>'+data[i]+'</option>');
}
}
if($selected) {
$selector.trigger('change');
}
$selector.removeAttr('disabled');
}
});
}
function onModelChange() {
var $selectors = $("#select-qualifier");
var $selector = $("#select-qualifier");
var $make = $("#select-make").val();
var $yr = $("#select-yr").val();
var $model = $("#select-model").val();
var $selected = $selector.data("selected");
$selectors.empty();
$selector.append('<option>Please wait</option>');
$selector.attr('disabled', 'disabled');
$.ajax({
url: ajax_url,
data: {
action: 'get_data_qualifiers',
make: $make,
yr: $yr,
model: $model
},
dataType: 'JSON',
success: function(data) {
$selectors.empty();
$selector.append('<option value="">Select Qualifier</option>');
if(data.length > 0) {
for(var i in data) {
$selector.append('<option'+(data[i] == $selected ? " selected" : "")+'>'+data[i]+'</option>');
}
}
if($selected) {
$selector.trigger('change');
}
$selector.removeAttr('disabled');
}
});
}
This is a code with DropDown list which can update the database upon on change, it doesn't work for some reason. I realize that the value $ gp_name didn't send out, can someone help me to fix it?
<select name='status' id='status'>
<option value="<?php echo $status ?>"><?php echo $status ?></option>
<option value="Inquiry">Inquiry</option>
</select>
<input type="hidden" name="gp_name" id="gp_name" value="<?php echo $gp_name;?>" />
<div id="autosavenotify"></div>
<script>
$(document).ready(function() {
var gp_name = $('#gp_name').val();
$('select').on('change', function() {
var statusVal = $(this).val();
var gp_name = $('#gp_name').val();
alert(statusVal,gp_name);
$.ajax({
type: "POST",
url: "save.php",
data: {
statusType: statusVal,
gp_name: gp_name
},
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
save.php
<?php
require_once("connMysql.php");
$gp_name=$_POST['gp_name'];
$st=$_POST['statusType'];
$qry ="UPDATE lotus_gp SET status='".$st."' where gp_name='".$gp_name."'";
$done = mysql_query($qry);
if($done)
{
echo $gp_name;
echo $st;
}
?>
First, check if the data is getting from your front-end sides on your PHP page.
if(isset($_POST['gp_name']) && isset($_POST['statusType'])){
$gpname = $_POST['gp_name']; // echo it to ensure
$satype = $_POST['statusType']; // echo it to ensure
}
If the data is not printed then you might have an issue with inputs.
I real need your help since I'm a beginner in php and Ajax. My problem is that, I can not send data in the database via my appended form in post.php, also when the button of id #reply clicked it sends empty data to database by refreshing the page. When the reply link is pressed I only get the Result of reply link to be shown without other information (name and comment). I need your help to make my appanded form to be able to add/send data to the database without refreshing the page, I also need to disable the form from index.php to make replies when the reply button / link is pressed. Thank you.
post.php
<?php include("config.php"); //inserting
$action=$_POST["action"];
if($action=="addcomment"){
$author = $_POST['name'];
$comment_body = $_POST['comment_body'];
$parent_id = $_POST['parent_id'];
$q = "INSERT INTO nested (author, comment, parent_id) VALUES ('$author', '$comment_body', $parent_id)";
$r = mysqli_query($conn, $q);
if(mysqli_affected_rows($conn)==1) { header("location:index.php");}
else { }
}
// showing data
error_reporting( ~E_NOTICE );
function getComments($conn, $row) {
$action=$_POST["action"];
if($action=="showcomment"){ $id = $row['id'];
echo "<li class='comment'><div class='aut'>".$row['author']."</div><div class='comment-body'>".$row['comment']."</div>";
echo "<a href='#comment_fo' class='reply' id='".$row['id']."'>Reply</a>";
$result = mysqli_query($conn, "SELECT * FROM `nested` WHERE parent_id = '$id' ORDER BY `id` DESC");
}
if(mysqli_num_rows($result)>0) { echo "<ul>";
while($row = mysqli_fetch_assoc($result)) { getComments($conn,$row); }
echo "</ul>"; } echo "</li>";
}
if($action=="showcomment"){
$q = "SELECT * FROM nested WHERE parent_id = '".$row['id']."' ORDER BY `id` DESC";
$r = mysqli_query($conn, $q);
while($row = mysqli_fetch_assoc($r)){ getComments($conn,$row); }
}
?>
<!DOCTYPE HTML><head><script type='text/javascript'>
$(document).ready(function(){
$("a.reply").one("click", function() {
var id = $(this).attr("id");
var parent = $(this).parent();
$("#parent_id").attr("value", id);
parent.append(" <br /><div id='form'><form><input type='text' name='name' id='name'><textarea name='comment_body' id='comment_body'></textarea><input type='hidden' name='parent_id' id='parent_id' value='0'><button id='reply'>Reply</button></form></div>");
$("#reply").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){ showComment(); }
});
});
});
});
</script></head></html>
//index.php
<html><head><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function showComment(){
$.ajax({
type:"post",
url:"post.php",
data:"action=showcomment",
success:function(data){ $("#comment").html(data); }
});
}
showComment();
$(document).ready(function(){
$("#button").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
</script></head><body>
<form id="form_comment">
<input type="text" name="name" id='name'/>
<textarea name="comment_body" id='comment_body'></textarea>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
<input type="button" id="button" value="Comment"/>
</form>
<div id="comment"></div> </body></html>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault(); //add this line to prevent reload
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
Here is a simple incomplete ajax example.
FromPage.php
Here is the ajax that I'd use. The variables can be set however you like.
<script type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
var name = "John Smith";
$.ajax({
url: 'toDB.php',
type: 'post',
dataType: 'html',
data: {
carArray: cars,
firstName: name
},
success: function(data) {
console.log(data); //Testing
}
});
</script>
toDB.ph
This is the second page - the one that writes the values to the database etc.
<?php
$cars = $_POST['carArray'];
$FirstName=$_POST['firstName'];
//Used to test - it will print out the array
print("<pre>");
print_r($cars);
print("</pre>");
//Do something with $cars array and $FirstName variable
?>
I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.