I am trying to update an id with a value from another button, here's what I have up to now:
$('.viewemployment').on('click', function(e){
var url = '<?php echo Config::get('URL'); ?>dashboard/employment_json/' + this.id;
$.get(url,function(d){
document.getElementById("update_employment").value = this.id;
},'json');
});
The above is working, because the rest of my code (which I have removed) is working, but the set value isn't. This is the button I am trying to set a value to the id
<button type="button" class="btn btn-default waves-effect update_employment" id="update_employment" style="display: none;"><?php echo System::translate("Update Employment"); ?></button>
I want to use the id of this button for an ajax request:
$('.update_employment').on('click', function(e){
$.ajax({
url: "<?php echo Config::get('URL'); ?>/dashboard/update_employment/" + $("input[name='json_name']").val() + "/" +
$("#json_country").find(":selected").text() + "/" + $("input[name='json_start']").val() + "/" + $("input[name='json_end']").val()
+ "/" + $("input[name='json_duration']").val() + "/" + $("input[name='json_description']").val() + "/" + this.id + "/" + "<?php echo System::escape(Session::get('token')); ?>",
cache: false,
success: function(html){
<!-- success !-->
}
});
but the this.id is being passed as update_employment rather than the new value which shouldv'e been set
You need to get the target's id from the Event. e is an Event
$('.viewemployment').on('click', function(e){
var url = '<?php echo Config::get('URL'); ?>dashboard/employment_json/' + this.id;
$.get(url,function(d){
document.getElementById("update_employment").value = e.target.id;
},'json');
});
I don't think it's a good idea to change the id, because you can soon lose track of it as the complexity of you app increases. Instead, you could capture the value of this.id to a variable and store it using jQuery's .data() function:
$('.viewemployment').on('click', function(e){
var theId = this.id;
var url = '<?php echo Config::get('URL'); ?>dashboard/employment_json/' + theId;
$.get(url,function(d){
$("#update_employment").data("idToQuery", theId);
},'json');
});
Then access it with:
$("#update_employment").data("idToQuery")
If you really must change the button's id, you can do it through jQuery's .attr() function:
$('#update_employment').attr('id', theId)
Try changing the following line:
document.getElementById("update_employment").value = this.id;
to:
document.getElementById("update_employment").id = this.id;
Related
I'm trying to make two Ajax calls in one page using jQuery. The first Ajax runs successfully and produces results. Second Ajax is supposed to fire up on button click and show the result, but it runs twice every time I click on the button. And initially on the first time clicking on the button, I have to click twice before it produces a result. Here's what I'm trying to do:
function showPicture() {
$("button").click(function() {
var id = this.id;
$.ajax({
type: 'POST',
url: 'displaySearch.php',
data: {'getTile': $(this).val()},
success: function(data) {
console.log(id);
$("#" + id).replaceWith("<img src=" + data + " />");
}
});
});
}
Here's my button:
<button id=" . $count . " onclick=showPicture() value=" . htmlentities($result['Poster']) . ">Click Me!</button>
I have seen similar questions on Google but I cannot figure out what the problem is. Any help would be greatly appreciated.
You have 2 onClick handlers, somewhat:
onClick
$("button").click()
Remove one of the handlers.
Example
function showPicture(id) {
$.ajax({
type: 'POST',
url: 'displaySearch.php',
data: {'getTile': $(this).val()},
success: function(data) {
console.log(id);
$("#" + id).replaceWith("<img src=" + data + " />");
}
});
}
<button id=" . $count . " onclick=showPicture(" . $count . ") value=" . htmlentities($result['Poster']) . ">Click Me!</button>
Your function 'showPicture' which you are calling from the html attribute below
<button id=" . $count . " onclick=showPicture()
is calling your function as you would expect.
but the function showPicture() itself is then binding a onclick event
function showPicture() {
$("button").click(function() { <------- this
......
So it is being hit twice as you have the attribute onclick and the even binding onclick.
The event click is on all html buttons.
What you should do: Remove the binding in the function to all buttons
function showPicture(caller) {
var id = $(caller).attr("id");
var val = $(caller).val();
console.log(id);
console.log(val);
$.ajax({
type: 'POST',
url: 'displaySearch.php',
data: {'getTile': val },
success: function(res) {
--you are replacing the button with an image... or something like that
$("#" + id).replaceWith("<img src=" + res+ " />");
}
});
}
html
<button id=".$count." onclick="showPicture(this)" value=".htmlentities($result['Poster']).">Click Me!</button>
I have been working on a e-commerce web application. There is a wishlist module which I'm trying to implement. I'm adding the products into wishlist using ajax calls and also removing it with ajax. The adding part works fine but I have a problem in removing part . What I'm trying to do is, making an ajax call to fetch the wishlist items from the database and adding a remove button dynamically using jquery. Although I know that I have to use a .live function to attach an event to it which I did but when i click on the button all the items which are present in the wishlist are removed . I see multiple ajax request was made in console under network tab and I don't get it why , although I clicked it only once. The following is a snippet of my code
$.ajax({
type: "POST",
url: "fetchdata1",
data: "cat=" + cat,
success: function(data) {
productContainer.innerHTML = "";
var $productContainer = $('#productContainer');
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span>\n\
<br/><br/><a id='remove' href='#'>REMOVE</a></div>");
foo(value['id']);
} else {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span></div>");
}
});
}
});
function foo(value) {
var pid = value;
$('#remove').live("click", function() {
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});
In the first ajax request I'm fetching products from the database then adding remove button to it dynamically then calling function foo which attach the click event using .live function and then make call to database to remove it.
Hey guys I'm not pro at web, so go easy on me if I made some silly mistake.
Thanks!
Problem:
You have same id for multiple hyperlink and you are using .live function on "id based" selector. It is applying click function again & again on first element.
Solution:
Update your hyperlink
<a href='#' onclick="foo(this)" pid=value['id']>REMOVE</a>
Then in foo() function
function foo(obj) {
var pid = $(obj).attr("pid");
$(obj).bind("click", function() {
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});
i don't get why you using same id multiple times.
and afaik, jQuery.live already deprecated.
you can use this if you want to get live behavior:
$(document).on('click', 'element-selector', function(){
...
});
with your code, it can rewriten to:
$(document).on('click', '[id=remove]', function(){
...ajax call...
});
now the problem with your fetch data function is this:
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
...append element...
**foo(value['id']);**
} else {
...append element...
}
});
as we know foo() are your function that bind remove behavior.
based on your code, whenever that fetch data has newVar = 1, it will directly call foo. which mean binding remove behavior multiple times, as many as newVar = 1 was.
solution:
you can put pid as a attribute on your a element
maybe something like remove
and within remove click function, you can use $(this).attr('pid') to get that value.
and remove that foo() content to outside the function, since $(element).live(...) or $(document).on(event, element, ...) will listen the element, even the element dynamicly added to the page.
The issue happened because you register listener multiple times in each loop. So to resolve, you need to register once after all button has been populated. I also change selector to class ".remove" because you going to have multiple remove button so using id is will be duplicated, and using jquery .on() instead of .live() (deprecated)
$.ajax({
type: "POST",
url: "fetchdata1",
data: "cat=" + cat,
success: function(data) {
productContainer.innerHTML = "";
var $productContainer = $('#productContainer');
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span>\n\
<br/><br/><a class='remove' id='remove' data-pid='" + value['id'] + "' href='#'>REMOVE</a></div>");
} else {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span></div>");
}
});
foo();
}
});
function foo() {
$('.remove').on("click", function() {
var pid = $(this).data("pid");
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});
I have select html tag, which value get from database, and the data will return to query and return an value to another dropbox.
My tag HTML like this:
And i want to give the value of data which is selected to another dropdown here:
And my javascript like this:
And the url direct to here:
And the model like this :
How i can change value to id sektor 20, when i have selecting a dropdown from sektor10?, and how to return value from controller and change value of sektor20?
A working sample what I have done for selecting from dropdown and display values as per the selected value.
In your controller-
function functionname($id){
$details = $this->your_model->get_details($id);
echo json_encode($details);
exit;
}
In Model-
function get_details($id){
$this->db->select('*');
$this->db->from('packages');
$this->db->where('package_id',$id);
$query = $this->db->get()->result();
return $query;
}
Javascript-
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("#sector10").change(function() {
var selectedMark = $("#sector10").val();
if (selectedMark != "") {
jQuery.ajax({
type: 'POST',
dataType: "json",
async:false,
url: "<?php echo base_url() . 'loyalty/functionname/'; ?>" + selectedMark,
success: function(data)
{
$("#cards").html("");
$("#cards").append("<option value=''>Select a Card</option>");
var index=1;
$.each(data, function() {
$("#cards").append("<option value='" + this.card_id + "'>" + this.card_name + "</option>");
$("div#cards_chosen div.chosen-drop ul.chosen-results").append("<li class='active-result' data-option-array-index='"+index+"' >" + this.card_name + "</li>");
index++;
});
}
});
}
});
});
</script>
I have this jQuery AJAX Like Dislike Script
<script>
$(function(){
var PostID = <?php echo $PostID; ?>;
$('.like-btn').click(function(){
$('.dislike-btn').removeClass('dislike-h');
$(this).addClass('like-h');
$.ajax({
type:"POST",
url:"rate.php",
data:'Action=LIKE&PostID='+PostID,
success: function(){
}
});
});
$('.dislike-btn').click(function(){
$('.like-btn').removeClass('like-h');
$(this).addClass('dislike-h');
$.ajax({
type:"POST",
url:"rate.php",
data:'Action=DISLIKE&PostID='+PostID,
success: function(){
}
});
});
});
</script>
Now I want to transform this script to multi post Like Dislike System.
How i can do this? HTML will look like this:
Like
Dislike
LIKE/DISLIKE will be action, 1 will be ID of post to like/dislike. Thanks
you can make something like this. Each post it is each div with postId and two controls inside (like and dislike buttons). When you click like - function will get post id and send with post to server. You must to check ajax part of function.
$(function () {
$('.like').click(function () { likeFunction(this); });
$('.dislike').click(function () { dislikeFunction(this);});
});
function likeFunction(caller) {
var postId = caller.parentElement.getAttribute('postid');
$.ajax({
type: "POST",
url: "rate.php",
data: 'Action=LIKE&PostID=' + postId,
success: function () {}
});
}
function dislikeFunction(caller) {
var postId = caller.parentElement.getAttribute('postid');
$.ajax({
type: "POST",
url: "rate.php",
data: 'Action=DISLIKE&PostID=' + postId,
success: function () {}
});
}
<div class="post" postid="10">
<input type="button" class='like' value="LikeButton" /> </input>
<input type="button" class='dislike' value="DislikeButton"> </input>
</div>
If you have some questions or need more help you can ask me :)
If you want more than one post per page you can do this:
function send(action, id)
{
var opposite;
opposite = action === 'like' ? 'dislike' : 'like';
$('#' + opposite + '-' + id).removeClass(opposite + '-h');
$('#' + action + '-' + id).addClass(action + '-h');
$.ajax({
type:"POST",
url:"rate.php",
data:'Action=' + action + '&PostID=' + id,
success: function(){
}
});
}
Now you only need to attach the handlers properly ($PostID must be different for every post in a loop):
<a href="#"
id="like-<?php echo $PostID; ?>"
onclick="send('like', <?php echo $PostID; ?>)">Like</a>
<a href="#"
id="disloke-"<?php echo $PostID; ?>"
onclick="send('dislike', <?php echo $PostID; ?>)">Dislike</a>
That's just a layout of the code, there may be defects. It's pretty different from where we started, so only you can actually test it and see where it need refinement.
I am trying to call jQuery function when button is clicked. But I am getting the error as follows:
Uncaught ReferenceError: update_question_ajax is not defined
HTML:
<button type="button" class="update-question-<?php echo $i; ?> button" onclick="update_question_ajax(<?php echo $i; ?>)" style="outline: 0 none;"><?php _e('Update') ?></button>
jQuery:
$(function(){
function update_question_ajax(id)
{
var test = $('.edit-question-' + id + ' input[name="translated"]');
var editedQuestionId = $('#question-id-'+id).val();
var editedQuestionObj = $('.edit-question-' + id + ' input[name="translated"]').val();
var modalObj = $('#myQuestionModal');
$.ajax({
type: "POST",
url: "<?php echo base_url('admin/question/admin_edit_question'); ?>",
data:{
edited_question: editedQuestionObj,
question: editedQuestionId
},
success: function(){
modalObj.dialog('close');
modalObj.html('');
},
complete: function(){
//window.location.reload(true);
}
});
return false;
}
});
I appreciate if you guys help me out about this.
Thank you!
Seems to be a scope issue. You've defined the function essentially inside another function. You should also try to avoid placing php inside javascript. Technically it works, but isn't really good form.
Removed the inline click handler.
<button type="button" class="update-question button" data-id="<?php echo $i; ?>" style="outline: 0 none;"><?php _e('Update') ?></button>
Then we create a self executing function, pass jQuery in as $ which gives everything inside the ability to use "$" as jQuery. Then define your click handler for the button and use a data attribute to pass the id rather than using PHP mixed in your JS and placing it in the DOM. Just feels a little cleaner. Also, make sure you are loading jquery / other scripts at the bottom of your document, just before the close body. This way you don't need a .ready because your document will already be loaded.
(function($){
// Define click handler.
$('button.update-question').on('click', function(e){
e.preventDefault();
var id = $(this).data('id');
update_question_ajax(id);
});
function update_question_ajax(id) {
var test = $('.edit-question-' + id + ' input[name="translated"]'),
editedQuestionId = $('#question-id-'+id).val(),
editedQuestionObj = $('.edit-question-' + id + ' input[name="translated"]').val(),
modalObj = $('#myQuestionModal');
$.ajax({
type: "POST",
url: "YOURURL",
data:{
edited_question: editedQuestionObj,
question: editedQuestionId
},
success: function(){
modalObj.dialog('close');
modalObj.html('');
},
complete: function(){
//window.location.reload(true);
}
});
}
}(jQuery));
You should move the function definition outside of the document.ready callback ($(function() { ... }):
function update_question_ajax(id) {
var test = $('.edit-question-' + id + ' input[name="translated"]');
var editedQuestionId = $('#question-id-'+id).val();
var editedQuestionObj = $('.edit-question-' + id + ' input[name="translated"]').val();
var modalObj = $('#myQuestionModal');
$.ajax({
type: "POST",
url: "<?php echo base_url('admin/question/admin_edit_question'); ?>",
data:{
edited_question: editedQuestionObj,
question: editedQuestionId
},
success: function(){
modalObj.dialog('close');
modalObj.html('');
},
complete: function(){
//window.location.reload(true);
}
});
return false;
}
Everything you put inside the $(function() {} is executed when the DOM is ready but is private to its scope.
If on the other hand you want to use unobtrusive javascript, then get rid of this onclick attribute from your markup:
<button type="button" class="button update-question-<?php echo $i; ?>" dtaa-id="<?php echo $i; ?>" style="outline: 0 none;"><?php _e('Update') ?></button>
and then use the document ready callback to unobtrusively subscribe to the .click event of those buttons:
$(function() {
function update_question_ajax(id) {
var test = $('.edit-question-' + id + ' input[name="translated"]');
var editedQuestionId = $('#question-id-'+id).val();
var editedQuestionObj = $('.edit-question-' + id + ' input[name="translated"]').val();
var modalObj = $('#myQuestionModal');
$.ajax({
type: "POST",
url: "<?php echo base_url('admin/question/admin_edit_question'); ?>",
data:{
edited_question: editedQuestionObj,
question: editedQuestionId
},
success: function(){
modalObj.dialog('close');
modalObj.html('');
},
complete: function(){
//window.location.reload(true);
}
});
return false;
}
$('.button').click(function() {
var id = $(this).data('id');
return update_question_ajax(id);
});
});