$.post in jquery is not working? - javascript

My $.post is not working as I am trying to extract JSON data from my PHP file, I don't know the reason why it's not showing the output?
Here's my code.
HTML:
<pre id="love" type="submit" data-toggle="modal" data-target="#myModal" onclick="mymodal(\''+this["id"]+'\')">'+this["love"]+' students <i class="glyphicon glyphicon-heart fa-lg" style="color:red"></i></pre >
where this["id"] has been passed to mymodal() function.
javascript code:
var list='';
function mymodal(id){
$.post('postname_.php',{post_id:id},function(data1){
$.each(data1.result,function(){
list+='<div class="modal fade" id="myModal" role="dialog">'+'<div class="modal-dialog">'+'<div class="modal-content">'+
'<div class="modal-header">'+'<button type="button" class="close" data-dismiss="modal">×</button>'+
'<h4 class="modal-title">Students who loved your post</h4>'+' </div>'+'<div class="modal-body">';
list+='<h4 class="text-danger">'+this["finame"]+' '+this['sename']+'</h4>';
list+='</div>'+'<div class="modal-footer">'+
'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'+'</div>'+
'</div>'+'</div>'+'</div>';
$('#insert').append(list);}),'json'
});
}
my php code:
<?php
require("../vendor/library50-php-5/CS50/CS50.php");
CS50::init(__DIR__ . "/../config.json");
$result=array();
$frows3=CS50::query("SELECT * FROM userhit WHERE plove=? AND bypost=?",1,$_POST['post_id']);
foreach($frows3 as $frow3){
$frow4=CS50::query("SELECT * FROM userinfopersonal WHERE user_id=? ",$frow3['user_id']);
$frow5=CS50::query("SELECT * FROM userprof WHERE user_id=? ",$frow3['user_id']);
array_push($result,array('finame'=>$frow4[0]['firstname'],'sename'=>$frow4[0]['secondname'],'url1'=>$frow5[0]['url']));
}echo json_encode(array('result'=> $result)); ?>
where CS50::query provides me all my rows of table which satisfy the given query, no worry about that, I checked that's giving perfect json file. The main problem is the alert in function mymodal() is working that means on clicking pre tag it's coming inside function, but the alert inside $.post is not executed.

It looks like your 'json' argument for $.post() function is not within the correct function scope. See the updated code below (I took the liberty of removing the excess string concatenation – I may be wrong, but it didn't appear to have utility). Proper spacing can help to catch these syntax errors.
var list='';
function mymodal (id) {
$.post('postname_.php', {post_id: id}, function (data) {
$.each(data.results, function (i, result) {
list+='<div class="modal fade" id="myModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal">×</button><h4 class="modal-title">Students who loved your post</h4></div><div class="modal-body">';
list+='<h4 class="text-danger">' + result["finame"] + ' ' + result['sename'] + '</h4>';
list+='</div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div>';
$('#insert').append(list);
});
}, 'json');
}
To see the difference, here is the original code tabbed in a more conventional manner.
var list='';
function mymodal(id){
$.post('postname_.php',{post_id:id},function(data1){
$.each(data1.result,function(){
list+='<div class="modal fade" id="myModal" role="dialog">'+'<div class="modal-dialog">'+'<div class="modal-content">'+
'<div class="modal-header">'+'<button type="button" class="close" data-dismiss="modal">×</button>'+
'<h4 class="modal-title">Students who loved your post</h4>'+' </div>'+'<div class="modal-body">';
list+='<h4 class="text-danger">'+this["finame"]+' '+this['sename']+'</h4>';
list+='</div>'+'<div class="modal-footer">'+
'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'+'</div>'+
'</div>'+'</div>'+'</div>';
$('#insert').append(list);
}),'json'
});
}

Your JavaScript code is correct (Please format the code before asking for help in online forums).
https://jsfiddle.net/s295zzmt/
Your HTML code looks in correct, probably because it was copy pasted from within JavaScript code. But since you said that alert inside mymodal function is working correctly, lets ignore it.
There are two possibilities.
The HTTP request is failing
It is returning invalid JSON
Check network tab in Firefox Developer Tools / Chrome Developer Console. Make sure that the XHR request is returning 200 OK. If so, check the HTTP response and ensure that it is valid JSON.

Related

Capture the click event of dynamic Buttons in Bootstrap Modal using jquery [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I hava Bootstrap model as below
<div class="modal fade" id="PQModel" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title " id="exampleModalLongTitle"><strong>Priority Queue Selection</strong></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body justify-content-center">
<div id="modal-text"></div>
</div>
<div class="modal-footer justify-content-center">
<button type="button" class="btn btn-danger cancel">Cancel</button>
</div>
</div>
</div>
</div>
In this modal I am writing some dynamic buttons accoridng to the JSON response from server as below.
var scrn = '';
$.each(pqueueList, function(index, val)
{
scrn += ' <div class="row justify-content-center top-buffer">';
scrn += ' <div class="col-6">';
scrn += ' <div class="btn btn-block';
if (val["fieldType"] == "EVEN"){
scrn += ' btn-primary ';
}
else{
scrn += ' btn-success ';
}
scrn += '" value="'+val["pqId"]+'"><h2>'+val["pqName"]+'</h2></div>'
scrn += ' </div>';
scrn += '</div>';
});
$('#modal-text').html(scrn);
$("#PQModel").modal('show');
}
I am driving to capture the click event on each of the button as below.
$("#PQModel #modal-text div.btn").on('click',function(){
var value = $(this).attr('value');
alert("value "+ value);
});
The modal is coming as expected and buttons are coming as expected. But the click I am not able to capture button click event.I am not sure, where am I going wrong. Please help me solve it out.
I suspect that binding of the objects for the click function is happening before you complete the generation and display of the objects. To make sure, replace your third code block with something simple like
console.log($("#PQModel #modal-text div.btn")),
and verify that at the time where this is called that objects are actually being selected
You're attaching a click event before the DOM elements exist. This means the event listener is attaching to nothing.
You would want to use event delegation to properly handle this situation. This attaches an event listener to the parent container, and whenever there is a click inside of it, it determines if the element matches the secondary selector provided (div.btn)
$("#PQModel #modal-text").on('click','div.btn', function(){
var value = $(this).attr('value');
alert("value "+ value);
});
Event Delegation JQuery Docs

Passing data to Bootstrap 4 Modal

I'm using a PHP script to read data from a database and create an image gallery based on the results using Bootstrap Cards. Now I would like to have the possibility to delete data from the gallery. I finally found a way to do this -
PHP code:
[...]
echo "<div class='col-sm-4'>";
echo "<div class='card-deck'>";
echo "<div class='card' id='id_".$uploads[$i]['id']."'>";
echo "<img class='card-img-top' src='".$imagePath.$uploads[$i]['md5']."_tn.jpg' alt='Card image cap'>";
echo "<div class='card-img-overlay'><a class='close' href='#'>×</a></div>";
echo "<div class='card-body'>";
[...]
Javascript:
$(document).ready(function(){
$('.close').click(function(){
var target = $(this).parent().parent().attr('id');
$.ajax({url:'delete.php?id=' + target.replace('id_', '')});
location.reload();
});
});
This works perfectly fine, but I would like to include a Bootstrap Modal before actually deleting the picture from the gallery.
HTML modal code:
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Delete picture</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Do you really want to delete this picture?</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="deletePic" class="btn btn-danger">Delete Picture</button>
</div>
</div>
</div>
</div>
PHP code:
[...]
echo "<div class='col-sm-4'>";
echo "<div class='card-deck'>";
echo "<div class='card' id='id_".$uploads[$i]['id']."'>";
echo "<img class='card-img-top' src='".$imagePath.$uploads[$i]['md5']."_tn.jpg' alt='Card image cap'>";
echo "<div class='card-img-overlay'><a class='close' data-toggle='modal' data-target='#deleteModal' href='#'>×</a></div>";
echo "<div class='card-body'>";
[...]
Since the modal is now an additional step between the click on the X button and the actual delete my Javascript will not work anymore. Could someone please let me know how I can hand over the picture ID to the modal and in the next step delete the picture?
Thanks!
Simply you can do this:
$('a.close').click(function(){
var target = $(this).parent().parent().attr('id');
var pictureId = target.replace('id_', '');
$("#deletePic").data('picture-id', pictureId);
$("#deleteModal").modal("show");
});
Above code, we changed something. Firstly we removed ajax request. After that, we assigned picture id to delete button in the modal. After that, we opened the #deleteModal
Now, we know #deletePic has picture's ID number.
If we want to delete picture when clicked #deletePic button, we should use this:
$("#deletePic").on("click", function() {
var pictureId = $(this).data('picture-id');
$.ajax({url:'delete.php?id=' + pictureId});
});
And you shouldn't miss that, there are two .close class.
Firstly anchor has .close class that you want to use it. Also, bootstrap's modal contains .close class. So you should work ELEMENT.CLASSNAME if there are different elements has the same class.
I hope this will work for you.

Code is getting executed even when hitting cancel button (ajax)

Okay so I have a function "deactivate" which passes in 3 parameters to it.
<a href="#myModal" onclick="deactivate('{{ $user->getRoleName() }}', '{{ $user->getFullName() }}', {{ $user->id }}); return false;" role="button" data-toggle="modal" class="btn btn-danger btn-small delete">
<i class="btn-icon-only"></i>
Deactivate User
</a>
Here is my function:
function deactivate(title, name, id) {
$('#modal-user-role').html(title);
$('#modal-user').html(name);
$('#confirm').click(function() {
$.ajax({
url: '/user/' + id + '/',
type: 'PUT',
success: function (data) {
$('#alerts').html('<p class="alert alert-success">Successfully deactivated ' + title + ': ' + name + '</p>' + $('#alerts').html());
$('#r' + id).hide();
},
error: function (jqXHR, textStatus, errorThrown) {
$('#alerts').html('<p class="alert alert-error">A problem occured while deactivating ' + title + ': ' + name + '</p>' + $('#alerts').html());
$('#r' + id).hide();
}
});
});
}
Here is my HTML that goes with the function:
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close icon-remove" data-dismiss="modal" aria-hidden="true"></button>
<h3 id="myModalLabel">Deactivate User</h3>
</div>
<div class="modal-body">
<p>Are you sure you want to deactivate user <span id="modal-user-role"></span>: <span id="modal-user"></span>?</p>
<p>This action cannot be undone.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button id="confirm" data-dismiss="modal" class="btn btn-danger">Confirm Deactivation</button>
</div>
</div>
Does anyone know why my cancel button is not working? I believe it has something to do with the onclick I am using but not quite sure how to fix it.
So, basically if I click the deactivate user button and than cancel and click another user and then cancel and then click another user and than confirm the deactivation it will delete each user from the DB.
Which I do not want.
I have the button type="button" which I thought would fix it. But it is not.
Any ideas at all would be greatly appreciated.
As I mentioned in the comments, the problem is how you are registering the click handler...
since the click handler is registered within the deactivate method, every time the method is called a new handler is added - it doesn't remove the previously added handlers...
so you can try to remove the handlers using .off()
$('#confirm').off('click.deactivate').on('click.deactivate', function () {
})
Note: When using event unbinding I prefer using name spacing

bootstrap modal not showing

We are currently stuck using bootstrap 2.3.2, and are looking to replace our current dialogs with bootstrap's modals.
I've located all the views where modals need to be instantiated and attempted 2 ways to call them without success.
With JS:
Html:
<a title='New Group' class='btn btn-fancy' id="btn-new-group" data-bind="visible: Value() == 'CanCreateNewGroup', click: corp.page.CreateGroupDialog.show">New Group<i class="fa fa-fw fa-lg fa-users"></i></a>
JS:
define([
'app-utils',
'jquery',
'bootstrap'
], function (utils) {
var CreateGroupDialog = function () {
};
CreateGroupDialog.prototype = $.extend(true, CreateGroupDialog.prototype, {
show: function (model) {
var dialog = $('#testing-bootstrap').modal({
toggle: true,
show: true,
keyboard: true
});
}
});
return CreateGroupDialog;
});
Without JS:
Html:
<a data-target="#testing-bootstrap" data-toggle="modal" class="btn btn-simple show_tooltip" title="Create Group"><i class="fa fa-fw fa-plus-circle"></i><span>Create Group</span></a>
The reason why I have to come here is that I get NO console errors, NO clue. The JS in my example is being hit, bootstrap is included and I've stepped through bootstrap code and it is loading my modal's html, but it is not coming up on the screen in EITHER way, with no console errors.
Actual modal markup (from bootstrap's example)
<div id="testing-bootstrap" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
Thanks, everyone.
I'm not totally sure how the binding is working in your example - it appears to use the Knockout data-bind attribute, but the rest is jQuery. I'm guessing that your CreateGroupDialog is not being correctly bound to the modal HTML - especially since you are using require.js. If the HTML without JS does not work either, there could be something else wrong, but I would modify your constructor code to bind to your <a> that should trigger the modal.
var CreateGroupDialog = function () {
$( 'a[title="Create Group"]' ).click( $.proxy( this.show, this ) );
};
Then instantiate it:
var modal = new CreateGroupDialog;
The suspected html in the description area of this question was part of an HTML partial which was being called in an area of the application that was not going to be visible then.
If you are using html partials then look into their visibility before doubting the bootstrap modals. That was my problem.

Pass php variable using jquery ajax to a modal

I am having a problem with my jquery ajax script. I can not get it to pass the variable to the modal. I have been messing with this all weekend and can not figure out way it does not pass the variable.
This is the link to call the modal and the id I am trying to pass
echo '<img src="./images/see.png" class="open-editexpenses" data-target="#editexpenses" data-id="' . $value['expid'] . '" >';
This is the jquery ajax script
$(document).on('click', '.open-editexpenses', function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "expenses.php",
data: {id: id},
success: function() {
$('#editexpenses').modal('show');
}
});
});
This is the modal I am opening
<div class="modal fade" id="editexpenses" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<?php
echo $id;
var_dump($_POST);
//var_dump($_GET);
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
$(x).data('id') is not the same as $(x).attr('data-id'), which is probably what you're after to read the data-id attribute of your img element.
See jQuery Data vs Attr? for more info.
I'm going to assume the 'modal' is expenses.php and also that you're using a jQuery plugin for $('#editexpenses').modal('show'); to mean anything.
From what I can see you haven't actually added the response from expenses.php into the DOM. You can do this by altering the success function in your AJAX call:
success: function(html) {
$('body').append(html);
$('#editexpenses').modal('show');
}
Here I've just added the HTML returned to the end of the page, but jQuery has plenty of other ways you can insert into the DOM: https://api.jquery.com/category/manipulation/
As an aside, be careful about assuming that the $id variable in expenses.php exists. This works when PHP's register_globals setting is on, but this is considered extremely bad practice and was deprecated in PHP 5.3.0 and actually removed in 5.4.0. Just use $_POST['id'] instead.

Categories

Resources