Trying to get html element value to a variable with Jquery - javascript

I have a confirm modal that will delete a user (from XML file), it shows the user name in the confirmation modal, but when i'm trying to get that value to a variable to pass it to php via AJAX, I can't get the value of the html element (span), so I can't pass it to php... when I alert it, its clear.
This is the Dialog HTML
<div id="myDialog">
<h3>¿Está seguro de eliminar al usuario <b><span id="nombre_usuario_borrar"></span></b> ?</h3>
</div>
This is the Dialog.js
$(function() {
$("#myDialog").dialog({
autoOpen: false,
modal: true,
title: "Eliminar",
buttons: {
'Eliminar': function() {
var usuario_borrar = $('#nombre_usuario_borrar').val();
alert(usuario_borrar);// It alerts nothing
$.ajax({
type: "POST",
url: 'eliminar2.php',
data: {
"usuario_borrar": usuario_borrar
},
error: function(result) {
alert("Error!!!");
}
});
$(this).dialog('close');
},
'Cancelar': function() {
$(this).dialog('close');
}
}
});
});
function Editar(nombre_archivo) {
alert(nombre_archivo);
}
function Eliminar(nombre_archivo) { // this works.
$("#nombre_usuario_borrar").html(nombre_archivo);
$("#myDialog").dialog("open");
}
function asignarUsuarioBorrar(nombre_archivo){
var obj = $("#usuario_borrar");
obj.attr("value",nombre_archivo);
}
As you can see, it shows 'Benigno' (span) value right, but when I click 'Eliminar', it alerts nothing.

$('#nombre_usuario_borrar').val()
This only works for HTML elements with a "value" option. The <span> tag does not have this option.
Try this instead to get the text within the <span>:
$('#nombre_usuario_borrar').text()

Related

Modal dialog's onshow not called after postback

I have a Bootstrap modal dialog that I am using to populate with data when user clicks on "Edit" in a jQuery data table. There is a Cancel and Submit button on this modal.
When I open the modal and click Cancel and then select another table row and click "Edit", everything is fine; data gets populated correctly each time "Edit" is clicked. However, if I do a postback by clicking "Submit" on the modal and then click "Edit" again, modal opens and no data is there.
I am using modal's on('show.bs.modal', ...) to populate it and it never gets hit after a postback is done.
// This is called when "Edit" in data table row is clicked
function showEdit(var1, var2) {debugger
$('#hfVar1').val(var1);
$('#hfVar2').val(var2);
showEditModal();
}
function showEditModal() {debugger
$("#spnEditHeader").text("Edit Something");
$('#editModal').modal('show');
}
$(document).ready(function () {
// This populates the jQuery data table
showTable(somthing, anotherThing);
// This is executed as long there is no postback;
// once a postback is perfoemd this is not hit, modal not populated
$('#editModal').modal({
keyboard: true,
backdrop: "static",
show: false
}).on('show.bs.modal', function (e) {debugger
var var1= $('#hfVar1').val();
var var2= $('#hfVar2').val();
//make ajax call to populate items
populateMPOOEdit(var1, var2);
});
....
});
//This is the button in modal that causes postback
<div class="modal-footer">
<div id="divEditButtons" style="text-align: center;">
<button id="btnCancel" class="btn btn-info2" data-dismiss="modal" aria-hidden="true" aria-label="Cancel">Cancel</button>
<button id="btnSubmit" class="btn btn-primary" aria-hidden="true" aria-label="Update">Update</button>
</div>
</div>
// "Submit" button's click handler
$(document).on("click", "#btnSubmit", function (event) {
// Validate data (client side validation)
var isValid = validateUpdate();
// Also need a server side validation checking for duplicate name, using ajax to do this
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: '<%= ResolveUrl("services/mpoo.asmx/NameExists") %>',
cache: false,
data: JSON.stringify({ "Name": name }),
}).done(function (data) {
var result = data.d;
if (result != '') {
nameExists = JSON.parse(data.d);
if (nameExists == "true") {
$("#lblErrName").text("Duplicate Name");
$("#lblEditErrName").show();
isValid = false;
}
if (isValid) {
__doPostBack('btnSubmit', JSON.stringify({
action: "SaveUpdate", Var1: var1, ..., Varn: varn
}));
$('#editModal').modal('hide');
}
}
});
return false; // to prevent modal from closing if there are errors on page
});
Create a function like this:
//basically everything you had in your document.ready function
function myJsFunc() {
// This populates the jQuery data table
showTable(somthing, anotherThing);
// This is executed as long there is no postback;
// once a postback is perfoemd this is not hit, modal not populated
$('#editModal').modal({
keyboard: true,
backdrop: "static",
show: false
}).on('show.bs.modal', function (e) {debugger
var var1= $('#hfVar1').val();
var var2= $('#hfVar2').val();
//make ajax call to populate items
populateMPOOEdit(var1, var2);
});
....
}
Then in your Page_Load event handler in your codebehind, try putting this:
Page.ClientScript.RegisterStartupScript(this.GetType(), "some random name for your script", "myJsFunc();", true);

Do AJAX check before confirming delete

I have a Telerik grid. For the uninitiated, it just means I've got a table on a page.
On this Telerik grid, I've got a column for deleting a record. I originally had it so that a user could click, and then it would fire a javascript confirm dialog. If the user hit ok, it would call go the Delete link; if not then it would cancel without refreshing the page. That original code is below.
columns.Template(
#<text><a href='#Url.Content("~/HazardControl/Delete/" + #item.Id)'
style="cursor:pointer;" onclick = "return confirm('Are you sure you want to delete this record?');">
<img src="~/Content/Images/DeleteItem.gif" alt="Delete" />
</a></text>
).Width(50).HtmlAttributes(new { style = "text-align:center" });
Now, the requirements I have now is that they want to check if a record is eligible for deletion before doing that confirm delete, so now my code looks like this:
columns.Template(
#<text><a href='#Url.Content("~/Training/Delete/" + #item.Id)'
style="cursor:pointer;" onclick="deleteConfirmation(#item.Id)">
<img src="~/Content/Images/DeleteItem.gif" alt="Delete" />
</a></text>
).Width(50).HtmlAttributes(new { style = "text-align:center" });
<script type="text/javascript" >
function deleteConfirmation(recordId) {
$.ajax({
url: '#Url.Action("ValidateDelete", "Training")',
type: 'POST',
data: { id: recordId },
success: function (result) {
var deleteRecord = false;
if (result) {
var userConfirm = confirm('Are you sure you want to delete this record?')
if (userConfirm) {
deleteRecord = true;
}
}
else {
alert('Delete no allowed, the record is in use!');
}
return deleteRecord;
}
});
return false;
}
</script>
I thought I'd be able to accomplish this by using an AJAX call before doing the confirm, BUT what actually happens is that the validation part occurs correctly, then the link activates anyway despite returning false or true. I though that when you used the anchor tag and used the onclick method and returned false, then the nothing would happen, but that does not seem to be the case when using AJAX. What am I doing wrong here? Has this been done before? Is it possible here?
The AJAX call occurs asynchronously so returning true or false will have no effect on the event bubbling.
In my example below if it returns true it will trigger a click of the original element that will this time return true and allow the link click to go through. The variable deleteRecord might have to be renamed if you have multiple links and the #linkid should be for the element that was originally clicked. If you assigned an id to the link of deleteItem-#item.Id you could pick this up in the JavaScript.
var deleteRecord = false;
function deleteConfirmation(recordId) {
if(!deleteRecord)
{
$.ajax({
url: '#Url.Action("ValidateDelete", "Training")',
type: 'POST',
data: { id: recordId },
success: function (result) {
if (result) {
var userConfirm = confirm('Are you sure you want to delete this record?')
if (userConfirm) {
deleteRecord = true;
$("#linkid").click();
}
}
else {
alert('Delete not allowed, the record is in use!');
}
}
});
}
return deleteRecord;
}
Here's how I did it: Removed the link and gave the OnClick event to the image. Javascript to do the checks and calls to Delete link.
columns.Template(
#<text>
<img src="~/Content/Images/DeleteItem.gif" alt="Delete" style="cursor:pointer;" onclick="deleteConfirmation(#item.Id)" />
</text>
).Width(50).HtmlAttributes(new { style = "text-align:center" });
<script type="text/javascript">
function deleteConfirmation(recordId) {
$.ajax({
url: '#Url.Action("ValidateDelete")',
type: 'GET',
data: { id: recordId },
success: function (result) {
if (result) {
var userConfirm = confirm('Are you sure you want to delete this record?')
if (userConfirm) {
window.location.href = '#HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()/Delete/' + recordId;
}
}
else {
alert('Delete not allowed, the record is in use!');
}
}
});
}
</script>

Can't place jQuery inside loaded document.ready: not called

I have a page called: contact_profile.php that uses jquery .load to load info into a div.
$('#json_comments').load('json_comments_content.php');
json_comments_content.php looks like this:
<?php
require_once 'core/init.php';
$user = new User();
if(!$user->isLoggedIn()) {
Redirect::to('login.php');
}
$contact = new Contact();
//check to make sure there is current contact selected, otherwise redirect to index. This helps when you deselect a contact from menu bar while on contact page.
if (!($contact->isSelected())) {
Redirect::to('index.php');
}
?>
<div class="items general-item-list">
<div class="item">
<div class="item-head">
<div class="item-details">
<img class="item-pic" data-field="pic_url" src="">
<span class="item-label" data-field="datetime" data-value="" data-pk=""></span>
</div>
</div>
<div class="item-body"></div>
</div>
</div>
Load More...
<script type="text/javascript">
$(document).ready(function() {
$('.comments_data').loadmore({
source: 'json_comments.php',
step: 15,
userid: '<?php echo $user->data()->id; ?>'
});
//on load, disabled the comments editable info on page load so it looks better.
$('#json_comments a').attr("data-disabled", "true");
$.fn.editable.defaults.mode = 'inline';
});
</script>
I am using a custom plugin called 'loadmore' that will load more data on my page from a mysql database. It works fine.
However, I have to use the following code for the data that is supplied by the loadmore plugin:
$('.edit_me').editable({
emptytext: ".....",
url: "ajax_xeditable_update.php?table=comments",
});
That code is using the X-Editable plugin for jQuery: http://vitalets.github.io/x-editable/
If I place the code in the loaded content's page inside the document.ready function, it never gets called!
Here's what my loadmore plugin looks like. If the code for X-Editable is placed there it will work properly. It would be better to have the code placed in the loaded page and NOT in the plugin - that way the plugin can stay generic.
Hope I was clear on my problem.
Here's the loadmore custom plugin:
(function ($) {
"use strict";
$.fn.loadmore = function(options) {
var self = this,
settings = $.extend({
source: '',
step: 2,
userid: '',
}, options),
stepped = 1,
item = self.find('.item'),
items = self.find('.items'),
finished = function() {
// hide the load more button
self.find('.items-load').remove();
},
append = function(value) {
var name, part, id, userid, canedit;
item.remove();
for(name in value) {
if(value.hasOwnProperty(name)) {
id = value['id'];
userid = value['user_id'];
part = item.find('*[data-field="' + name +'"]');
//find anything that has a can edit class and then add the general editable class for x-editable to work.
canedit = item.find(".can_possibly_edit");
if(part.length){
part.text(value[name]);
//add the value to an image if there is one for x-editable to work.
if($(part).is("img")) {
$(part).attr("src", value[name]);
}
//only make the current user's stuff editable
if(settings.userid == userid ) {
//add edit_me to the classes so x=editable can work. but then remove edit_me and the editable class so x-editable doesn't work for data that doesn't belong to the user(found in the else clause below).
$(canedit).addClass('edit_me editable editable-pre-wrapped editable-click editable-disabled');
$(canedit).attr('data-value', value[name]);
//there must be an id field in the json so it can be assigned to the primary key for x-editable to work.
$(canedit).attr('data-pk', id);
} else {
//remove hyperlink stuff and just leave the text to view only.
$(canedit).removeClass('edit_me editable');
}
}
}
}
item.clone().appendTo(items);
//this works if it's placed here only!
$('.edit_me').editable({
emptytext: ".....",
url: "ajax_xeditable_update.php?table=comments",
});
},
load = function(start, count) {
$.ajax({
url: settings.source,
type: 'get',
dataType: 'json',
data: {start: start, count: count},
success: function(data) {
var items = data.items;
if(items.length) {
$(items).each(function(index, value) {
append(value);
});
stepped = stepped + count;
}
if(data.last === true) {
finished();
}
}
});
};
if(settings.source.length) {
self.find('.items-load').on('click', function(){
load(stepped, settings.step);
return false;
});
load(1, settings.step);
} else {
console.log('Source required for loadmore.');
}
};
}(jQuery))
It's almost like on the loaded page: json_comments_content.php I need to run the loadmore plugin on document.ready and THEN once the loadmore has been completed, return back to the page and run:
$('.edit_me').editable({
emptytext: ".....",
url: "ajax_xeditable_update.php?table=comments",
});
Not sure if it matters, but the loadmore script is included on my main page from: 'js/loadmore.js'. It's in a subdirectory.

Bootstrap popover repeats an action/ event twice?

Why Bootstrap's popover repeats an action twice? For instance, I want to submit a form inside the popover's data-content via ajax. It repeats all the form data twice and the posts form twice.
Any idea what I can do about it?
jquery + bootstrap,
$('.bootstrap-popover-method').popover({
placement: 'bottom',
container: 'body',
html:true,
content: function () {
var p = $(this);
var data = $('#popover-content').html();
$('#popover-content').remove();
p.attr("data-content", data);
p.popover('show');
}
});
$('.bootstrap-popover-method').on('shown.bs.popover', function () {
// do something…
console.log(this); // I get twice of the button element <button class="btn btn-default bootstrap-popover-method"...>
console.log($(".btn-submit").length); // I get twice of '1'.
$(".link").click(function(){
console.log($(this).attr("href")); // I get once of 'test.html'.
return false;
});
$(".btn-submit").click(function(){
console.log($(this).closest("form").attr("action")); // I get twice of '1.php'
var form = $(this).closest("form");
console.log(form.serialize()); // I get twice of 'username=hello+world!'
$.ajax({ // it posts twice to 'POST https://localhost/test/2014/css/bootstrap/1.php'
type: "POST",
url: form.attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data){
//alert(data); // show response from the php script.
}
});
return false;
});
});
bootsrap + html,
<button type="button" class="btn btn-default bootstrap-popover-method" data-title="body" data-container="body" data-toggle="popover" data-placement="bottom">
Popover on bottom
</button>
<div id="popover-content">
hello
<form action="1.php" class="myform">
<input type="text" name="username" value="hello world!"/>
<input type="submit" value="submit" class="btn-submit"/>
</form>
</div>
This happens because popover.content checks if the tooltip is empty or not.
A simple fix would be to add a title attribute to popover.
$('.bootstrap-popover-method').popover({
placement: 'bottom',
container: 'body',
html:true,
title: "New Title",
content: function () {
var p = $(this);
var data = $('#popover-content').html();
$('#popover-content').remove();
p.attr("data-content", data);
p.popover('show');
}
});
https://github.com/twbs/bootstrap/issues/12563#issuecomment-56813015
This might be an old post, but i'm gonna leave here my work around.
I'm using bootstrap 3.3.5.
So the buggy behavior is that on every execution of "popover('show')", Bootstrap calls the rendering function twice, and only the second call is the one that actually renders the popup.
My fix is to return a short html string for the first call, and for the second call i let run the whole rendering function:
jQuery('.bootstrap-popover-method').popover({
html: true,
trigger: 'manual',
content: function(){//This is our rendering function for the popup's content
var __G_bs_popover_shown= jQuery.data(jQuery('body')[0], '__G_bs_popover_shown');
//Create a global variable, attached to the body element, to keep track of the repeating calls.
__G_bs_popover_shown= (typeof __G_bs_popover_shown == 'undefined') ? 1 : (__G_bs_popover_shown + 1) % 2;
//Update the global var
jQuery.data(jQuery('body')[0], '__G_bs_popover_shown', __G_bs_popover_shown);
//return a short string on every first call (this will not be rendered, anyway)
if(__G_bs_popover_shown == 1) return '<div>BLANK</div>';//==>this should not be an empty string!
//PLACE YOUR CODE HERE, E.G. AJAX CALLS, ETC..
//DON'T FORGET TO RETURN THE HTML FOR THE POPUP'S CONTENT!
}
});
I think you need to prevent the default event of the submit button
$(".btn-submit").click(function(e){
e.preventDefault();
console.log($(this).closest("form").attr("action")); // I get twice of '1.php'
var form = $(this).closest("form");
console.log(form.serialize()); // I get twice of 'username=hello+world!'
$.ajax({ // it posts twice to 'POST https://localhost/test/2014/css/bootstrap/1.php'
type: "POST",
url: form.attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data){
//alert(data); // show response from the php script.
}
});
return false;
});
$('.bootstrap-popover-method').off('shown.bs.popover')
.on('shown.bs.popover', function (e) {
e.preventDefault();
}
// unbind your submit button click
$(".btn-submit").off('click').on('click',function(){
console.log($(this).closest("form").attr("action")); // I get twice of '1.php'
var form = $(this).closest("form");
console.log(form.serialize()); // I get twice of 'username=hello+world!'
$.ajax({ // it posts twice to 'POST https://localhost/test/2014/css/bootstrap/1.php'
type: "POST",
url: form.attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data){
//alert(data); // show response from the php script.
}
});
return false;
});

Passing javascript variable to php without refreshing the page

I have a 5x5 grid of div boxes (25 of them) and I am using jQuery UI to register when I drop a item in it. It will receive the title of the box it was dropped in and the name of the item, that part works.
I want to pass the title and name to PHP without refreshing the page (because then the items will reset). I get a "success!" but it seems like it doesn't pass the data.
index.php
<script>
$(function() {
$( "li img" ).draggable({
snap: ".grid",
start: function (event, ui ) {
item = $(this).attr('title');
}
});
$( "li .grid" ).droppable({
drop: function( event, ui ) {
box = $(this).attr('title');
$.ajax({
type: "POST",
url: 'index.php',
data: { box : 'box' },
success: function(data){
alert("success!");
}
});
}
});
});
</script>
sessions.php
<?php
session_start();
if(isset($_POST['box']))
{
// store session data
$_SESSION['box'] = $_POST['box'];
}
//retrieve session data
echo $_SESSION[box];
?>
How do I pass the title and name to PHP without refreshing the page?
Try to change the url and your data from this:
url: 'index.php',
data: { box : 'box' }
to this:
url: 'sessions.php',
data: { box : box }
Given that you're doing this...
box = $(this).attr('title');
I assume you want to pass that variable to the server. However, you're just passing the literal string "box", not the variable box.
In your code, you've written this...
data: { box : 'box' },
which needs to be this, to pass the value in box:
data: { box : box },
As an aside, you've created a global variable box. Instead of box = $(this).attr('title');, you should use var box = $(this).attr('title'); to create a variable local to the function.

Categories

Resources