Hi I wanting to submit the filter form when any of the checkboxes' are checked. Have looked at multiple forums and cant seen to get the answer. Also with the current code when i uncheck the input box it passes empty value. All in the same file. Go easy i am new :) . I want to see the parameter in the url , so i can pass value to this page from other pages and select the appropriate checkbox on load
**TEST.PHP**
<body>
<!-- Page Content -->
<div class="container">
<div class="row">
<br />
<h2 align="center">Advance Ajax Product Filters in PHP</h2>
<br />
<form action="" id="filter">
<div class="col-md-3">
<div class="list-group">
<h3>LEVEL</h3>
<div style="height: 180px; overflow-y: auto; overflow-x: hidden;">
<div class="list-group-item checkbox">
<?php
$sql = "SELECT DISTINCT(carcolor) FROM car";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
foreach($result as $row)
{
?>
<input type="checkbox" onclick="filtercolor()" class="color" name="color" value="<?= $row['carcolor']; ?>"/>
<label><?php echo $row['carcolor']; ?></label>
<?php
}
}
else {
echo "No data Found";
}
?>
</div>
</div>
</div>
</div>
</form>
<div class="col-md-9">
</div>
</div>
</div>
<script>
function filtercolor() {
var color = $('input:checkbox[name="color"]:checked').map(function(){return this.value;}).get().join('|');
$.ajax({
url: 'test.php',
data:"color=" + color,
type: "GET",
success: function(html) {
alert('form submited');
},
});
}
</script>
</body>
</html>
Try this
function filtercolor(checkBox) {
let checkBox_val = checkBox.value;
alert(checkBox_val);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span> 0 </span>
<input type="checkbox" onclick="filtercolor(this)" class="color" value="0"/> <br>
<span> 1 </span>
<input type="checkbox" onclick="filtercolor(this)" class="color" value="1"/> <br>
<span> 2 </span>
<input type="checkbox" onclick="filtercolor(this)" class="color" value="2"/> <br>
<span> 3 </span>
<input type="checkbox" onclick="filtercolor(this)" class="color" value="3"/> <br>
<span> 4 </span>
<input type="checkbox" onclick="filtercolor(this)" class="color" value="4"/>
Related
What am I trying to achieve:
After form is being filled-out and submit button being clicked, I want to be able to submit form and do an AJAX call - payment.php file (I did integration of PayPal, I am sending following values via mail firstname, surname, email, phone, number, date of birth, CV, photo, etc...) and I am also trying to store it into the database.
Where am I failing at?
This is multiple-step form, the problem is occuring when I get to the last step of filling-out form and by clicking "Submit" button nothing happens - my AJAX call is not working...
My jQuery code:
$(document).ready(function(){
var current_fs, next_fs, previous_fs; //fieldsets
var opacity;
var current = 1;
var steps = $("fieldset").length;
setProgressBar(current);
$(".next").click(function(){
current_fs = $(this).parent();
next_fs = $(this).parent().next();
//Add Class Active
$("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");
//show the next fieldset
next_fs.show();
//hide the current fieldset with style
current_fs.animate({opacity: 0}, {
step: function(now) {
// for making fielset appear animation
opacity = 1 - now;
current_fs.css({
'display': 'none',
'position': 'relative'
});
next_fs.css({'opacity': opacity});
},
duration: 500
});
setProgressBar(++current);
});
$(".previous").click(function(){
current_fs = $(this).parent();
previous_fs = $(this).parent().prev();
//Remove class active
$("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");
//show the previous fieldset
previous_fs.show();
//hide the current fieldset with style
current_fs.animate({opacity: 0}, {
step: function(now) {
// for making fielset appear animation
opacity = 1 - now;
current_fs.css({
'display': 'none',
'position': 'relative'
});
previous_fs.css({'opacity': opacity});
},
duration: 500
});
setProgressBar(--current);
});
function setProgressBar(curStep){
var percent = parseFloat(100 / steps) * curStep;
percent = percent.toFixed();
$(".progress-bar")
.css("width",percent+"%")
}
$(".submit").click(function(){
var request;
//moj kod
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $("#msform");
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "payment.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Request uspjeĆĄno poslat!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.log(JSON.stringify(errorThrown));
console.error(
"Desio se sljedeci error: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
//moj kod ->end
return false;
})
});
This is jQuery code (obviously) - and here I am handling the form and its data (at least it's what I intended to do with it)
This is form inside of HTML:
<form class="paypal" action="payment.php" method="post" name="Form" id="msform">
<?php
$paket = $_GET['paket'];
if($paket == "standard")
{
?>
<input type="hidden" name="standard" value="standard">
<input type="hidden" name="item_number" value="1">
<?php
}
else if($paket == "bewerbungscheck")
{
?> <input type="hidden" name="bewerbungscheck" value="bewerbungscheck">
<input type="hidden" name="item_number" value="2">
<?php
}
else if($paket == "premium")
{
?> <input type="hidden" name="premium" value="premium">
<input type="hidden" name="item_number" value="3">
<?php
}
else if($paket == "lowbudget")
{
?>
<input type="hidden" name="lowbudget" value="lowbudget">
<input type="hidden" name="item_number" value="4">
<?php
}
else{
echo "There's no package with this name, please go back and choose again, wisely!";
?>
<button class="btn">
Go Back
</button>
<?php
exit();
}
?>
<!-- progressbar -->
<ul id="progressbar">
<li class="active" id="account"><strong>Personal Info</strong></li>
<li id="personal"><strong>Appointment</strong></li>
<li id="payment"><strong>Documents</strong></li>
<li id="confirm"><strong>Finish</strong></li>
</ul>
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar"
aria-valuemin="0" aria-valuemax="100"></div>
</div>
<br>
<!-- fieldsets -->
<fieldset>
<div class="form-card">
<div class="row">
<div class="col-7">
<h2 class="fs-title">Personal Information:</h2>
</div>
<div class="col-5">
<h2 class="steps">Step 1 - 4</h2>
</div>
</div>
<!-- FOR PAYPAL -->
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="no_note" value="1" />
<input type="hidden" name="lc" value="DE" />
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest" />
<input type="hidden" id="first_name" name="first_name" value="Customer's First Name" />
<input type="hidden" id="last_name" name="last_name" value="Customer's Last Name" />
<input type="hidden" id="payer_email" name="payer_email" value="customer#example.com" />
<!-- END OF SECTION FOR PAYPAL -->
<label class="fieldlabels">Email: *</label>
<input id="email" type="email" name="email" placeholder="example#meinegutebewerbung.de" />
<label class="fieldlabels">Name: *</label>
<input id="fn" type="text" name="uname" placeholder="Name" />
<label class="fieldlabels">Surname: *</label>
<input id="sur" type="text" name="usur" placeholder="Surname" />
<label class="fieldlabels">Expertised in: *</label>
<input type="text" name="expert" placeholder="ex.:Bachelor in Computer science" />
<label class="fieldlabels">Phone number: *</label>
<input type="tel" name="phone" placeholder="+000000000000000" />
<label class="fieldlabels">Birth Date: *</label>
<input type="date" name="date" placeholder="Date" />
</div>
<input type="button" name="next" onclick="populate()" class="next action-button"
value="Next" />
</fieldset>
<fieldset>
<div class="form-card">
<div class="row">
<div class="col-7">
<h2 class="fs-title">Appointment details:</h2>
</div>
<div class="col-5">
<h2 class="steps">Step 2 - 4</h2>
</div>
</div>
<label class="fieldlabels">Select appointment date: *</label>
<input id="date_picker" type="date" name="date-res" />
<label class="fieldlabels">Which time span is the most fitting for you: *</label> <br>
<select name="suitabletime " id="suitable">
<option value="09-14">09:00 - 14:00</option>
<option value="14-20">14:00 - 20:00</option>
</select>
</div>
<input type="button" name="next" class="next action-button" value="Next" />
<input type="button" name="previous" class="previous action-button-previous"
value="Previous" />
</fieldset>
<fieldset>
<div class="form-card">
<div class="row">
<div class="col-7">
<h2 class="fs-title">Upload documents:</h2>
</div>
<div class="col-5">
<h2 class="steps">Step 3 - 4</h2>
</div>
</div>
<label class="fieldlabels">Upload Your Photo:</label>
<input type="file" name="pic" accept="image/*">
<label class="fieldlabels">Upload CV (must be PDF):</label>
<input type="file" name="pic" accept=".pdf">
</div>
<input type="button" name="next" class="next action-button" value="Submit" />
<input type="button" name="previous" class="previous action-button-previous"
value="Previous" />
</fieldset>
<fieldset>
<div class="form-card">
<div class="row">
<div class="col-7">
<h2 class="fs-title">Finish:</h2>
</div>
<div class="col-5">
<h2 class="steps">Step 4 - 4</h2>
</div>
</div>
<br><br>
<h2 class="purple-text text-center"><strong>SUCCESS !</strong></h2>
<br>
<div class="row justify-content-center">
<div class="col-3">
<img src="https://i.imgur.com/GwStPmg.png" class="fit-image">
</div>
</div>
<br><br>
<div class="row justify-content-center">
<div class="col-7 text-center">
<h5 class="purple-text text-center">You Have Successfully Signed Up</h5>
</div>
</div>
</div>
</fieldset>
</form>
How did I came to conclusion that this is not working?
I have actually inserted console.log() so I can get some output after the code is executed, but I am not getting anything. The second thing is that I also setted up PHP to do echo and again I am not getting anything.
As #kikon already stated inside of the comments, the problem was that I did not put the class="submit" as a attribute to the <button>, therefore element with the class of submit didn't exist, so the jQuery couldn't trigger the code inside of the function for AJAX.
I've created a step by step test (fiddle example below) that doesn't quite tally up the total correctly. It works fine if all questions have one answer but when there's multiple answers for a single question it gives a strange tally.
(All answers to the questions are the first checkbox except for "Question 2", the multiple choice question, which is the first 2 checkboxes)
For the multiple choice question - the progress squares at the bottom change green when only one of the two answers is correct (when you click next), it should only be green when both are checked correctly, if not correct then it should be red.
The second issue is that if you answer all questions correctly then the final score is 7... when it should be 5 (multiple choice questions should add 1 point per answer). (If you inspect the fiddle, you can see the total being updated when the next button is clicked in the hidden field at the bottom)
Where am I going wrong?
http://jsfiddle.net/rob_teamworks/vebcsjw0/
jQuery(function($) {
$(document).ready(function() {
// hide all form-rows, but not the first one
$('.form-row').not(':first').hide();
// hide on last step
$('button.next').last().hide();
var score = 0;
$('button.next, input.check').click(function(e) {
// prevent the next buttons from submitting the form
e.preventDefault();
var item = $(this).parents('div.form-row').find('.correct:first').data('progress');
if ($(this).parents('div.form-row').find('.correct:first').is(":checked") && $(this).parents('div.form-row').find('.correct:first').hasClass('correct-answer')) {
$('.quiz-progress-circle[data-progress="' + item + '"]').removeClass("progress-incorrect");
$('.quiz-progress-circle[data-progress="' + item + '"]').addClass("progress-correct");
score += Number(score+1);
} else {
$('.quiz-progress-circle[data-progress="' + item + '"]').removeClass("progress-correct");
$('.quiz-progress-circle[data-progress="' + item + '"]').addClass("progress-incorrect");
}
// hide this form-row, and show the next one
$(this).parents('div.form-row').hide().next('div.form-row').show();
$('.finalscore').val(score);
});
// add the submit button to the last form-row
$('<input>').addClass('check').prop('type', 'submit').appendTo($('.form-row:last'));
});
});
jQuery(function($) {
$(document).ready(function () {
$("input[type=checkbox].correct").click(function (e) {
if ($(e.currentTarget).closest("div.question").length > 0) {
toggleInputs($(e.currentTarget).closest("div.question")[0]);
}
});
});
function toggleInputs(questionElement) {
if ($(questionElement).data('max-answers') == undefined) {
return true;
} else {
maxAnswers = parseInt($(questionElement).data('max-answers'), 10);
if ($(questionElement).find(".correct:checked").length >= maxAnswers) {
$(questionElement).find(".correct:not(:checked)").attr("disabled", true);
} else {
$(questionElement).find("input[type=checkbox].correct").attr("disabled", false);
}
}
}
});
.quiz-progress-circle {
height:5px;
width:5px;
background-color:grey;
display:inline-block;
margin-right:10px;
}
.progress-correct {
background-color:green!important;
}
.progress-incorrect {
background-color:red!important;
}
.progress-current {
background-color:blue!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="row test">
<div class="columns">
<div class="entry">
<form class="form" method="POST" action="http://example.com/test-insert.php">
<input type="hidden" value="teamworks" name="test-user">
<input type="hidden" value="Introduction" name="test-name">
<div class="form-row">
<h1>Quiz | Introduction</h1>
<div class="clear"></div>
<div id="module-area">
<div id="modules-top"></div>
<div id="modules-repeat">
<h2 class="training">1. Question 1</h2>
<div class="question" data-max-answers="1">
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="correct correct-answer" data-progress="1" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 1">
</div>
<div style="display:table-cell;">
<p>
Answer 1 </p>
</div>
</div>
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="correct " data-progress="1" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 2">
</div>
<div style="display:table-cell;">
<p>
Answer 2 </p>
</div>
</div>
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="correct " data-progress="1" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 3">
</div>
<div style="display:table-cell;">
<p>
Answer 3 </p>
</div>
</div>
</div>
<div class="inner"></div>
<button class="next">Next >></button>
<div class="clear"></div>
</div>
<div id="modules-bottom"></div>
</div>
</div>
<div class="form-row" style="display: none;">
<h1>Quiz | Introduction</h1>
<div class="clear"></div>
<div id="module-area">
<div id="modules-top"></div>
<div id="modules-repeat">
<h2 class="training">2. Question 2</h2>
<div class="question" data-max-answers="2">
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="correct correct-answer" data-progress="2" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 1">
</div>
<div style="display:table-cell;">
<p>
Answer 1 </p>
</div>
</div>
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="correct correct-answer" data-progress="2" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 2">
</div>
<div style="display:table-cell;">
<p>
Answer 2 </p>
</div>
</div>
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="correct " data-progress="2" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 3">
</div>
<div style="display:table-cell;">
<p>
Answer 3 </p>
</div>
</div>
</div>
<div class="inner"></div>
<button class="next">Next >></button>
<div class="clear"></div>
</div>
<div id="modules-bottom"></div>
</div>
</div>
<div class="form-row" style="display: none;">
<h1>Quiz | Introduction</h1>
<div class="clear"></div>
<div id="module-area">
<div id="modules-top"></div>
<div id="modules-repeat">
<h2 class="training">3. Question 4</h2>
<div class="question" data-max-answers="1">
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="correct correct-answer" data-progress="3" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 1">
</div>
<div style="display:table-cell;">
<p>
Answer 1 </p>
</div>
</div>
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="correct " data-progress="3" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 2">
</div>
<div style="display:table-cell;">
<p>
Answer 2 </p>
</div>
</div>
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="correct " data-progress="3" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 3">
</div>
<div style="display:table-cell;">
<p>
Answer 3 </p>
</div>
</div>
</div>
<div class="inner"></div>
<button class="next">Next >></button>
<div class="clear"></div>
</div>
<div id="modules-bottom"></div>
</div>
</div>
<div class="form-row" style="display: none;">
<h1>Quiz | Introduction</h1>
<div class="clear"></div>
<div id="module-area">
<div id="modules-top"></div>
<div id="modules-repeat">
<h2 class="training">4. Question 5</h2>
<div class="question" data-max-answers="1">
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="correct correct-answer" data-progress="4" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 1">
</div>
<div style="display:table-cell;">
<p>
Answer 1 </p>
</div>
</div>
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="correct " data-progress="4" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 2">
</div>
<div style="display:table-cell;">
<p>
Answer 2 </p>
</div>
</div>
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="correct " data-progress="4" style="width: 20px;" type="checkbox" name="answer[]" value="Answer 3">
</div>
<div style="display:table-cell;">
<p>
Answer 3 </p>
</div>
</div>
</div>
<div class="inner"></div>
<button class="next" style="display: none;">Next >></button>
<div class="clear"></div>
</div>
<div id="modules-bottom"></div>
</div>
<input class="check" type="submit"></div>
<div class="quiz-progress">
<div class="quiz-progress-circle" data-progress="1"></div>
<div class="quiz-progress-circle" data-progress="2"></div>
<div class="quiz-progress-circle" data-progress="3"></div>
<div class="quiz-progress-circle" data-progress="4"></div>
</div>
<input type="hidden" value="236" name="test-id">
<input class="finalscore" type="hidden" value="" name="test-score">
<input type="hidden" value="2" name="test-pass">
</form>
<div class="clear"></div>
</div>
</div>
</section>
This is the php file it calls on submit. The variable $score comes from the hidden field with the name test-score that is tallied up by the jquery variable score.
<?php
$score = $_POST["test-score"];
$pass_msg = $_POST["test-pass"];
if ($score >= $pass_msg) {
$pass_txt = "Pass";
} else {
$pass_txt = "Fail";
}
// Opens a connection to a MySQL server
$username="root";
$password="root";
$database="local";
$host="localhost";
$con = mysqli_connect($host, $username, $password);
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db($con, "local");
$user = $_POST["test-user"];
$testid = $_POST["test-id"];
$sql = mysqli_query($con, "INSERT INTO test (`name`, `testname`, `score`, `pass-fail`) VALUES ('".$user."', '".$testid."', '".$score."', '".$pass_txt."')");
if (!$sql)
{
die('Error: ' . mysqli_error());
}
mysqli_close($con);
header('Location: http://example.com/training/introduction/');
?>
Thanks to #viorel for the answer, it's caused an additional problem:
It should only show the second submit button on the last question... it should submit the form but it's not counting the question towards the score.
I've looked a little bit at the code and simplified the following bit:
$('button.next, input.check').click(function (e) {
// prevent the next buttons from submitting the form
e.preventDefault();
var correctAnswers = $(this).siblings().find('.correct-answer').length;
var totalUserCorrectAnswers = $(this).siblings().find('.correct-answer:checked').length;
var totalCheckedAnswers = $(this).siblings().find('input:checked').length;
var item = $(this).parents('div.form-row').find('.correct:first').data('progress');
var resultBubble = $('.quiz-progress-circle[data-progress="' + item + '"]');
if(correctAnswers === totalUserCorrectAnswers && totalUserCorrectAnswers === totalCheckedAnswers) {
resultBubble.removeClass("progress-incorrect");
resultBubble.addClass("progress-correct");
score += 1;
} else {
resultBubble.removeClass("progress-correct");
resultBubble.addClass("progress-incorrect");
}
// hide this form-row, and show the next one
$(this).parents('div.form-row').hide().next('div.form-row').show();
$('.finalscore').val(score);
});
I've added three control variables: the total number of correct answers expected (correctAnswers), the number of correct answers the user selected (totalUserCorrectAnswers) and the total number of checked answers (totalCheckedAnswers). You may not need this last check since you are disabling the checkboxes.
For each steps, there's a simple check to see if the total number of answers selected equals the number expected. If they match, the score is incremented by one and the progress squares get the appropriate color. I couldn't figure out exactly the problem before, but it seems that you were only selecting the first correct checked answer
To answer your second question,
score += Number(score+1);
This will add 2 each time, not 1. Change it to:
score++;
For your first question, your if function when button.next is clicked is true when only one answer is correct. A fix could be to define a variable (green = 1). And then run a jQuery Each for every .correct. In the Each Loop, if it has class correct answer but is not ticked, then change green to 0. Also, if a 'correct' with no 'correct-answer' is ticked then also update variable green to 0.
After the Each Loop, then use the value of the variable 'green' to determine if the progress square should be green or not.
I have to submit a form with some fields, like multiple checkboxes selection and some hidden input fields via ajax and replace html content with response. finally i go with javascript/ajax...but where i was wrong?
<?php include( 'session.php');
$userid=$_SESSION[ 'Userid'];
include( 'connection.php');
?>
<head>
<script>
function myFunction() {
var soi = document.getElementById("sweaterownerid").value;
var osp = document.getElementById("osweaterpic").value;
var osi = document.getElementById("osweaterid").value;
var value = [];
$("input[name*='" + sweater+ "']").each(function () {
// Get all checked checboxes in an array
if (jQuery(this).is(":checked")) {
value.push($(this).val());
}
});
var dataString = 'soi1=' + soi + '&osp1=' + osp + '&osi1=' + osi + '&value1=' + value;
if (soi1 == '' || osp1 == '' || osi1 == '' || value1 == '') {
alert("Please Fill All Fields");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "Usercloset1.php",
data: dataString,
cache: false,
success: function(response) {
$('#mydiv').replaceWith(response);
}
});
}
return false;
}
</script>
</head>
<div id="mydiv">
<div class="padding-top">
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 ">
<div class="shop_item" style="width:100%;">
<form id="myForm">
<?php
$sweaterid=$_GET['d'];
$sownerid=$_GET['e'];
$opic=$_GET['f'];
$query1="select * from `usersweater` where `Sweaterid`='$sweaterid'";
$result1=mysql_query($query1);
$row1=mysql_fetch_assoc($result1);
$sweaternikname=$row1['SNickname'];
?>
<div>
<ul class="sweaters">
<li> <h4><?php echo $sweaternikname; ?></h4> <img src="upload/<?php echo $opic; ?>"> </li>
</ul>
<ul class="sweater1">
<?php
$query="select * from `usersweater` where `Userid`='$userid' && `Swap`='0' ";
$result = mysql_query($query);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)){
$sid = $line[Sweaterid];
$img = $line[Sweaterpic];
$nikname = $line[SNickname];
$size = $line[Size];
?>
<li> <h4><?php echo $nikname; ?><input type="checkbox" name="sweater[]" value="<?php echo $sid; ?>" /></h4> <img src="upload/<?php echo $img; ?>"> </li>
<?php } ?>
</ul>
</div>
<input type="hidden" name="sweaterownerid" value="<?php echo $sownerid; ?>">
<input type="hidden" name="osweaterpic" value="<?php echo $opic; ?>">
<input type="hidden" name="osweaterid" value="<?php echo $sweaterid; ?>">
<input type="submit" name="next" onclick="myFunction()" value="NEXT" class="btn woo_btn btn-primary" style="margin-left: 30px;">
<input type="button" name="cancel" value="CANCEL" class="btn woo_btn btn-primary">
</form>
</div>
</div>
<div class="clearfix"></div>
<hr>
</div>
</div>
I want to pass the selected option to another page, which I do now using form action. But I want it dynamically without reloading page. I am new to ajax/javascript.
Second thing is, how can I handle the response, where submitting this form I want to replace first page content with the reponse that we get using ajax. This means replace all html content with other page's html content. I atteched the file which I want in response after submit.
<div class="padding-top">
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 ">
<div class="shop_item" style="width:100%;">
<div style="text-align:center;">
<h4>Are you sure you want to swap?</h4>
</div>
<form action="Usercloset2.php" method="post">
<?php
include('session.php');
include('connection.php');
foreach ($_POST['value1'] as $sid){
$query1="select * from `usersweater` where `Sweaterid`='$sid'";
$result1=mysql_query($query1);
$row1=mysql_fetch_assoc($result1);
$sweaternikname=$row1['SNickname'];
$sweaterpic=$row1['Sweaterpic'];
?>
<div style=" ">
<ul class="sweaters">
<li> <h4><?php echo $sweaternikname; ?></h4> <img src="upload/<?php echo $sweaterpic; ?>"> </li>
</ul>
</div>
<!-------requester's own sweater details--------------->
<input type="hidden" name="sid[]" value="<?php echo $sid;?>">
<input type="hidden" name="snikname[]" value="<?php echo $sweaternikname;?>">
<input type="hidden" name="spic[]" value="<?php echo $sweaterpic;?>">
<?php } ?>
<!-------requester's show intrest that sweater details--------------->
<?php
$sownerid=$_POST['soi1'];
$opic=$_POST['osp1'];
$sweaterid=$_POST['osi1'];
?>
<input type="hidden" name="sweaterownerid" value="<?php echo $sownerid;?>">
<input type="hidden" name="osweaterpic" value="<?php echo $opic;?>">
<input type="hidden" name="osweaterid" value="<?php echo $sweaterid;?>">
<div style="float:right; margin-right:10px;">
<input type="submit" name="next" value="NEXT" class="btn woo_btn btn-primary">
<input type="button" name="cancel" value="CANCEL" class="btn woo_btn btn-primary">
</div>
</form>
</div>
</div>
<div class="clearfix"></div>
<hr>
</div>
you can use in your Ajax like this:
var form = $('#your_form_id');
var formAction = $('#your_form_id').attr('action');
/* Get input values from form */
values = form.serializeArray();
/* Because serializeArray() ignores unset checkboxes and radio buttons: */
values = values.concat(
$('#your_form_id input[type=checkbox]:not(:checked)').map(
function() {
return {
"name": this.name,
"value": this.value
}
}).get()
);
$.ajax({
'ajax code here'
});
or you can check https://api.jquery.com/serialize/
You can achive it though this.
jQuery(document).ready(function($){
$("#your_button_id").on('click', function(e){
e.preventDefault();
$("#your_form_id") .submit();
})
})
Ajax
$("#your_form_id").on('submit', function(e) {
e.preventDefault();
$.post('URL_HERE', $(this).serialize(), function(response) {
console.log(response)
});
});
I have 2 forms on a page with structures
<div id="tabs-7">
<form action="/admin/languages" id="1" class="mainForm" method="POST">
<fieldset>
<div class="widget">
<input type="hidden" maxlength="40"class="autoF" name="base" id="base" value="<?php echo base_url(); ?>" />
<input type="hidden" maxlength="40"class="autoF" id="lang_id" name="lang_id" value="1" />
<div class="rowElem">
<label>Calender</label>
<div class="rowElem noborder" >
<label>Date:</label>
<div class="formLeft">
<input type="text" name="date" class="datepicker date" value="<?php echo isset($data['1']['date']['text']) ? $data['1']['date']['text'] : ""; ?>" />
</div>
</div>
<label> Note:</label>
<div class="formLeft">
<?php
if (!empty($data['1']['calender_contents'])) {
$text = preg_replace('/\s+/', ' ', $data['1']['calender_contents']['text']);
}
?>
<textarea name="calender_contents" class="auto limit calender_contents" style="min-width: 600px;max-width: 600px;min-height:80px;max-height: 80px;"><?php echo isset($data['1']['calender_contents']['text']) ? $text : ""; ?></textarea>
</div>
<div class="rowElem "><input type="button" value="Add Note" class="blueBtn left addnote"></div>
</div>
<div class="rowElem "><input type="submit" value="Save" class="greenBtn right"></div>
</div>
</fieldset>
</form>
</div>
<div id="tabs-8">
<form action="/admin/languages" id="2" class="mainForm" method="POST">
<fieldset>
<div class="widget">
<input type="hidden" maxlength="40"class="autoF" name="base" id="base" value="<?php echo base_url(); ?>" />
<input type="hidden" maxlength="40"class="autoF" id="lang_id" name="lang_id" value="2" />
<div class="rowElem">
<label>Calender</label>
<div class="rowElem noborder" >
<label>Date:</label>
<div class="formLeft">
<input type="text" name="date" class="datepicker date" value="<?php echo isset($data['2']['date']['text']) ? $data['2']['date']['text'] : ""; ?>" />
</div>
</div>
<label> Note:</label>
<div class="formLeft">
<?php
if (!empty($data['2']['calender_contents'])) {
$text = preg_replace('/\s+/', ' ', $data['1']['calender_contents']['text']);
}
?>
<textarea name="calender_contents" class="auto limit calender_contents" style="min-width: 600px;max-width: 600px;min-height:80px;max-height: 80px;"><?php echo isset($data['2']['calender_contents']['text']) ? $text : ""; ?></textarea>
</div>
<div class="rowElem "><input type="button" value="Add Note" class="blueBtn left addnote"></div>
</div>
<div class="rowElem "><input type="submit" value="Save" class="greenBtn right"></div>
</div>
</fieldset>
</form>
</div>
and javascript :
$(".datepicker").datepicker({
defaultDate: +7,
autoSize: true,
appendText: '(yyyy-mm-dd)',
dateFormat: 'yy-mm-dd',
onClose: function(dateText, inst) {
var form = $(this).closest("form");
var formID = $(form).attr("id");
console.log(formID);
if(formID == "1"){
formID = 1;
}
else{
formID = 2;
}
var lang_id = formID;
var date = $(".date").val();
console.log(lang_id);
console.log(date);
$.ajax({
type: 'POST',
url: "/admin/getnote",
dataType: "json",
data: {"date": date, "lang_id": lang_id},
success: function(data) {
console.log(data.arr[0]);
if(data.arr[0] != undefined){
$('.calender_contents').val(data.arr[0].note);
$('.date').val(data.arr[0].date);
}
else {
$('.calender_contents').val("");
}
}
});
}
});
I am able to get the value from the database in the first tab that is tab 7 fine and value
but when use the date picker in the second form to its value also gets displayed in the first table so was looking for some advise as how i can combine $(this).closest("form"); with these fields
$('.calender_contents').val(data.arr[0].note);
$('.date').val(data.arr[0].date);
so that i could get value in the specific form field . Thank you.
You select #calendar_contents. If you use the same "id" for 2 elements, first you're doing it wrong (an id must be unique), then jQuery will only return you the first element that has the requested id.
Try using a class and "locate" the tab you're using.
You can't have html elements on the same page that have the same id, even if they are in different forms. The id attribute must be unique on the whole page
I'm using PHP, Smarty and jQuery for my website. There is a functionality of showing and hiding an element on a form. The HTML as well as code from jQuery function is as below:
HTML Code:
<div class="c-mega-accord">
<ol class="fnAccordion">
<li>
<a class="fnTrigger" href="#">Practice Sheet Basic Details <span></span></a>
<div class="fnAccContent">
<div class="c-grad-box">
<div class="form-wrapper">
{if $error_msg}<div class="error-info">{$error_msg.error_msgs}</div>{/if}
<form name="manage_practice_sheet" id="manage_practice_sheet" action="practice_sheet.php" method="post">
<input type="hidden" name="op" id="op" value="{$op}" />
<input type="hidden" name="sheet_type" id="sheet_type" value="{$sheet_type}" />
<input type="hidden" name="form_submitted" id="form_submitted" value="yes" />
<input type="hidden" name="practice_sheet_id" id="practice_sheet_id" value="{$practice_sheet_id}" />
<input type="hidden" name="hidden_practice_sheet_category_id" id="hidden_practice_sheet_category_id" value="{$practice_sheet_category_id}" />
<input type="hidden" name="practice_sheet_id" id="practice_sheet_id" value="{$practice_sheet_id}" />
<p class="form-info fl-right">* Mandatory fields</p>
<ul>
<li>
<label>{'Category'|signal_on_error:$error_msg:'practice_sheet_category_id'}<span class="reqd">*</span></label>
<div class="form-element">
<select name="practice_sheet_category_id" id="practice_sheet_category_id" <!--onChange="get_subcategory_by_category('{$control_url}modules/category/manage_category.php', this.value, 'get_subcategory_by_category', '#practice_sheet_sub_category_id');"--> >
<option value="">Select</option>
{if $all_parent_categories}
{foreach from=$all_parent_categories item="parent_category"}
<option value="{$parent_category.category_id}" {if $data.practice_sheet_category_id==$parent_category.category_id || $practice_sheet_category_id==$parent_category.category_id} selected="selected"{/if}>{$parent_category.category_name}</option>
{/foreach}
{/if}
</select>
</div>
</li>
<li>
<label>{'Practice Sheet Name'|signal_on_error:$error_msg:'practice_sheet_name'}<span class="reqd">*</span></label>
<div class="form-element">
<input class="" type="text" name="practice_sheet_name" id="practice_sheet_name" value="{$data.practice_sheet_name}" maxlength="50">
</div>
</li>
<li>
<label>Display Date</label>
<div class="form-element">
<input type="text" class="cal fl-left" id="frmDate" name="frmDate" value="{if $data.practice_sheet_display_date !='0' && $data.practice_sheet_display_date !=''}{$data.practice_sheet_display_date}{/if}">
</div>
</li>
<li>
<label>Practice Sheet For</label>
<div class="form-element">
<input class="" type="text" name="practice_sheet_for" id="practice_sheet_for" value="{$data.practice_sheet_for}" maxlength="50">
</div>
</li>
<li>
<label></label>
<div class="form-element">
<!--<input type="submit" value="{$submit_value}" class="c-btn" id="saveAddMore" name="submit">
<input type="button" value="{$cancel_value}" class="c-gray-btn" id="done" name="done" onclick="javascript:window.location.href='{$control_url}modules/practice_sheet/practice_sheet.php?op={$query_string}'"><br/>-->
<span class="c-btn c-continus-btn"><input type="button" name="continus" id="continus" value="Continue" id="" name=""></span>
<span class="c-gray-btn c-cancel-btn"><input type="button" value="Cancel" id="" name=""></span>
</div>
</li>
</ul>
</form>
</div>
</div>
</div>
</li>
<li>
<a class="fnTrigger" href="#">Select Category <span></span></a>
<div class="fnAccContent">
<div class="c-grad-box">
</div>
</div>
</li>
</ol>
</div>
jQUery Code:
function accordion(){
var li = $(".fnAccordion > li");
li.eq(0).addClass("active");
li.children('.fnAccContent').not(':first').hide();
$(".fnAccordion .fnTrigger").click(function(e){
e.preventDefault();
var numLi = $(this).parent('li').siblings();
if(numLi.length > 0){
$(this).parent('li').siblings().removeClass("active");
var curState = $(this).parent().find(".fnAccContent").css("display");
if(curState == "none"){
$(".fnAccContent").slideUp();
$(this).parent().addClass("active");
$(this).parent().find(".fnAccContent").slideDown();
}
}else{
$(this).parent('li').toggleClass("active");
$(this).parent().find(".fnAccContent").slideToggle();
}
})
}
$(document).ready(function(){
accordion();
})
Now the functionality of hide/show is working fine when I click on following two elements:
<a class="fnTrigger" href="#">Practice Sheet Basic Details <span></span></a>
<a class="fnTrigger" href="#">Select Category <span></span></a>
Actually I want to make this functionality work on Continue button(following is the HTML code snippet for it):
<input type="button" name="continus" id="continus" value="Continue" id="" name="">
I tried to make it work on Continue button by applying the class fnTrigger but it didn't work. Can you help me in this regard? Thanks in advance.
If you want the function to be triggered when both the classes are present,
you use
$(".fnAccordion .fnTrigger").click(function(){
//Your code here
});
If you want the function to get triggered when element of either class is clicked, use a "," to separate the classes.
$(".fnAccordion, .fnTrigger").click(function(){
//Your code here
});
Your check only checks for the fnTrigger class INSIDE an element with the class fnAccordion
$(".fnAccordion .fnTrigger").click(function(e){});
Is your button inside the element with the class fnAccordion?