I have ajax based form submission and on success I want to show a success message. The elements are being generated dynamically by mysql results. Currently the success message for one shows up for all the elements in loop. How can I obtain this for that particular element. Some insight will be very helpful.
<?php if($row['section'] == 1) {?>
<ul class="list-group">
<li class="list-group-item active">
<div class="radio noMargin" id="<?php echo $sectionOne ; ?>info"><?php echo $no ; ?> <span class="glyphicon glyphicon-arrow-right"></span></div><?php echo "<font color='pink'>Ques ID :[".$row['id']."]</font>";?><div class="question"><?php echo $row['question'] ; ?></div>
<div style="float:right; margin-top:-20px;">
Marks:<?php echo $row['marks'] ; ?></div></li>
<?php
echo '<input type="hidden" name="question[]" id="questionId" value="'.$row['id'].'">';
echo '<input type="hidden" name="attempt" value="'.$attemptCount.'">';
echo '<input type="hidden" name="unit_id" value="'.$unit_id.'">';
echo '<input type="hidden" name="chapter_id" value="'.$chapter_id.'">';
$questionId = $row['id'] ;
$sqO =$db->query("SELECT id, options from tbl_options_mock_question WHERE question_id = ".$questionId."");
while($rowO=mysql_fetch_array($sqO))
{
?>
<li class="list-group-item wrp_radio">
<div class="radio noMargin">
<label>
<input disabled type="radio" class="checkedInfo" alt="<?php echo $no ; ?>" name="optionAns<?php echo $i ; ?>" value="<?php echo $rowO['id'] ; ?>">
<?php echo $rowO['options'] ; ?></label>
</div>
</li>
<?php } ?>
<div class="successMessage" style="display:none;"><font color="green"><b>Your notes for question is submitted successfully.</b></font></div>
<br>
<a class="click_notes" data-question-id="<?=$questionId?>"> <font size='2' color='blue'> Add Notes</font></a>
<br>
<div class="demo"></div>
</ul>
<?php $i++;$no++; ?>
<?php } ?>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.click_notes').on('click', function() {
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html('<div class="comment_form"><span><b>X</b></span><form id="contactForm1" action="submit.php" method="post"><textarea required cols="50" class="span10" name="notes" rows="6"></textarea><br><input class="btn btn-primary" id="submitnotes" name="submit_notes" type="submit" value="Add Notes"><input type="hidden" name="submitValue" value="' + tid + '" /></form><br></div>');
});
$(document).on('submit', '#contactForm1', function(e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function(data) {
$('.comment_form').hide();
$(".successMessage").show();
},
error: function(xhr) {
console.log('An error occurred.');
console.log(xhr);
},
});
}).on('click', 'span', function() {
$(this).parent().hide()
});
});
</script>
Here is a Fiddle I used for testing: https://jsfiddle.net/Twisty/gokfth37/41/
HTML
<ul class="list-group">
<li class="list-group-item active">
<div class="radio noMargin" id="section-1-info">
1
<span class="glyphicon glyphicon-arrow-right"></span>
</div>
<font color='pink'>Ques ID : 1</font>
<div class="question">
Question 1
</div>
<div style="float:right; margin-top:-20px;">Marks: Marks 1
</div>
</li>
<li>
<input type="hidden" name="question[]" id="questionId" value="1">
<input type="hidden" name="attempt" value="0">
<input type="hidden" name="unit_id" value="1">
<input type="hidden" name="chapter_id" value="1">
</li>
<li class="list-group-item wrp_radio">
<div class="radio noMargin">
<input disabled type="radio" class="checkedInfo" alt="1" name="optionAns1" value="1">
<label>Answer 1</label>
<input disabled type="radio" class="checkedInfo" alt="2" name="optionAns2" value="2">
<label>Answer 2</label>
<input disabled type="radio" class="checkedInfo" alt="3" name="optionAns3" value="3">
<label>Answer 3</label>
</div>
</li>
<li>
<div class="successMessage" style="display:none;">
<font color="green">
<b>Your notes for question is submitted successfully.</b>
</font>
</div>
<br>
<a class="click_notes" data-question-id="1">
<font size='2' color='blue'>
Add Notes
</font>
</a>
<br>
<div class="demo">
</div>
</li>
</ul>
I made some leaps and created HTML based on the PHP code you had. You can see here that I had to correct a lot of HTML Syntax. You should not have <ul> that have <input> or <div> elements as children. It should only be <li> elements that can then contain other elements.
So when the "Add Notes" button is clicked, a form is dynamically created that must have a unique ID and all the elements within must have unique IDs. This form will have a Close button, a Text Area, a hidden element and a submit button. When the form is submitted, the data from the form should be submitted via POST to a specific URL and upon successful submission, display the success note.
JavaScript
$(function() {
$('.click_notes').on('click', function() {
$(this).parent().find(".successMessage").hide();
$(this).hide();
var that = $(this);
var tid = $(this).data('question-id');
var form = $("<form>", {
id: "contact-form-" + tid,
action: "submit.php",
method: "POST",
class: "comment-form"
}).submit(function(e) {
e.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(data) {
console.log("Success");
$('.comment-form').hide();
that.parent().find(".successMessage").show();
that.show();
},
error: function(xhr) {
console.log('An error occurred.');
console.log(xhr);
}
});
});
$("<span>", {
class: "close btn"
}).html("X").click(function() {
that.show();
$(this).parent().hide();
}).appendTo(form);
$("<textarea>", {
required: true,
cols: "50",
class: "span10",
name: "notes"
}).appendTo(form);
$("<input>", {
type: "hidden",
name: "submitValue",
value: tid
}).appendTo(form);
$("<button>", {
class: "btn btn-primary",
id: "submit-notes-" + tid,
type: "submit"
}).html("Add Notes").appendTo(form);
$(this).closest('li').find('.demo').html(form);
});
});
One of the benefits of creating content with jQuery is that you can bind callbacks when you create the object. So instead of mucking around with .on() you can also just call .click() or .submit() right when you're creating the objects. Either works, but sometimes one is easier to manage than the other.
In the example above, we create the form, bind a submit callback to it, add other elements, and the replace #demo with this newly created content. I also added some extra bits to hide a few things, if they are being shown.
When you see var that = $(this); it's sort of a little trick since we do not want to confuse this in some of the other callbacks, yet we may need to reference the original this, and we can, using that.
Hope this helps.
I suggested moving the message outside the loop so you only have ONE message. You could even show it in a dialog
Also you have more than one jQuery loaded. Just load latest or 3.x, not both
change id="contactForm" to class="contactForm"
The HTML is invalid. Move the </ul> to before the demo div
It would have been easier if you wrapped each question and demo div in a wrapper, but try this:
$(document).on('submit', '.contactForm', function(e) {
e.preventDefault();
var $currentForm = $(this);
...
success: function(data) {
$currentForm.hide();
$currentForm.prevAll(".successMessage:first").show();
},
Related
I have working code for posting data to DB using PHP and Jquery without refreshing the page.
But however, I could only use 1 form with the given code, if I'm to add another form with different variables both the forms getting submitted.
My code goes as:
index:
Query starts
$countlikes = 1;
$countdislikes = 1;
<form data-id='<?= $countlikes?>' action="likeinsert" method="post" id="myform<?= $countlikes?>">
<input type="hidden" id="fid<?= $countlikes?>" name="fid" value="<?php echo $f_id; ?>" />
<input type="hidden" id="uid<?= $countlikes?>" name="uid" value="<?php echo $u_id; ?>" />
<button style="border:none; background:transparent;" data-toggle="tooltip" data-placement="right" title="Like" class="up"><i class="fa fa-thumbs-o-up"></i><?= $f_likes; ?></button>
</form>
<form data-id='<?= $countdislikes?>' action="dislikeinsert" method="post" id="myform<?= $countdislikes?>">
<input type="hidden" id="fid<?= $countdislikes?>" name="fid" value="<?php echo $f_id; ?>" />
<input type="hidden" id="uid<?= $countdislikes?>" name="uid" value="<?php echo $u_id; ?>" />
<button style="border:none; background:transparent;" data-placement="right" data-html="true" title="DisLike" class="down"><i class="fa fa-thumbs-o-down"></i><?= $f_dislikes; ?></button>
</form>
$countlikes ++;
$countdislikes ++;
Query Ends
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
$(document).on('submit','form',function(e){
e.preventDefault();
let id = $(this).data('id');
$.post(
'likeinsert.php',
{
fid: $("#fid"+id).val(),
uid: $("#uid"+id).val()
},
function(result){
if(result == "success"){
$("#result").val("Values Inserted");
} else {
$("#result").val("Error");
}
}
);
});
</script>
<script>
$(document).on('submit','form',function(e){
e.preventDefault();
let id = $(this).data('id');
$.post(
'dislikeinsert.php',
{
fiid: $("#fid"+id).val(),
uiid: $("#uid"+id).val()
},
function(result){
if(result == "success"){
$("#result").val("Values Inserted");
} else {
$("#result").val("Error");
}
}
);
});
</script>
When I to click on any form button, both forms are getting submitted.
It is happening, because you are adding two submit event listeners on both forms, so when you submit one form, both jquery scripts are getting executed.
To prevent this, add form's unique ids to your event listeners (in your case they are myform1 and myform1, but you should make them unique), somewhat like this:
$(document).on('submit','form#dislikesForm',function(e){
request to dislikeinsert.php ...
$(document).on('submit','form#likesForm',function(e){
request to likeinsert.php...
My jQuery code is not sending a value from the textarea name="post_description"
<form id="post" method="post">
<div class="input-group">
<textarea name="post_description" class="form-control" placeholder="<?php echo $lang['description']; ?>" rows="4" ng-model="description"></textarea>
</div>
<div id="share_result"></div>
<a id="share" class="btn-custom">
<i class="fa fa-th-large"></i> <?php echo $lang['share']; ?>
</a>
</form>
$(document).ready(function() {
$("#share").click(function(e) {
e.preventDefault();
var postimg = $("#post").serialize();
$.post("posts/post_image.php", postimg).done(function(data) {
$("#share_result").html(data);
}).fail(function() {
//alert("Error submitting forms!");
})
})
})
On the backend:
$post_description = $_POST['post_description'];
It's returning as undefined index but the names do match
May be because you prevent event onclick you have to set event prevent on form submit like this :
<form id="post" method="post">
<div class="input-group">
<textarea name="post_description" class="form-control" placeholder="<?php echo $lang['description']; ?>" rows="4" ng-model="description"></textarea>
</div>
<div id="share_result"></div>
<a id="share" class="btn-custom">
<i class="fa fa-th-large"></i> <?php echo $lang['share']; ?>
</a>
<button type="submit" id="postform">Submit form</button>
</form>
When you click on submit button your form will submit and then
$("#post").submit(function (e) {
e.preventDefault();
// here is your code
});
Or if you don't want to add this button you have to change from
var postimg = $("#post").serialize();
to
var postimg = {post_description:$("textarea[name='post_description']").val()};
It was the Angular js conflict so I had to write my own jquery function to replace the angular and keep the same angular beraviour on the page, here is my jquery solution for angular replacement:
<script type="text/javascript">
$(document).ready(function(){
$("#post_description").keyup(function(){
// Getting the current value of textarea
var currentText = $(this).val();
// Setting the Div content
$("#text_output").text(currentText);
//$("#text_output").value(currentText);
$("#text_output").attr("value", currentText);
});
});
</script>
I have a custom dropdown. Want to change the value of the button as selected option of dropdown
list.
This is my view code. I tried with jquery but unsuccessfull.
Please some one help me with jquery
<div class="col-md-5 col-sm-6">
<div class="form-group droplist">
<label for="project_category">project Categary</label><br/>
<input type="button" class="form-control" id="relig" value="<?php if(isset($projectDetails->project_category) && !empty($projectDetails->project_category)){
echo #$projectDetails->project_category;
}else{
echo "select Category";
}?>">
<div id="religions" class="dropdownmenu" style="display:none;padding-left:17px">
<?php foreach($categories as $cat){ ?>
<div id="<?php echo $cat['code'] ?>" class="maincategory">
<label><input type="radio" class="category" name="project_category" id="category" value="<?php echo $cat['code'] ?>"> <?php echo $cat['Project_classification_id']." - ".$cat['Description'] ?></label><br/>
</div>
<?php } ?>
</div>
</div>
</div>
I have above 140 dropdown values for that i used foreach, notonly 3 values
This is my jquery. I done all thing but unable to show the checked radio value as button value(title)
$('#relig').click(function(){
$('#religions').slideToggle("fast");
});
traversed_ids = [];
$(document).on('change','.project_category',function() {
maincat = $(".project_category:checked").val();
if ($.inArray(maincat, traversed_ids) < 0) { //check element exist in array or not
traversed_ids.push(maincat); //add element to array
changeCategoryList(maincat); //call ajax
}
});
function changeCategoryList(maincategory){
$.ajax({
url: '<?php echo site_url("abcd/xyz"); ?>',
type: 'POST',
data: { maincategory:maincategory },
dataType: 'json',
success: function(data) {
$.each(data, function(key, value) {
var MoreTag='';
MoreTag += '<div id="'+value.code+'" Style="padding-left:20px" class="subcategory">';
MoreTag += '<label ><input type="radio" class="project_category" name="project_category" id="project_category" value="'+value.code+'"> '+value.Project_classification_id+' - '+value.Description+'</label><br/>';
MoreTag += '</div>';
$("#"+maincategory).append(MoreTag);
});
}
});
}
$(".maincategory").click(function (e) {
e.stopPropagation(); //to stop event bubbling
if ($(this).children('.subcategory').is(':checked')) { //check if hidden or not
$(this).children('.subcategory').hide(); //if yes hide
} else {
$('.maincategory').children('.subcategory').hide();
$(this).children('.subcategory').show(); // else show
}
});
I have made sample example as per my understanding from your question.
Please check below example.
$(document).on('change','input[name="rgroup"]',function() {
radio = $("input[name='rgroup']:checked").val();
$("#btn").val(radio);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="rgroup" value="test1">Test1
<input type="radio" name="rgroup" value="test2">Test2
<input type="radio" name="rgroup" value="test3">Test3
<input type="radio" name="rgroup" value="test4">Test4
<br>
<input type="button" id="btn" value="Change">
I have the following code:
<ul class='app-tasks'>
<li class='app-tasks__item'>
<label class='app-tasks__label'>
<input id='some' value='1' type='checkbox'/>
<span>One</span>
<div class='app-tasks__mark'></div>
</label>
</li>
<li class='app-tasks__item'>
<label class='app-tasks__label'>
<input id='some' value='2' type='checkbox'/>
<span>TWO</span>
<div class='app-tasks__mark'></div>
</label>
</li>
<li class='app-tasks__item'>
<label class='app-tasks__label'>
<input id='some' value='3' type='checkbox'/>
<span>Three</span>
<div class='app-tasks__mark'></div>
</label>
</li>
</ul>
The li are being taken from MySQL. The code below is used to delete it.
$('#some').change(function() {
if ($(this).is(':checked')) {
var id = $(this).val();
var dataString2 = 'id=' + id;
console.log(id);
$.ajax({
type: "GET",
url: "sub.php",
data: dataString2,
success: function() {
console.log("Okay");
var s = $('.app-tasks .app-tasks__item').length - 1;
$('.app-header__title').html('All Tasks (' + s + ')');
}
});
return false;
}
});
But the code is only being run on the first li. There is no problem with the PHP script.
Identifiers in HTML must be unique. Switch to CSS class to identify elements using Class Selector
<input class="some" value="1" type="checkbox"/>
Then use
$('.some').change(function() {
//Rest of the code
});
You can't use the same id twice. Name each one differently, or use classes instead and do:
$('.some').change(function()
{
});
I have an jquery ajax call where I add a new comment to a database. It saves just fine but when i want to reaload the div where the comments are shown, I always get an additional div which I do not want. When I reaload the page everything is just fine and displayed as wanted!
The script:
<script>
$("#addcmt").click(function() {
var UserID = $("#UserID").val();
var ClassID = $("#ClassID").val();
var text = $("#appendedInputButton").val();
var option;
if($("#option").is(':checked')) {
option = 3;
} else {
option = 1;
}
$.ajax({
type: "GET",
url: "/comment/functions/add_class_comment.php",
data: "text=" + text + "&UserID=" + UserID + "&ClassID=" + ClassID + "&option=" + option,
success: function(msg) {
$("#CommentList").load(location.href+' #CommentList');
$('#appendedInputButton').val("");
$('.criticalcomment').attr('checked', false);
}
});
});
</script>
The php+html where they comments are shown:
<div class="bs-docs-example" id="message">
<div id="CommentList">
<?php
for ($i=0; $i<$l; $i++) {
switch($commentarr[$i]->getOption()) {
case 1:
$option="alert-success";
break;
case 2:
$option="alert-info";
break;
case 3:
$option="alert-error";
}
echo '<div class="Comments alert '.$option.'"><div class="CommentsName">'.$userarr[$i]->getFirstname().' '.$userarr[$i]->getLastname().'</div>';
echo '<div class="CommentsDate">'.renderDate($commentarr[$i]->getDate()).'</div><div class="CommentsText">'.$commentarr[$i]->getText().'</div>';
if ($deletebutton == 1) {
echo '<div class="deleteButtonAdmin"><input type="button" class="btn btn-small btn-primary delcmt" value="Löschen" name="'.$commentarr[$i]->getID().'"></div>';
}
echo '</div>';
}
?>
</div>
<form class="Comments postmessage">
<div class="input-append" style="margin-top: 10px;">
<input type="hidden" name="ClassID" id="ClassID" value="<?php echo $c->getID(); ?>">
<input type="hidden" name="UserID" id="UserID" value="<?php echo $u->getID(); ?>">
<textarea class="span12" name="text" id="appendedInputButton" type="text"></textarea>
<label for="option">Kritisch?</label><input type="checkbox" id="option" class="criticalcomment" name="option" value="1">
<input type="button" class="btn" id="addcmt" value="Post">
</div>
</form>
</div>
I hope someone got an idea or hint for me!
Well, $("#CommentList").load(location.href+' #CommentList'); tells jQuery to replace the contents of #CommentList with #CommentList, so you get two nested #CommentLists, correct?
You might have to do $("#CommentList").remove().load(location.href+' #CommentList'). If that does not work, try introducing a temporary div:
$("<div />").load(location.href+' #CommentList', function (div) {
$('#CommentList').replaceWith($(div));
})
try adding this after loading the div!
$("#CommentList").find('div').unwrap(); or
$("#CommentList").find('#CommentList').unwrap();//I am doubtful about this