Here's the situation: I'm writing a simple AJAX application that performs CRUD functions. When the user double clicks on a particular element, the element changes into a text box so that they can edit inline. When the text box loses focus (code for which is below), the value of the textbox gets POSTed to a PHP script that updates the database.
All is groovy except for one thing. When I create a new record, which gets popped onto the top of the list with AJAX, I can't edit that record without refreshing the page. I mean, the edit looks like it's been committed, but when you refresh, it reverts back to the original. After refreshing, there are no issues.
To boil it down: When I try to run the following code on newly created rows in my table (both in the database and on the page), the edit appears to be made on the page, but never makes it to the database.
//Make changes on FOCUSOUT
$('#editable').live('focusout', function(){
var parentListItem = $(this).parents('li');
var theText = $(this).val();
var parentListItemID = parentListItem.parents('ul').attr('id');
$(this).remove();
parentListItem.html(theText);
parentListItem.removeClass('beingEdited');
$.post("databasefuncs.php?func=edit", { postedMessage: parentListItemID, fullTextContent: theText },
function(result){
if(result == 1) {
parentListItem.parents('ul').animate({ backgroundColor: 'blue' }, 500).animate({ backgroundColor: '#eeeeee' }, 500);
} else {
alert(result);
}
});
});
I suppose you are not binding the event to the new DOM Element loaded via AJAX.
Your problem is that the post executes but the function you target (func=edit) never fires, the params you are sending after the question mark are never read by your php, you are sending a post request and wanting it to behave like a get by attaching parameters to the URL, change your request to:
$.ajax({
type: "POST",
url: "databasefuncs.php",
data: {func: "edit", postedMessage: parentListItemID, fullTextContent: theText},
success: function(data, textStatus, jqXHR) {
if(textStatus === "success") {
parentListItem.parents('ul').animate({ backgroundColor: 'blue' }, 500).animate({ backgroundColor: '#eeeeee' }, 500);
}
else {
alert(textStatus);
}
}
});
Now in your PHP you have $_POST["func"] = "edit";
Hope this is clear and it helps. Cheers.
Related
Okay, so this little bit of code either posts and then updates #arrival, or it removes it and replaces it with standard text. One click posts, one click resets. The problem I'm having, and cannot figure out, is that the code as is requires two clicks to do the initial posting, and then one click to remove and one click to post again ad infinitum. But it first requires two clicks to get to working.
Any help would be appreciated.
$(document).ready(function(){
$("#change").click(function(e) {
e.preventDefault();
var data = {};
$.each($('input[name^="u\\["]').serializeArray(), function() {
var vv = this.name.replace(/u/, '' ).replace(/(\[[]\])$/,'');
data[vv] = this.value;
});
var clicks = $(this).data('clicks');
if (clicks) {
// odd clicks
$.ajax({
type : "POST",
cache : false,
url : "napad.php?n=<?=$_GET['n']?>&o=<?=$_GET['o']?>&arrival",
data : {'X': data},
success: function(data) {
$("#arrival").html(data);
}
});
} else {
// even clicks
$('#arrival').contents().remove();
$('#arrival').append('Arrival Time: Normal');
}
$(this).data("clicks", !clicks);
});
});
If you saying you doesnt want it firing 2 times but you want it trigger the event one time clicking.
try to add this on you jquery function.
$("#change").unbind("click").click(function() {
// Your code
});
Let me know if it works. Thanks. :)
So I have a jquery click function assigned to an on/off toggle. Very simple script:
$('.on-off').on('click', function(e) {
e.preventDefault();
var $this = $(this);
$this.find('.slider').toggleClass('active');
});
We have two versions of this toggle. One toggles instantly when clicked and then we submit the value when clicking next(aka submit).
Our other one calls a jquery ajax function that toggles on success and upon success if it is a specific message code that is defined on the backend.
jQuery.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: {'requestType': requestType},
success: function(message) {
if(message.STATUS=='2000'){
if(currentButtonClicked=='dashboardChargingButton'){
if($('#dashboardChargingButton').html()==startCharge)
$('#dashboardChargingButton').html(stopCharge);
else
$('#dashboardChargingButton').html(startCharge);
}
if(currentButtonClicked=='invokeChargingButton'){
$( "#invokeChargingButton .slider" ).toggleClass( 'active');
}
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + " - " + xhr.statusText);
}
});
}
As you can see I have to toggle the class again using the same code but with direct targeting.
The on off toggles of this type have an onclick inside the actual html calling the function that handles this ajax.
My goal is to have my first set of code the one that targets the element and toggles the class to do all of this, but dynamically to where we don't have to call a function everytime.
Conceptually what I thought is:
$('.on-off').on('click', function(e) {
e.preventDefault();
var $this = $(this);
if (!$this.attr('onclick')) {
$this.find('.slider').toggleClass('active');
} else {
var clickFunction = $this.attr('onclick');
call the clickFunction
if (clickfunction = true) {
$this.find('.slider').toggleClass('active');
}
}
});
What this would do is grab the onclick, but not call it until I specify. And inside the ajax request instead of toggling I would just return true.
This might not be the best method. I am just trying to ecapsulate everything to limit the amount of code as well as make all the dom changes for those elements in one spot for any potential defects.
Here is a link to a basic fiddle of the on/off toggle.
Fiddle
I hope I explained everything in good enough detail.
On my page I want the user to be able to mouseover a td element, have the page make an Ajax call to the server, and then append a title attribute to the td to serve as a tooltip for the remainder of the time the user is on the page.
The information the page needs to retrieve is very basic so there's nothing too complicated about this... however I cannot get the code to append the data I receive from the Ajax call onto the td element.
Jquery/Ajax
$('.ChannelCodeDesc').mouseover(function () {
//Only append if we don't have a title
if (!$(this).attr('title')) {
//Let me know when we're about to make Ajax call
console.log('ajax');
$.ajax({
type: 'GET',
url: '#Url.Action("GetDesc", "ZipCodeTerritory")',
data: { channel: $.trim($(this).text()) },
success: function (data) {
//Append to td
$(this).attr('title', data);
//Display what we got back
console.log(data);
}
});
}
//What does the title look like when we're done?
console.log($(this).attr('title'));
});
Unfortunately I can see, in the console, the 'ajax' entry, followed by the exact value I'm expecting for the data object, but undefined appears as the value for the td title attribute from the final console.log statement (end of the mouseover).
HTML/Razor
<td class="ChannelCodeDesc">
#Html.DisplayFor(model => model.displayForPaging[i].ChannelCode)
#Html.HiddenFor(model => model.displayForPaging[i].ChannelCode)
</td>
Ajax Controller Method
public JsonResult GetDesc(string channel)
{
var description = (from c in db.Channel
where c.ChannelCode.Equals(channel)
select c.ChannelLongDescription).FirstOrDefault();
return Json(description, JsonRequestBehavior.AllowGet);
}
The problem is that the this object in the success function is not the td element. By default the context of the jquery ajax callbacks is set as an object representing the ajax options. However you can change that using the context option:
$('.ChannelCodeDesc').mouseover(function () {
//Only append if we don't have a title
if (!$(this).attr('title')) {
//Let me know when we're about to make Ajax call
console.log('ajax');
$.ajax({
type: 'GET',
url: '#Url.Action("GetDesc", "ZipCodeTerritory")',
data: { channel: $.trim($(this).text()) },
context: this, //make sure "this" inside the success callback is the td element
success: function (data) {
//Append to td
$(this).attr('title', data);
//Display what we got back
console.log(data);
}
});
}
//What does the title look like when we're done?
console.log($(this).attr('title')); });
I am assuming that the data returned by Ajax is valid....
the $(this) within success does not refer to the td anymore.
do this outside the ajax call:
var me = $(this);
Then in your success code do this:
me.attr('title', data);
The final console.log statement shows undefined because it occurs before the AJAX request is complete (because AJAX requests are Asynchronous).
Also, a td can't have a title attribute, might need to look at a different option:
how to apply style to 'title' attribute of 'td' tag
And others have stated, can't use $this inside the ajax success function like that.
In my web app, on one of the forms, I have a button(s) that users can click to look up names from the corporate directory. Once they have found the name, they click on the results and the name and other directory data is populated onto the form. At least, that is how I would like it to work.
My question is how to properly use a callback function so that my data from the look up is brought back to the form where I can parse it out to the correct fields.
From the form page I have the following click function:
$(".lookupNameBTN").button({
icons: {primary:"ui-icon-gear"}}) //button
.on("click",function(event){
var btn = $(this).attr("data");
mainApp.lookup(function(obj){
if(btn == "request"){
$("input[name=requestName]").val(obj.cil);
}; //request
if(btn == "client"){
$("input[name=clientName]").val(obj.cil);
}; //client
}); //lookup
}); //click
The mainApp.lookup() opens the dialog box and loads the server files.
mainApp.lookup = function(callback){
if($("#lookupDialog").length == 0){
$("body").append("<div id=\"lookupDialog\" class=\"dialogDivs\" />");
}; //div exists
$("#lookupDialog").load("/RAMP/cfm/common/lookup.cfm",function(r,s,x){
if(s == "success"){
mainApp.lookupDialog = $("#lookupDialog").dialog({
title: "Corporate Directory",
modal: true,
width:600,
height:450,
position: {my:"center center", at:"center center", of: "#app"},
close: function(){
$("#lookupDialog").dialog("destroy").remove();
} //close
}); //dialog
}else{ alert("Error in Loading");
} //success
}); //load
}; //mainApp.lookup
Finally, on the lookup popup, I have the following when the user clicks on the table row with the results:
$("#lookupResultsTbl tr").on("click",function(){
var rslt= $(this).attr("data");
// magic goes here to return value
}); //click
Once I have the value, I'm unclear how to get it back to the callback function?
I really appreciate the assistance.
Thanks,
Gary
UPDATE: I added the Coldfusion tag because using CF9 for my server side. Since this isn't specific to server side, I'll remove that tag.
My question is around continuation. One the form page, I am calling mainApp.lookup. I would like to provide a callback in that function that returns the data from the directory lookup.
The load function completes and returns the html for the dialog box. The user must interact with that dialog by searching for a name and getting the returned results.
I am looking for a way to return the data in the tr click event in the dialog box back to the mainApp.lookup function and then to the callback in the original statement in my form.
You should be able to safely invoke your callback function in the if(s == "success") code block;
mainApp.lookup = function(callback){
if($("#lookupDialog").length == 0){
$("body").append("<div id=\"lookupDialog\" class=\"dialogDivs\" />");
}; //div exists
$("#lookupDialog").load("/RAMP/cfm/common/lookup.cfm",function(r,s,x){
if(s == "success"){
callback() // here
mainApp.lookupDialog = $("#lookupDialog").dialog({
title: "Corporate Directory",
modal: true,
width:600,
height:450,
position: {my:"center center", at:"center center", of: "#app"},
close: function(){
$("#lookupDialog").dialog("destroy").remove();
} //close
}); //dialog
}else{ alert("Error in Loading");
} //success
}); //load
}; //mainApp.lookup
.. which is itself in the standard jQuery .load() callback function anyway .. so I hope I've understood your question properly!
I am New to AJAX and have already asked a few question son this matter, but i have another, I use an AJAX call to auto save a value from a drop down list to database, this works great, however every time i change a value (Their are multiple drop downs with several values each can hold) I want the div to update to reflect the change in value. The AJAX I have is as follows:
<script>
$(document).ready(function(){
$('select').on('change',function () {
var statusVal = $(this).val();
var job_id = $(this).prop('id');
$.ajax({
type: "POST",
url: "saveStatus.php",
data: { statusType : statusVal, jobID: job_id },
success: function(data) {
$('#div1').load('jobs.php #div1', function() {});
}
})
});
});
</script>
So when I change a value in one drop down box (In div1) it refreshs the value, but if i was to change another value in the same or different drop down it no longer refreshs the div or saves the value to my DB, without the reload bit in my AJAX i can change the value in multple fields and it saves, but with the reload part it only happens once
-----EDIT-----
Ok further questioning, I have used
$('#div1').on( 'change', 'select', function( ) {
var statusVal = $(this).val();
var job_id = $(this).prop('id');
$.ajax({
type: "POST",
url: "saveStatus.php",
data: { statusType : statusVal, jobID: job_id },
success: function(data) {
$('#div1').load('jobs.php #div1', function() {});
}
})
});
});
and that works great even for multiple select changes. However what if I have a few selects in a few divs, EG div1, div2 and div3. How can I adapt this code to be able to refresh all divs on a change in any of the divs, or is a case of just having the code 3 times adapted for each div.
-----EDIT-----
Thankyou all, I am able to do this with
$('#div1, #div2').on( 'change', 'select', function( ) { //stuff
Ian
Your listener is bound to the select element, which I'm betting is being blown away and relaced with the load(). Check out event delegation. jQuery makes it easy. Try binding the listener on '#div1'
$('#div1').on( 'change', 'select', function( e ) { //stuff
It should then apply to the refreshed content as well.