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);
});
});
Related
I'm trying to refresh my div using an ajax call, but for some reason it only fires in the first click, what am i doing wrong.
the first time i click the button it do everything fine, after that nothing happens (the loading part the rest of the script works fine)
here is the code of my javascript:
$('.btn-filtrar').on('click', function(){
let id = $(this).closest('tr').data('id');
let filter_type = $(this).closest('tr').data('type');
let sort_order = document.getElementById(filter_type +'_sort-order_' + id).value;
//console.log(id, filter_type, sort_order);
$.ajax({
url: "index.php?route=module/eot_filter/saveFilter&token=<?php echo $token; ?>",
type: "POST",
data: {
id:id,
filter_type:filter_type,
sort_order:sort_order
},
success: function (result) {
$("#"+ filter_type +"").load(" #"+ filter_type +"");
}
});
});
You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content).
See http://api.jquery.com/on/#direct-and-delegated-events
$(document).on('click','.btn-filtrar' ,function(){
let id = $(this).closest('tr').data('id');
let filter_type = $(this).closest('tr').data('type');
let sort_order = document.getElementById(filter_type +'_sort-order_' + id).value;
//console.log(id, filter_type, sort_order);
$.ajax({
url: "index.php?route=module/eot_filter/saveFilter&token=<?php echo $token; ?>",
type: "POST",
data: {
id:id,
filter_type:filter_type,
sort_order:sort_order
},
success: function (result) {
$("#"+ filter_type +"").load(" #"+ filter_type +"");
}
});
});
I would suggest you to Click Here to get the better idea on why to use $(document).on("click", "YOUR SELECTOR") ... instead of $("YOUR SELECTOR").on("click",..).
So in your case, the code should be something like :
$(document).on('click','.btn-filtrar' ,function(){
let id = $(this).closest('tr').data('id');
let filter_type = $(this).closest('tr').data('type');
let sort_order = document.getElementById(filter_type +'_sort-order_' + id).value;
//console.log(id, filter_type, sort_order);
$.ajax({
url: "index.php?route=module/eot_filter/saveFilter&token=<?php echo $token; ?>",
type: "POST",
data: {
id:id,
filter_type:filter_type,
sort_order:sort_order
},
success: function (result) {
$("#"+ filter_type +"").load(" #"+ filter_type +"");
}
});
});
I'm trying to build a simple Like/Unlike button but I can't manage to to make it with the Unlike button because the function just won't fire.
Tried with .data and .attr.
HTML+PHP:
<span id="<?php echo $quote_id; ?>_count"><?php echo $likes_count; ?> likes</span>
<br>
<a class="like_button" data-q="<?php echo $quote_id; ?>" data-action="like" href="#">Like</a>
JS:
$(document).ready(function(){
$('.like_button[data-action="like"]').on('click',function(event){
event.preventDefault();
var q = $(this).attr('data-q');
$.ajax({
url: 'http://localhost/q/functions/l.php',
method: 'get',
data: {qi: q, a: "1"},
dataType: "json",
success: function(data)
{
$('#' + q + '_count').text((data.likes) + ' likes');
$('.like_button[data-action="like"]').data('action', 'unlike');
}
});
});
$('.like_button[data-action="unlike"]').on('click',function(event){
event.preventDefault();
var q = $(this).attr('data-q');
$.ajax({
url: 'http://localhost/q/functions/l.php',
method: 'get',
data: {qi: q, a: "0"},
dataType: "json",
success: function(data)
{
$('#' + q + '_count').text((data.likes) + ' likes');
$('.like_button[data-action="unlike"]').data('action', 'like');
}
});
});
});
Try this:
$(document).on('click', '.like_button', function(event){
if($(this).data('action') === 'like'){
// function for like button
} else if ($(this).data('action') === 'unlike'){
// function for unlike button
}
});
First, you don't need two onclick events. Also, cache $(this) so you don't have to re-query the DOM. Finally, try this code but the one in the snippet I had to remove all php and ajax from it, it's just to demonstrate how you could go about it with just one handler. hope it helps
$('.like_button').on('click',function(event){
var $this = $(this);
var action = $this.data('action');
event.preventDefault();
var q = $(this).attr('data-q');
$.ajax({
url: 'http://localhost/q/functions/l.php',
method: 'get',
data: {qi: q, a: action === 'like' ? "1":"0"},
dataType: "json",
success: function(data)
{
$('#' + q + '_count').text((data.likes) + ' likes');
$this.data('action', action === 'like' ? 'unlike':'like');
}
});
});
$('.like_button').on('click',function(event){
var action = $(this).attr('data-action');
console.log(action);
event.preventDefault();
$(this).attr('data-action', action === 'like' ? 'unlike':'like');
});
a[data-action="like"]{
background: gray;
color: lightgray
}
a[data-action="unlike"]{
background: blue;
color: lightblue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="<?php echo $quote_id; ?>_count"><?php echo $likes_count; ?> likes</span>
<br>
<a class="like_button" data-q="<?php echo $quote_id; ?>" data-action="like" href="#">Like</a>
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;
i cant pass the variable to my controller function.please help
<input type="button" id="mydate" name="mydate" value="<?php echo $dat;?>" class="monthYearPicker" />
script:
$('#mydate').on('click', function () {
var textBoxVal = $(this).val();
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>Money_c/selectallbudget', // link to CI function
data: {
val: $(this).val()
},
success: function (msg) {
console.log(msg);
}
});
});
how will i take this javascript variable var textBoxVal = $(this).val() in my controller function.
controller:
public function selectallbudget(){
$mydate= $this->input->post('val');
$sendMe = $this->money_m->selectbudget($mydate);
echo json_encode($sendMe);
}
With the help of ajax you can do it.
FIRST:
--------------------------------
<!--write this code in you header-->
<input type="hidden" value="<?php echo base_url(); ?>" id="baseurl"/>
<!--your javascript code-->
<script type="text/javascript">
var base_url = $('#baseurl').val();
var dateValue = $('#mydate').val();
$.ajax({
url: base_url + "controller_name/function_name", // define here controller then function name
method: 'POST',
data: { date: dateValue }, // pass here your date variable into controller
success:function(result) {
alert(result); // alert your date variable value here
}
});
</script>
<!--your controller function-->
public function budget()
{
$dat = $_POST['date'];
echo $dat;
}
--------------------------------
SECOND: if you want to load any html code then you use this method otherwise above first method
--------------------------------
<!--write this code in you header-->
<input type="hidden" value="<?php echo base_url(); ?>" id="baseurl"/>
<!--your javascript code-->
<script type="text/javascript">
var base_url = $('#baseurl').val();
var dateValue = $('#mydate').val();
$( "#mydate" ).load(
base_url + "controller_name/function_name", // define here controller then function name
{ date: dateValue }, // pass here your date variable into controller
function(){
// write code on success of load function
}
);
</script>
<!--your controller function-->
public function budget()
{
$dat = $_POST['date'];
echo $dat;
}
Your code is almost okay. There is only one change in your controller code:
Controller:
public function selectallbudget(){
//$mydate= $_POST['val']; This is not PHP this is codeigniter
$mydate = $this->input->post('val');
$sendMe = $this->money_m->selectbudget($mydate);
echo json_encode($sendMe);
}
Please make use of ajax. This problem has already been discussed here. Please refer it.
Pass Javascript Variables tp PHP Controller in Code Igniter
What you're doing wrong here is $(this).val() to pass on the input's value.
The this object's scope keeps on changing, and is quite different when you try to access in
data: {
val: $(this).val()
}
It's rather trying to access the current object at hand.
Solution's pretty simple though (since you're already initialising textBoxVal to the input's value.
$('#mydate').on('click', function () {
var textBoxVal = $(this).val();
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>Money_c/selectallbudget', // link to CI function
data: {
val: textBoxVal
},
success: function (msg) {
console.log(msg);
}
});
});
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.