I want to create an Add and Remove from ordered lists button for my site.
But I can not click again when I click add button or remove button.
<script>
$(document).ready(function () {
$('.order-lists div #add').click(function(e) {
$('.order-lists div').removeClass('active');
var $parent = $(this).parent();
if (!$parent.hasClass('active')) {
$parent.addClass('active');
var DataId = $(this).attr('value');
var requested = { 'id': DataId }
$.ajax({
type: 'POST',
url: 'config/process/order-lists.php',
data: requested,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
ids = data['mov_id'];
name = data['mov_name'];
mov_size = data['mov_size'];
$.cookie(ids, name);
$.cookie(name, mov_size);
$("#" + ids + ' ' + 'a').remove();
$("#" + ids).append('<a class="btn btn-danger" id="remove" href="javascript:void(0);" value="' + ids + '"> <i class="glyphicon glyphicon-shopping-cart"></i> Remove </a>');
});
}
e.preventDefault();
});
$('.order-lists div #remove').click(function(e) {
$('.order-lists div').removeClass('remove');
var $parent = $(this).parent();
if (!$parent.hasClass('remove')) {
$parent.addClass('remove');
var DataId = $(this).attr('value');
var requested = { 'id': DataId }
$.ajax({
type: 'POST',
url: 'config/process/order-lists.php',
data: requested,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
ids = data['mov_id'];
name = data['mov_name'];
mov_size = data['mov_size'];
$.removeCookie(ids, null);
$.removeCookie(name, null);
$("#" + ids + ' ' + 'a').remove();
$("#" + ids).removeClass('remove');
$("#" + ids).append('<a class="btn btn-danger" id="add" href="javascript:void(0);" value="' + ids + '"> <i class="glyphicon glyphicon-shopping-cart"></i> Add Order List </a>');
});
}
e.preventDefault();
});
});
</script>
use on function for dynamically added elements.
$(document).ready(function () {
$('.order-lists').on('click', '#add' , function(e) {
$('.order-lists div').removeClass('active');
var $parent = $(this).parent();
if (!$parent.hasClass('active')) {
$parent.addClass('active');
var DataId = $(this).attr('value');
var requested = { 'id': DataId }
$.ajax({
type: 'POST',
url: 'config/process/order-lists.php',
data: requested,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
ids = data['mov_id'];
name = data['mov_name'];
mov_size = data['mov_size'];
$.cookie(ids, name);
$.cookie(name, mov_size);
$("#" + ids + ' ' + 'a').remove();
$("#" + ids).append('<a class="btn btn-danger" id="remove" href="javascript:void(0);" value="' + ids + '"> <i class="glyphicon glyphicon-shopping-cart"></i> Remove </a>');
});
}
e.preventDefault();
});
});
same for remove.
Related
Really struggling to get a relative path to work for an Ajax request.
From like.js I'm trying to get to likeunlike.php
Error message:
jquery-3.3.1.js:9600 POST http://localhost:8000/serverside/likeunlike.php 404 (Not Found)
File structure:
JQuery:
$(document).ready(function(){
// like and unlike click
$(".content").on("click",".like",function(){
var id = $(this).attr("id"); // Getting Button id
var split_id = id.split("_");
var postid = split_id[1];
var userid = split_id[2];
// AJAX Request
$.ajax({
url: '../serverside/likeunlike.php',
type: 'post',
data: {postid:postid,userid:userid},
dataType: 'json',
success: function(data){
var likes = data['likes'];
var type = data['type'];
$("#likes_" + postid + "_" + userid).text(likes);
if(type == 1){
$("#like_" + postid + "_" + userid).css("color","lightseagreen");
}
if(type == 0){
$("#like_" + postid + "_" + userid).css("color","#ffa449");
}
}
});
});
});
Have provided the index file as requested by one of the answers. Hope it helps.
Index.php:
<?php
include "detail/config.php";
?>
<html>
<head>
<title>Talk</title>
<link href="style/style.css" type="text/css" rel="stylesheet" />
<script src="jquery/jquery-3.3.1.js" type="text/javascript"></script>
<script src="search/script/like.js" type="text/javascript"></script>
<script src="search/check/check.js" type="text/javascript"></script>
</head>
<script>
$(function() {
$('form').on("submit", function(e) {
e.preventDefault();
$('#error').text(""); // reset
var name = $.trim($("#search").val());
if (name.match(/[^a-zA-Z0-9 ]/g)) {
$('#error').text('Please enter letters and spaces only');
return false;
}
if (name === '') {
$('#error').text('Please enter some text');
return false;
}
if (name.length > 0 && name.length < 3) {
$('#error').text('Please enter more letters');
return false;
}
$.ajax({
url: 'search/search.php',
method: 'POST',
data: {
msg: name
},
dataType: 'json',
success: function(response) {
$(".content").html("")
$(".total").html("")
if(response){
var total = response.length;
$('.total') .append(total + " Results");
}
$.each(response, function() {
$.each($(this), function(i, item) {
var mycss = (item.Type == 1) ? ' style="color: #ffa449;"' : '';
$('.content').append('<div class="post"><div class="post-text"> ' + item.MessageText + ' </div><div class="post-action"><input type="button" value="Like" id="like_' + item.ID + '_' + item.UserID + '" class="like" ' + mycss + ' /><span id="likes_' + item.ID + '_' + item.UserID + '">' + item.cntLikes + '</span></div></div>');
});
});
}
});
});
});
</script>
<body>
<form action="index.php" method="post" id="myForm" autocomplete="on"><pre>
<input name="msg" id="search" type="text" autofocus value= "<?php if(isset($_POST['msg'])) {
echo htmlentities ($_POST['msg']); }?>"></input> <span id="error"></span>
<input type="submit" style="border:0; padding:0; font-size:0">
</pre></form>
<div class="total">
</div>
<div class="content">
</div>
</body>
</html>
jquery / js has no information about his location.
this should be work.
var base_url = window.location.origin;
// like and unlike click
$(".content").on("click",".like",function(){
var id = $(this).attr("id"); // Getting Button id
var split_id = id.split("_");
var postid = split_id[1];
var userid = split_id[2];
// AJAX Request
$.ajax({
url: base_url + '/search/serverside/likeunlike.php',
type: 'post',
data: {postid:postid,userid:userid},
dataType: 'json',
success: function(data){
var likes = data['likes'];
var type = data['type'];
$("#likes_" + postid + "_" + userid).text(likes);
if(type == 1){
$("#like_" + postid + "_" + userid).css("color","lightseagreen");
}
if(type == 0){
$("#like_" + postid + "_" + userid).css("color","#ffa449");
}
}
});
});
});
I have resolved the situation by:
Making my directory structure simpler as well as the file names. It was over-engineered. I have my root folder now and then just one level below that for folders.
The Ajax url path, which I was struggling with was amended to 'serverside/like.php', which picked up the php file but nothing happened.
Reviewing the like.php code I had an include("../con/config.php") without a ';'. I added this and it's now working fine.
Thank you for everyone's help. Much appreciated as always.
New folder structure:
When I click the submit on button, the appended elements are not submitted. I already tried to change append() to appendTo() and html(). Please help.
$('select[name="bidang"]').on('change', function(e) {
e.preventDefault();
var id_bidang = $(this).val();
// AJAX request
$.ajax({
url: '<?php echo base_url()?>form_jurnal/getSubBidang',
method: 'GET',
data: {
id_bidang: id_bidang
},
dataType: "json",
success: function(response) {
$('select[id="sub_bidang"]').empty();
$.each(response, function(key, value) {
$('select[id="sub_bidang"]')
.append('<option value="' + value.id_subbidang + '
selected ">'+ value.nama_subbidang +'</option>');
});
}
});
});
<label>Sub Bidang :</label>
<select id="sub_bidang" name="sub_bidang">
<option>--Pilih Sub Bidang--</option>
</select>
EDITED with UPDATED CODE: Im missing something here; the jQuery is working, but the variables arent passing to the query. Below is all of the updated code:
<span class="accepted"><input type="button" title="accept" value="Accept" /></span>
AJAX Script
<script type="text/javascript">
$(function() {
$(".accept").click(function(){
var element = $(this);
var del_id = element.attr("id");
var order_id = element.attr("data-order");
//if(confirm("Are you sure you want to delete this?"))
//{
$.ajax({
type: "POST",
url: "accept.php",
//data: info,
data: {id:del_id,order_id:order_id},
success: function(){}
//
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
//}
//return false;
});
});
</script>
new php file
include('db.php');
$id = $_POST['id'] ;
$name = $_POST['order_id'] ;
$sql = "UPDATE mgap_orders SET mgap_status = 1 WHERE mgap_ska_id = :id AND mgap_ska_report_category = :name";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':id' => '$id',
':name' => '$name'
));
Instead of using var info = 'id=' + del_id; and data: info, You should send variables like below:
data: {id:del_id}
Future more, if you want to pass more variables you can go like below:
data: {id:del_id,order:ORDER_ID}
Hope this helps.
do like this
$.ajax({
type: "POST",
url: "delete.php",
data: {id:del_id,order:order_variable},
success: function(){
}
Specify your Data as an object. Should be separated by comma for each variable.
data: {variablename1: value1, variablename2: value2}
So you code should look like:
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("id");
//var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: { id: del_id, var2: var2, var3: var3 },
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("data-id");
var order_id = element.attr("data-order");
var info = 'id=' + del_id;
var order = 'order' + order_id;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "mod_accept.php", //Changed the processor file
data: {info, order},
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
Then in your html:
<span class="accepted"><input type="button" title="accept" value="Accept" /></span>
do something like
<span class="accepted">
<a href="#" class="delete" id="<?php echo $id1; ?>"
data-order="<?php echo $order_id;?>">
<input type="button" title="accept" value="Accept" /></a>
</span>
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("id");
var order_id = element.attr("data-order");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: {id:del_id,order_id:order_id},
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
I have to implement two functions, append and delete on set of comments. The insertion and deletion are working properly unless in one case.
When i try to remove newly added comment (before refreshing page), it wont remove. But when i refresh the page that comment removes swiftly.
Here's some code.
Following ajax is appending and removing the comment div.
<script type="text/javascript">
$(function() {
$(".commentbutton").click(function()
{
var element = $(this);
var postid = element.attr("id");
var commenttext = $("#commenttext"+postid).val();
var dataString = 'commenttext='+ commenttext+'&postid='+postid;
var postseq='#post'+postid;
if(commenttext=='')
{
alert("Please enter your comment");
}
else
{
//$("#flash").show();
//$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
$(postseq).append(html);
$(postseq).slideDown();
document.getElementById('commenttext'+postid).value='';
}
});
}
return false;
});
$('.delcombutton').click(function()
{
var commid = $(this).attr("id");
var dataString = 'delcomm=1&commid='+commid;
var delcomment = '#comment'+commid;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
cache: false,
success: function(html){
$(delcomment).slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
</script>
Structure of my div
echo "<div id='post{$postseq}'>";
while($commentonpost=mysql_fetch_array($resultcomm)){
if($commentonpost['visible']==1){
echo '
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;" id="comment'.$commentonpost['commentid'].'">
<div style="width:10%;float:left;"><a href="profile.php?user='.$commentonpost['usernick'].'" >'.$commentonpost['fname']." ".$commentonpost['lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;">'.$commentonpost['comment'].'</div>
<div style="width:8%;float:right;margin-left:2%;">
';
if($commentonpost['usernick']==$_SESSION['user_nick']){
echo ' <form action="" method="post">
<input type="submit" name="delcomm" value="X" class="delcombutton" id="'.$commentonpost['commentid'].'">
</form>
';
}
echo '<h5 class="msg">'.datetime($commentonpost['date']).'</h5>
</div>
<br/>
</div>
';
}
}
echo "</div>";
echo '
<form name = "form'.$postseq.'" method = "post" action="" onsubmit="return validateform()" style="width:100%">
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;">
<div style="width:10%;float:left;"><a href="profile.php?user='.$_SESSION['user_nick'].'" >'.$_SESSION['user_fname']." ".$_SESSION['user_lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;"><textarea placeholder="Comment..." name="commenttext" id="commenttext'.$postseq.'" class="inputcomment" ></textarea></div>
<br>
<input type="submit" id="'.$postseq.'" name="SubmitComment" value="Comment " class="commentbutton" style="font-size:1em;width:100px;float:right;margin-top:4px;margin-right:9%;">
</div>
</form>
</div>
';
PS: Sorry for such a raw code, i have very limited internet now.
You have to use delegation for dynamically added elements:
$(document).on('click','.delcombutton',function(){...});
Use event delegation model with .on() for dynamically added elements
$(function() {
$(document).on('click', '.commentbutton', function() {
var element = $(this);
var postid = element.attr("id");
var commenttext = $("#commenttext"+postid).val();
var dataString = 'commenttext='+ commenttext+'&postid='+postid;
var postseq='#post'+postid;
if(commenttext=='') {
alert("Please enter your comment");
}
else {
//$("#flash").show();
//$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
$(postseq).append(html);
$(postseq).slideDown();
document.getElementById('commenttext'+postid).value='';
}
});
}
return false;
});
$(document).on('click', '.delcombutton', function() {
var commid = $(this).attr("id");
var dataString = 'delcomm=1&commid='+commid;
var delcomment = '#comment'+commid;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
cache: false,
success: function(html){
$(delcomment).slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
I use codeigniter. And I have three field with the class .eghamat. I don't know why autocomplete doesn't work in the two first fields (INSERT VALUE HERE 1, INSERT VALUE HERE 2) but works in the third(INSERT VALUE HERE 3).
The problem might come from one of the following:
The php code
the $.each loop
the ajax call
Does someone see what's wrong?
html:
<div class="bg_units bu0">
<div class="auto_box">
<b class="search_hotel">
<div class="mediumCell">
<input type="text" name="hotel_auto" class="eghamat" placeholder="INSERT VALUE HERE 1">
</div>
<ul class="list_autobox_hotel">
</ul>
</b>
</div>
</div>
<div class="bg_units bu1">
<div class="auto_box">
<b class="search_hotel">
<div class="mediumCell">
<input type="text" name="hotel_auto" class="eghamat" placeholder="INSERT VALUE HERE 2">
</div>
<ul class="list_autobox_hotel">
</ul>
</b>
</div>
</div>
<div class="bg_units bu2">
<div class="auto_box">
<b class="search_hotel">
<div class="mediumCell">
<input type="text" name="hotel_auto" class="eghamat" placeholder="INSERT VALUE HERE 3">
</div>
<ul class="list_autobox_hotel">
</ul>
</b>
</div>
</div>
php:
function auto_complete() {
$hotel_search = $this ->input-> post('hotel_auto');
$query = $this->db->query("SELECT * FROM hotel_submits WHERE name LIKE '%$hotel_search%' ORDER BY name asc");
if($query->num_rows()==0){
return '0';
}else{
$data = array();
foreach ($query->result() as $row)
{
$units = json_decode($row->units);
$data[] = array('name' => $row->name, 'units' =>$units );
}
}
echo json_encode($data);
}
jQuery:
$('.auto_complete_eghamat').live('keyup',function () {
var $this = $(this),
$div = $this.closest('div.bg_units'),
bu_num = '.' + $div.attr('class').split(" ")[1];
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: 'auto_complete',
data: dataObj,
cache: false,
success: function (data) {
//alert(dataObj);
var id_name = $(bu_num+' .list_autobox_hotel').attr('id');
$(bu_num+' .list_autobox_hotel').show().html('');
if (data == 0) {
$(bu_num+' .search_hotel').show().html('<p><b>there is no</b></p>');
} else {
$.each(data, function (index, value) {
$('<p id="' + value.name + '">' + value.name + '</p>').appendTo(bu_num+' .list_autobox_hotel');
});
$('body').click(function () {
$(".list_autobox_hotel p").hide().remove();
$('.auto_complete').val('');
$('.list_autobox_hotel').show().html('');
$('.list_autobox_hotel').css('display', 'none');
});
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
could you please rename id="tour" and id="hotel" cz html cannot have same ids multiple times
id="tour"
and also
id="hotel"
appears 3 times in the code so please look into it.
could you please try it out. and let me know.your admin.js should be like this
$(document).ready(function () {
$('.list_autobox_hotel p').click(function() {
$(this).parent().parent().find('.eghamat').val($(this).text());
});
$(document).click(function() {
if($('.list_autobox_hotel').is(':visible')){
$('.list_autobox_hotel').hide();
}
return true;
});
////////////////////////////////////////////////////////////////
$('#loadingDiv').hide() // hide it initially
.ajaxStart(function () {
$(this).show();
}).ajaxStop(function () {
$(this).hide();
});
///////auto_complete///////////////////////////////////////////////
$('.eghamat').live('keyup', function () {
var $this = $(this),
$div = $this.closest('div.bg_units'),
bu_num = '.' + $div.attr('class').split(" ")[1];
var dataObj = $(this).closest('form').serialize();
//alert(dataObj);
$.ajax({
type: "POST",
dataType: 'json',
//url: 'binboy.gigfa.com/admin/…',
url: 'auto_complete',
data: dataObj,
cache: false,
success: function (data) {
//alert(bu_num);
var id_name = $(bu_num + ' .list_autobox_hotel').attr('id');
$(bu_num + ' .list_autobox_hotel').show().html('');
if (data == 0) {
$(bu_num + ' .list_autobox_hotel').show().html('<p><b>there is no</b></p>');
} else {
$.each(data, function (index, value) {
$('<p >' + value.name + '</p>').appendTo(bu_num + ' .list_autobox_hotel');
});
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});
Here is a simple code
$('.eghamat').click(function(){
var id =$(this).attr('id');
//Here you have the id select with it and put your code in it
});