ajax call back not working with knockout.js - ajax

I am having problems with this save function.
the line with comment //←this does not is not working, however the line with comment //←this one works is working. Is there anything wrong with calling it in the ajax callback? How can I get it to work?
save= function(){
var self=this;
function f(index, row){
jsRow=ko.toJS(row)
if (jsRow.isChanged) {
var value= jsRow.value;
self.commitRowToUndo(row); //←this one works
$.ajax({
url: "db/"+value._id,
type: "put",
data: JSON.stringify(value),
success: function(responce_json) {
self.commitRowToUndo(row); //←this does not
…
var row= something;
}
});
}
}
$.each(self.table.rows(), f);
}
save is bound to a button.

I found it: it was because I declared row latter, row became undefined. I did not realise that defining a variable had retro-active scope. (I will define variable at top of function/scope in Javascript from now on).

Related

mootools inline Ajax call not working

I am trying to use mootools ajax requests to record clicks on outgoing links. So far here is what I'm doing.
Each link looks like follows:
<div id="1">
StackOverflow
</div>
The javascript function clickRecord(id) is defined as follows:
function clickRecord(id){
var u = "record.php";
var req = new Request({
method: 'post',
url: u,
data:{'id':id},
onComplete:function(response){
}
}).send();
}
The problem I have is this. If I add a return false; to the onclick="" declaration, everything works fine, of course the problem there is that click does not take the user to the intended page. If I do not have the return false; then it seems like the ajax call is never executed.
I thought the onclick event should execute first and then only the default action should execute. Is this not the case?
There is an even stranger scenario if you use onmousedown event instead. It seems like on Firefox, if you use the onmousedown event, once you go to the new page, you cant simply navigate back to the old page, you have to refresh the old page. Else the call is not executed. This does not happen on IE.
Don't use onclick - very 1995.
Instead attach an event to the element and use event.stop(), ie:
StackOverflow
JS:
document.getElements('a').addEvents({
click: function(event) {
event.stop();
var u = 'record.php';
var req = new Request({
method: 'post',
url: u,
data: {
'id': this.get('data-id');
},
onComplete: function(response) {}
}).send();
}
});
Btw. <div id="1"> this is not valid in HTML, an ID'd needs to start with a letter.
OK. Found an answer to one of the questions:
The inline mootools request did not execute when declared through the onclick().
It seems this was caused by the script not being synchronous. So probably it returns without actually fully committing the request, and the browser then moves to another page breaking the execution. Adding a synchronous call to the script fixes the problem:
function clickRecord(id){
var u = "record.php";
var req = new Request({
async:false,
method: 'post',
url: u,
data:{'id':id},
onComplete:function(response){
}
}).send();
}
The second problem that was mentioned on the onmousedownevent, i.e. firefox not executing the ajax call if the browser navigates back is still unsolved. However I am leaving that to be as that wasn't the main question raised.

Return false not working for jQuery live

Well this has me well and truly stumped. After searching for the last few hours I still cannot seem to work out where I am going wrong.
I am trying to append an AJAX response to a container when it gets clicked. That works fine but I don't want it to append another object when the elements from the AJAX response also gets clicked.... so:
<div id="container">
<!-- AJAX response to get inserted here, for example -->
<span id="ajaxResponse"></span>
</div>
Here is my script:
$('#container').click(function(e) {
var current_el = $(this).get(0);
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
}
});
return false;
});
So it works fine but for some reason the click event on #container also fires when I click on the AJAX response span!?
According to jQuery documentation:
To stop further handlers from
executing after one bound using
.live(), the handler must return
false. Calling .stopPropagation() will
not accomplish this.
But unless I am mistaken, I am calling false? :(
Anyone help me out on this?
UPDATED:
So the only way I can get it to work is by updating my code to this:
$('#container').live('click', function() {
var current_el = $(this).get(0);
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
}
});
});
$('#ajaxResponse').live('click', function(e) {
return false;
});
This seems a little messy though... anyone have a better solution?
Where is live part you mention in the title of the question ?
It is how the event model works.. If you click on element which does not handle the event, the event will travel up the DOM hierarchy until it finds an element that handles the click (and stops its propagation..). Otherwise you would not be able to put an image inside a <a> tag and click on it..
You can bind a canceling handler on the inner element assuming you have someway to target it..
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
// assuming the returned data from ajax are wrapped in tags
$(current_el).children().click(function(){ return false;});
}
});
I think the return false is referring to something else in this case...
you should try calling stopPropagation() - this should stop the "click" function from propagating down to the ajaxResponse span....
One option that you may want to try is switching over to using live(). Essentially, the click event you setup is calling bind(), and the solution you referenced is using live() which is a variation on bind().
For example:
$('#container').live("click", function(e) {
var current_el = $(this).get(0);
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
}
});
return false;
});
HTH

jQuery Submit Function Does Not Work (Inner Function)

I have a problem with this jQuery code. It doesn't work as expected:
$('#select_dropdown').change ( function(){
$('#form_to_submit').submit( function(event){
$.post("list.php", { name: "John", time: "2pm" },
function(data) {
alert("Data Loaded: " + data);
});
});
});
However, this works:
$('#select_dropdown').change ( function(){
$('#form_to_submit').submit();
});
I wonder why the internal function on submit doesn't work. When a user selects a value from a dropdown, the form must be submitted. The second set of codes work but if I add an inner function to submit, it doesn't.
Basically, I want to do some ajax call after the user select on the dropdown.
According to documentation ( http://api.jquery.com/submit/ ), submit() without parameters will submit your form, but if you include arguments it will bind the submit event to the form, but it wont submit it.
So, the code posted by #Chris Fulstow would be the right way of submitting the form, but as ajax is not synchronous, function will continue without waiting for the answer and then, the alert will not be shown.
You can make it synchronous, but you must use $.ajax instead of $.post, because $.post doesn't include an async option. Anyway, I'm providing a solution for your specific problem, but I'm guess there should be a better way for doing it.
$(function() {
$('#select_dropdown').change(function() {
$('#form_to_submit').submit();
});
$('#form_to_submit').submit(function(event) {
$.ajax(
url: "list.php",
data: { name: "John", time: "2pm" },
success: function(){
alert("Data Loaded: " + data);
},
async:false,
);
});
});
When you call with a callback argument submit( handler(eventObject) ) it will only attach an event handler. To trigger a form submit, call submit() with no arguments:
$(function() {
$('#select_dropdown').change(function() {
$('#form_to_submit').submit();
});
$('#form_to_submit').submit(function(event) {
$.post(
"list.php",
{ name: "John", time: "2pm" },
function(data) {
alert("Data Loaded: " + data);
}
);
});
});
The .submit call in your first example is binding a function to the submit event on the form. From the fine manual:
.submit( handler(eventObject) )
handler(eventObject) A function to execute each time the event is triggered.
You need to bind your submit handler:
$('#form_to_submit').submit(function(event){ /*...*/ })
somewhere else and call submit as in your second example.
So the problem here is that in the first case, you are binding an event handler to the element, and in the second you are triggering it. Let's look at the first case:
$('#form_to_submit').submit(function(evt){ ... });
You're essentially doing something like
document.getElementById('form_to_submit').addEventListener(
'submit',
function(evt){...},
false
);
The second case is you instructing the form to submit, which is why it works. If you wanted the handler to work with your custom code you would need both of them. First bind your event handler, then, onchange instruct the form to submit.
$('#form_to_submit').submit(function(evt){ ... });
$('#select_dropdown').change(function(){
$('#form_to_submit').submit();
});
Keep in mind though, that as other people have already said, if your action is set to go to another location, you may not see the results of the binded event handler so instead of explicitly stating a url for your action, you will have to use something to prevent the form from going anywhere like action="javascript:void(0)" or the like.
To make your code a bit cleaner, you could pull the ajax out of an unnamed function and put it in a named one and call it on change so it looks like this.
var fetchList = function(){
$.ajax(...);
};
$('#form_to_submit').submit(fetchList);
$('#select_dropdown').change(fetchList);
I haven't run this code, please excuse any silly syntax mistakes I've made. But this should get you some of the way there. Good luck! :)

Jquery AJAX: How to Change button value on "success"?

I have multiple buttons on one page. Upon click, I track the button id, send the button value to backend php code that returns me updated value by changing the database. I am able to get back everything i need except this: Setting the button value on success!! This is the code i'm using:
$(document).ready(function(){
$("input[type='button']").click(function(){
var selected = $(this).attr("id");
var val = prompt("Enter new value",0);
$.ajax({
url:'updateCostItems.php',
data:{toupdate:selected, updatewith:val},
type:'GET',
dataType:'json',
success:function(json){
$(this).val(json.update);
},
error:function(xhr, status){
alert("Problem");
},
complete:function(xhr, status){
}
});
});
});
I think this is not correct, because the callback is run in the global scope.
Untested, but try just before $.ajax to write var $this = $(this) and then in your callback use $this.val(json.update)
Edit: Updated code snippet to ensure local $this by declaring with var. Other posts suggest using var button = $(this) which is probably better in bigger projects where keeping track of the variables is more challenging - but all the answers are the same really.
The problem is that 'this', inside the ajax request, points to the xhr object, not the button. You should store the reference to the button prior to do the call, like var button = $(this); and later updating it button.val(json.update);
Store the button in a local variable in the outer loop, then refer to that variable in the inner scope of the success handler:
$(document).ready(function(){
$("input[type='button']").click(function(){
var $btn = $(this)
var selected = $btn.attr("id");
var val = prompt("Enter new value",0);
$.ajax({
url:'updateCostItems.php',
data:{toupdate:selected, updatewith:val},
type:'GET',
dataType:'json',
success:function(json){
$btn.val(json.update);
},
error:function(xhr, status){
alert("Problem");
},
});
});
});
$(this) will not refer to the button at the time the success function is called. You will need to pass the button (or the button's id) along as a parameter to your callback. Storing a single global variable is not sufficient since you could potentially click on a 2nd button before the first ajax call returns.

JQM (jQueryMobile) problem with AJAX content listview('refresh') not working

This is a mock of what I'm doing:
function loadPage(pn) {
$('#'+pn).live('pagecreate',function(event, ui){
$('#'+pn+'-submit').click( function() {
$.mobile.changePage({
url: 'page.php?parm=value',
type: 'post',
data: $('form#'+pn+'_form')
},'slide',false,false);
loadAjaxPages(pn);
});
});
function loadAjaxPages(page) {
// this returns the page I want, all is working
$.ajax({
url: 'page.php?parm=value',
type: 'POST',
error : function (){ document.title='error'; },
success: function (data) {
$('#display_'+page+'_page').html(data); // removed .page(), causing page to transition, but if I use .page() I can see the desired listview
}
});
}
in the ajax call return if I add the .page() (which worked in the past but I had it out side of the page function, changing the logic on how I load pages to save on loading times), make the page transition to the next page but I can see the listview is styled the way I want:
$('#display_'+page+'_page').html(data).page();
Removing .page() fixes the transition error but now the page does not style. I have tried listview('refresh') and even listview('refresh',true) but no luck.
Any thoughts on how I can get the listview to refresh?
Solution:
$.ajax({
url: 'page.php?parm=value',
type: 'POST',
error : function (){ document.title='error'; },
success: function (data) {
$('#display_'+page+'_page').html(data);
$("div#name ul").listview(); // add div wrapper w/ name attr to use the refresh
}
});
Be sure to call .listview on the ul element
If it didn't style earlier, you just call .listview(), bot the refresh function. If your firebug setup is correct, you should have seen an error message telling you that.
I didn't have time to get down to creating some code before you posted your fix, but here's a little recommendation from me:
if(data !== null){ $('#display_'+page+'_page').html(data).find("ul").listview() }
This is a bit nicer than a new global selector. Also - you don't need the div and you can provide a detailed selector if you have multiple ULs.
caution: the above code requires data !== null. If it's null - it will throw an error.
If you add items to a listview, you'll need to call the refresh() method on it to update the styles and create any nested lists that are added. For example:
$('#mylist').listview('refresh');
Note that the refresh() method only affects new nodes appended to a list. This is done for performance reasons. Any list items already enhanced will be ignored by the refresh process. This means that if you change the contents or attributes on an already enhanced list item, these won't be reflected. If you want a list item to be updated, replace it with fresh markup before calling refresh.
more info here.

Resources