Ajax code only working on first <li> - php

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()
{
});

Related

How can i filter on checkbox using ajax php

I am using ajax in codeigniter, I have different checkbox now i want whenever someone checked
checkboxes,result should come according to user selection of checkboxes,so how can i do this ?
here is my code
<input type="checkbox" class="styled" id="Baker" value="Bakers">
<label for="role1">Bakers</label>
<input type="checkbox" class="styled" id="Bakerd" value="Bakersd">
<label for="role1">Bakersd</label>
<script>
$('.styled').click(function() {
alert($(this).attr('id'));
if(this.checked){
$.ajax({
type: "POST",
url: 'searchOnType.php',
data: $(this).attr('id'),
success: function(data) {
alert('it worked');
alert(data);
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});
</script>
Html
<ul class="unstyled centered">
<li>
<input type="checkbox" class="styled-checkbox" id="Baker" value="" onchange="checkBoxOnChange(this);">
<label for="role1">Baker</label>
</li>
<li>
<input type="checkbox" class="styled-checkbox" id="Barista" value="" onchange="checkBoxOnChange(this);">
<label for="role2">Barista</label>
</li>
<li>
<input type="checkbox" class="styled-checkbox" id="Bartender" value="" onchange="checkBoxOnChange(this);">
<label for="role3">Bartender</label>
</li>
<li id="filter">
</li>
</ul>
jQuery Script
<script>
function checkBoxOnChange(isChecked){
if($(isChecked).is(":checked")){
console.log("check");
$.ajax({
url: 'test.php',
type: 'POST',
data: {id: $(isChecked).attr('id')}, // I suggest you to use $(isChecked).val(). Add value in html same as id
success: function(data){
console.log(data);
$("#filter").text(data);
}
}
);
}else{
console.log("Uncheck");
}
}
</script>
Php Script
test.php example just return a selected checkbox value
<?php
echo ($_REQUEST['id']);
exit;
?>

Show success message on AJAX success

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();
},

Use jQuery to update database using POST method

I want to send every data from the form to an external php file and update the database values. It seems nothing happens. Console doesn't show any errors. I have searched for responses and nothing seems to work for me.
$(document).ready(function(){
$('#updatesettings').submit(function(e) {
e.preventDefault();
var lang = $(this).find('.dropdown-toggle').text();
console.log('lang=' + lang +'&'+ $(this).serialize());
$.ajax({
type: "POST",
url: "modules/game/updatesettings.php",
data: 'lang='+lang+'&'+$(this).serialize(),
}).done(function(data){
console.log(data);
})
.fail(function(error){
console.log(error);
});
;
});
});
<form id="updatesettings" method="post">
<p>
<label for="link">LINK</label>
<input type="text" name="link" class="textbox" id="link" value="<?php echo $tlink;?>" placeholder="LINK"> <?php if($tlink != "") echo'<i class="fa fa-check green"></i>'; else echo'<i class="fa fa-times red"></i>';?>
</p>
<p>
<label for="email">EMAIL</label>
<input type="text" name="email" class="textbox" id="email" value="<?php echo $email; ?>" placeholder="E-MAIL"><?php if($email != "") echo' <i class="fa fa-check green"></i>'; else echo' <i class="fa fa-times red"></i>';?>
</p>
<div class="btn-group">
<a class="btn dropdown-toggle btn-select" data-toggle="dropdown" href="#"><?php echo $langset; ?> <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><span class="flag flag-usa flag-1x"></span> English</li>
<li><span class="flag flag-rou flag-1x"></span> Romana</li>
</ul>
</div>
<p><input type="submit" class="button" href="#" value="Save settings"></p>
</form>
The external php file that I try to use for update is this.
<?php
#include_once('modules/connections/dbconn.php');
$link = $_POST["link"];
$link = mysql_real_escape_string($link);
$email = $_POST["email"];
$email = mysql_real_escape_string($email);
$id = $_SESSION["id"];
$lang = $_POST["lang"]
if($lang=="English"){
$lang="en";
}
else {
$lang="ro";
}
mysqli_query($GLOBALS['connect'],"UPDATE users SET `link`='$link' WHERE `id`='$id'");
mysqli_query($GLOBALS['connect'],"UPDATE users SET `email`='$email' WHERE `id`='$id'");
mysqli_query($GLOBALS['connect'],"UPDATE users SET `lang`='$lang' WHERE `id`='$id'");
exit;
?>
Thank you so much for trying to offer your help!
You are not handling the result in case of success(done) or error(fail). Try:
$.ajax({
type: "POST",
url: "updatesettings.php",
data: 'lang='+lang+'&'+$(this).serialize(),
})
.done(function(data){
console.log(data);
})
.fail(function(error){
console.log(error);
});
done() is called when your request is correct, fail() in case of some error.
Tip: press f12 and go to Network tab to check your requests.
Check this pen
There's two issues in your code. Firstly the querystring you're building is malformed. You need to add a & between the lang value and the rest of the serialised form data. Secondly the DOM traversal to get the .dropdown-toggle text is incorrect. this will refer to the form element so you need to use find() to work down the DOM, not parents() to go up it.
It would also be worth adding a success and error handler, at least to aid debugging. Try this:
$('#updatesettings').submit(function(e) {
e.preventDefault();
var lang = $(this).find('.btn-group .dropdown-toggle').text();
$.ajax({
type: "POST",
url: "updatesettings.php",
data: 'lang=' + lang + '&' + $(this).serialize(),
success: function() {
console.log('it worked!');
},
error: function(x, s, e) {
console.log('it failed');
console.log(x, s, e);
}
});
});

Using jQuery, JSON and AJAX,codeigniter to populate a submenu drop down

I have created a form with menu and submenu. I load the menu dropdown from database but i am facing the problem to load submenu from database using ajax,json and codeigniter pls solve my issue.. thanks in advance...
This is My view coding
<form action="" method="post" id="frm_submenu">
<div class="form-group">
<label for="menu">Select Menu</label>
<select class="form-control" id="selectmenuid">
<option value="">-- Select Menu --</option>
<?php foreach($showData as $show):?>
<option value="<?php echo $show->menu_id?>"><?php echo $show->menu_name?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label for="menu">Select Sub Menu</label>
<select class="form-control" id="selectsubmenu">
</select>
</div>
<div class="form-group">
<label for="imagetitle">Image Title</label>
<input type="text" class="form-control" name="imagetitle" id="imagetitle" placeholder="Enter Image Title" required="required">
</div>
<div class="form-group">
<label class="btn btn-default btn-file">
Browse <input type="file" style="display: none;">
</label>
</div>
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</form>
This is my ajax and jquery and json coding
$( "#selectmenuid" ).change(function() {
var id = $('#selectmenuid').val();
populate_submenu(id);
});
function populate_submenu(id){
$('#selectsubmenu').empty();
$('#selectsubmenu').append("<option>Loading ....</option>");
$.ajax({
type: "POST",
url : "<?php echo site_url('Admin_Creator/populate_submenu')?>/"+id,
contentType:"application/json;charset=utf-8",
dataType:'json',
success:function(data){
$('#selectsubmenu').empty();
$('#selectsubmenu').append("<option>Select Sub Menu</option>");
$.each(data,function(i,name){
$('#selectsubmenu').append('<option value="'+data[i].submenu_id+'"'+data[name].submenu_name+'</option>');
});
}
});
}
This is my controller coding
public function populate_submenu($id){
$smid=$id;
$data['query']= $this->db->select("select * from submenu where menu_id='$smid'");
echo json_encode($data);
}
You had an error when structuring your item html with appends. Use this instead:
$.each(data,function(key,value){
$('#selectsubmenu').append('<option value="'+value.submenu_id+'">'+value.submenu_name+'</option>');
});
You have a few problems at a first view. First your $smid variable should be in double quotes or escaped corespondingly. Variables in single quotes are treated as they look so your php code should look like this:
public function populate_submenu($id){
$smid=$id;
$data['query']= $this->db->select('select * from submenu where menu_id="$smid"');
echo json_encode($data);
}
In your JS code you are not closing the > from the starting open <option> tag in the each() method and getting the submenu_name wrong, you should get it by the index, so:
$('#selectsubmenu').append('<option value="' + data[i].submenu_id + '"' + data[name].submenu_name + '</option>');
should be:
$('#selectsubmenu').append('<option value="' + data[i].submenu_id + '">' + data[i].submenu_name + '</option>');
The code should be:
$("#selectmenuid").change(function() {
var id = $('#selectmenuid').val();
populate_submenu(id);
});
function populate_submenu(id) {
$('#selectsubmenu').empty();
$('#selectsubmenu').append("<option>Loading ....</option>");
$.ajax({
type: "POST",
url: "<?php echo site_url('Admin_Creator/populate_submenu')?>/" + id,
contentType: "application/json;charset=utf-8",
dataType: 'json',
success: function(data) {
$('#selectsubmenu').empty();
$('#selectsubmenu').append("<option>Select Sub Menu</option>");
$.each(data, function(i, name) {
$('#selectsubmenu').append('<option value="' + data[i].submenu_id + '">' + data[i].submenu_name + '</option>');
});
}
});
}

passing id name on click using ajax to php

i am using Ajax to make a filtered search system. I have three different tabs where users can search by names, by category and location.
I am able to seacrh when user enters name in the search box(tab-1).
In second tab, how can I use the same Ajax, so when user clicks a link, the id is passed in the ajax script to my php, and that id is passed as varibale in my mysql query.
First time with Ajax, any help would be highly appreciated.
AJAX script:
$(document).ready(function () {
$("#search_results").slideUp();
$("#button_find").click(function (event) {
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function (event) {
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way() {
$("#search_results").show();
var search_this = $("#search_query").val();
$.post("search.php", {
searchit: search_this
}, function (data) {
$("#display_results").html(data);
})
}
html:
<form id="searchform" method="post">
<input id="search_query" name="search_query" placeholder="What You Are Looking For?"
size="50" type="text" />
<input id="button_find" value="Search" type="submit" />
</form>
<div id="display_results">
</div>
<div class="tab">
<input id="tab-2" name="tab-group-1" type="radio" />
<label for="tab-2">Search by Category</label>
<div class="content">
<div id="searchbycategory">
<div id="nav_1_a">
<ul>
<li>All Categories</li>
<li>Category-1</li>
<li>Category-2</li>
<li>Category-3</li>
</ul>
<div id="display_results">
</div>
</div>
<!-- END nav_1_a -->
</div>
</div>
</div>
<div class="tab">
<input id="tab-3" name="tab-group-1" type="radio" />
<label for="tab-3">Search by location</label>
<div class="content">
<div id="searchbylocation">
<div id="nav_1_a">
<ul>
<li>All</li>
<li>Location-1</li>
<li>Location-2</li>
<li>Location-3</li>
<li>Location-4</li>
</ul>
</div>
search.php:
<?php
$connection = mysql_connect('localhost', 'user', 'pwd');
$db = mysql_select_db('db', $connection);
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = mysql_escape_string($term);
echo "Enter name to search";
else{
$sql = mysql_query("select col1,col2 from tab2 where tab2.somecolm like
'{$term}%'", $connection);
echo "<ul>";
if (mysql_num_rows($sql)){
while($info = mysql_fetch_array($sql, MYSQL_ASSOC ) ) {
echo "<li>";
echo "" . $info['col2'] . "";
echo "</li>";
}
}else{
echo "No matches found!";
}
echo "</ul>";
}
?>
Pass block id to search_ajax_way function:
$("#search_query").keyup(function(event){
event.preventDefault();
search_ajax_way(this.id);
});
Then pass block id in data param in ajax request:
function search_ajax_way(blockId){
$("#search_results").show();
var search_this=$("#search_query").val();
$.post("search.php", {searchit : search_this, 'blockId': blockId}, function(data){
$("#display_results").html(data);
})
}
Now blockId will be availible in your php script as $_POST['blockId'].
You say you want to pass the id when a link is clicked, but you don't have any code that handles link clicks. Add a click handler for links, and modify search_ajax_way() to accept an optional id for when links are clicked:
$("a").click(function (event) {
event.preventDefault();
search_ajax_way(this.id);
});
function search_ajax_way(clickedId) {
$("#search_results").show();
var postData = { searchit: $("#search_query").val() };
if (clickedId) {
postData.clickedId = clickedId;
}
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}
The id will be available in PHP as $_POST['clickedId']
Edit: Actually, I'd refactor to use search_ajax_way() as the event handler, rather than calling it from an anonymous event handler:
$("#button_find,a").click(search_ajax_way);
$("#search_query").keyup(search_ajax_way);
function search_ajax_way(event) {
event.preventDefault();
$("#search_results").show();
var postData = {
searchit: $("#search_query").val(),
clickedId: this.id
};
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}

Categories