How to get ajax request into a variable in sencha touch? - ajax

What I am trying to do is is get the information I have in my ajax request as the badgetext number
Here is where I am trying to do it. This seems simple, but I cant figure it out.
Ext.Ajax.request({
url: '../lib/messages.php',
success: function(response, opts) {
var badge_number = Ext.decode(response.responseText);
console.dir(badge_number);
},
failure: function(response, opts) {
console.log('server-side failure with status code');
}
});
var buttonsGroup1 = [{
text: 'Messages',
//badge_number variable from ajax request would go here. badgeText: '2',
handler: tapHandler
}];

Ah ok, I misread the question.
So the most straight forward way to put the badge text on the button is to create a closure.
var button = new Ext.Button({
text: 'Messages',
handler: tapHandler});
Ext.Ajax.request({
....
success: function(response, opts){
button.setBadge(Ext.decode(response.responseText));
}
...
});
This will cause the badge text to be updated when the AJAX call completes. You can then add the object to a Panel or Toolbar after the AJAX request code as you would have before.
If you absolutely have to have the badge text on the button before it is created, you will need to create the button group inside the success function and assign/add it to the appropriate container object.

Related

Selectors not working on ajax response

I'm using ajax to submit pages and return content blocks based on user action for an onboarding sequence.
If have a page which loads and get 1 content element, the user then clicks Yes or No, which loads the next content element into the same space (via ajax).
For some reason my selectors don't seem to be working on that ajax loaded html.
Here is my ajax function which gets the form:
$.ajax({
beforeSend: function() {
$("#loader").toggleClass('progress');
},
type: 'POST',
dataType: 'json',
data: data,
url: baseUrl+'welcome/user_confirmation_form',
complete: function( response ) {
$("#loader").toggleClass('progress');
},
success: function( response ) {
console.log(response);
$("div.welcome-page > .col").html(response.response);
},
error: function( response ) {
$("#next-steps").html(response.response);
}
});
I'm then trying to access the submit button (have tried doing it as a ahref and button type=submit but nothing seems to be selecting the event.
$('div.welcome-page').on('submit', "user_complete", function(e) {
e.preventDefault();
console.log('FOund form');
var user = $(this).serializeArray();
console.log(user);
});
If I view source, the ajax returned HTML is not even in the dom, but it is when viewing the UI normally.
I'm guessing this has something to do with it?
How can I select all the form data?
Any time I click on the button or ahref it just fires the same page again.
If user_complete is a class you are assigning on your submit button in your loaded html, then you are missing a .
$('div.welcome-page').on('submit', ".user_complete", function(e) {
But this will only work if you're using a submit action as this is listening for a submit event. Maybe you want to listen for a click event?
You need to bind the events to your handlers for your newly added HTML elements. Your original call to
$('div.welcome-page').on('submit' ...
Only bound the event handler for the elements that were on the page at that point in time.
You can put your handler into a function ...
var myHandler = function(e) {
e.preventDefault();
var user = $(this).serializeArray();
}
And then after you load the new HTML you need to bind the handler to the event. So, on success with the AJAX you would ...
success: function( response ) {
$("div.welcome-page > .col").html(response.response);
$('div.welcome-page').on('submit', "user_complete", myHandler);
},

jquery live() appending click events causing multiple clicks

I have some strange behaviour going on with the jQuery ajax functionality in my asp.net MVC3 application.
I have several boxes of data each containing a link to open a popup and change the data in each box. To do this I've added a jquery live() click event to process the data via a jQuery ajax call. In the "success" method of the ajax call, i take the return data and open a UI Dialog popup (a partial view) which contains a list of radio buttons. I select a different radio button and press 'close' - the close button fires another live() click event, processes that new data via an ajax call which refreshes the data in the box on the main page.
This works perfectly first time. If you then click to change it again, the popup opens, allows you to select a new value, but this time pressing close on the popup triggers two click events which throws an null error in my MVC controller.
If you repeat this process it triggers 3 click events, so it's clear that live() is appending these events somewhere.
I've tried using on() and click(), but the page itself is made up of panels loaded in via ajax so I used live() to automatically bind the events.
Here is the code I'm using:
HTML
<p><!--Data to update goes here--></p>
Update Data
First Click event calling popup with Partial View
$('a.adjust').live('click', function (e) {
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("ChangeOptions", "Search")';
var dialog = $('<div id="ModalDialog" style="display:none"></div>').appendTo('body');
// load the data via ajax
$.ajax({
url: url,
type: 'POST',
cache: false,
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
dialog.html(response);
dialog.dialog({
bgiframe: true,
modal: true
}
});
}
});
e.preventDefault();
});
Second click event the takes the new info to return updated partial view
$('a#close').live('click', function (event) {
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("GetChangeInfo", "Search")';
$.ajax({
url: url,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
$('#box-' + #column).html(response); //this refreshes the box on the main page
},
error: function () {
}
});
$('#ModalDialog').dialog('close');
event.preventDefault();
});
Anybody know what might be happening here, and how I could resolve it?
Use namespaces to unbind previous click binds like this:
$('a.adjust').unbind('click.adjustclick');
Then bind the click action to a.adjust:
$('a.adjust').bind('click.adjustclick', function(){
//your code here
//note the return false, this prevents the browser from visiting the URL in the href attribute
return false;
});
If i understand you correctly, you try to run the second click action when the dialog is closed. Therefor I would use the build in close function for the dialog like this:
$('a.adjust').bind('click.adjustclick', function(){
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("ChangeOptions", "Search")';
var dialog = $('<div id="ModalDialog" style="display:none"></div>').appendTo('body');
// load the data via ajax
$.ajax({
url: url,
type: 'POST',
cache: false,
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
dialog.html(response);
dialog.dialog({
bgiframe: true,
modal: true,
close: function(){
var jsonData2 = getJsonString(n[1]);
var url2 = '#Url.Action("GetChangeInfo", "Search")';
$.ajax({
url: url2,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: jsonData2,
success: function (response2) {
$('#box-' + #column).html(response2); //this refreshes the box on the main page
},
error: function () {
}
});
}
}
});
}
});
});
If you are using your own button a#close, bind a click event to it to close the dialog, it will automatically fire the close function for the dialog.
$('a#close').unbind('click.closedialog');
$('a#close').bind('click.closedialog', function () {
$('#ModalDialog').dialog('close');
return false;
}
Try this:
$('a#close').unbind('click').bind('click', function (event) {
//Your Code
});

can you do a jquery mobile popup on ajax response event?

Was hoping to use the popup and I am pretty sure I am trying to use it incorrectly. Any ideas on how this should work? Can you use the popup in this manner?
<script>
function onSuccess(data, status)
{
data = $.trim(data);
$("#notification").text(data);
}
function onError(data, status)
{
data = $.trim(data);
//$("#notification").text(data);
$("#notification").popup(data); }
$(document).ready(function() {
$("#submit").click(function(){
var formData = $("#callAjaxForm").serialize();
$.ajax({
type: "POST",
url: "sendmsg.php",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
});
</script>
I'm assuming you are trying to use the JQM popup widget, first your missing the closing } from your onError function. Second to use the popup widget you can first set the data
$("#myPopupContent").text(data)
Then to display you use the open method
$("#myPopup").popup("open")

Check if image exists, if not load it

I need to load an image if if hasn't been loaded yet.
For this i'm using the error function like this:
$.ajax({
type: "POST",
url: "inc/functions.php",
data: { productID: productIDVal, action: "addToCart"},
success: function(theResponse) {
busy=false;
$('#buyButton')
.error(function(){
var t = $("<img id='buyButton' src='images/checkout.png' />");
$.append(t);
});
}
});
But it is not working. Am i doing something wrong here?
Thanks in advance.
You need to specify where to append the image:
$('#buyButton').append(t); // NOT $.append(t);
// OR $(this).append(t);
More info here
Some general tips on debugging javascript.
Quick and dirty: Put an alert message on the first line of the error function like alert('inside error'). Then load the page and see if the alert message shows up. You can put variables inside the alert message to see what their values are. If you don't see an alert message it means that the code is not even being loaded for some reason, so you have to put an alert message at an earlier point. (This can get very tedious).
Better way: Start using Firebug or Safari's Web Inspector to debug the javascript. Just put debugger anywhere in your code and when the browser gets to that line of code, it will stop and give you a console with access to all variables and functions available at that point in the code.
The problem may be with the AJAX request. See what it is returning by trying this code:
$.ajax({
type: "POST",
url: "inc/functions.php",
data: { productID: productIDVal, action: "addToCart"},
success: function(data){ alert('success!'); },
error: function(XMLHttpRequest, textStatus, errorThrown){ alert(errorThrown) ;}
})
You can replace the alert messages with debugger to do further inspection of what is going on with Firebug.
you should move the code to error block
remove from the success block
error: function(request,error) {
var t = $("<img id='buyButton' src='images/checkout.png' />");
$(this).append(t);
}
the skeleton goes like this
$.ajax({
},
beforeSend: function() {
},
error: function(request,error) {
var t = $("<img id='buyButton' src='images/checkout.png' />");
$(this).append(t);
},
success: function(request) {
} // End success
}); // End ajax method

Proper jQuery technique to disable button with ajax post then re-enble button onComplete

I have a button that performs an ajax post -- I want to disable the button, then perform my work, then upon completion -- I want to re-enable the button. My interaction includes swapping out the image button (to a grayed out image button), and presenting a spinner. When complete, I hide the spinner and restore the original button image.
My approach includes unbinding, then rebinding the click event.
Here's my code -- it works great -- but, I want to know if this is a proper/efficient/acceptable strategy?
// Update club name
$j('#btnUpdateClubName').bind('click', updateClubName);
function updateClubName() {
var $this = $j(this);
var $spinner = $this.next('.spinner');
var renderURL = RES.BuildClubUpdateURL("UpdateClubName");
$this.ajaxStart(function() {
$this.attr("src", imgPathSaveAndUpdateBtnDisabled).unbind('click').addClass('wait-cursor');
$spinner.show();
});
$j.ajax({ type: "POST", data: $j('#hidStandingOrderId, #txtClubName, #clubOrderIdEditClubName').serialize(), url: renderURL, dataType: 'html', contentType: 'application/x-www-form-urlencoded',
success: function(data) {
// do some stuff
}
}
});
$this.ajaxComplete(function() {
$spinner.hide();
$this.attr("src", imgPathSaveAndUpdateBtn).bind('click', updateClubName).removeClass('wait-cursor');
$j("#cbEditClubName").colorbox.close();
});
}
What you have works but it is a bit wasteful, as it adds a new ajaxStart and ajaxComplete handler each time the function runs, I would make one suggestion though, change your .unbind() call to be more specific since you have the information. If you change this:
.unbind('click')
To this:
.unbind('click', updateClubName)
You can have other click events without the .unbind() interfering, it'll only unbind that one handler.
An overall better alternative (to me, you can debate whether it's "better") without rebinding would be to store a variable to know you're currently posting using $.data() and .data(), for example:
$j('#btnUpdateClubName').bind('click', updateClubName);
function updateClubName() {
if($.data(this, "posting")) return false; //are we posting? abort!
$.data(this, "posting", true); //set variable
var $this = $j(this);
var $spinner = $this.next('.spinner');
var renderURL = RES.BuildClubUpdateURL("UpdateClubName");
$this.attr("src", imgPathSaveAndUpdateBtnDisabled).addClass('wait-cursor');
$spinner.show();
$j.ajax({ type: "POST", data: $j('#hidStandingOrderId, #txtClubName, #clubOrderIdEditClubName').serialize(), url: renderURL, dataType: 'html', contentType: 'application/x-www-form-urlencoded',
success: function(data) {
// do some stuff
$spinner.hide();
$this.attr("src", imgPathSaveAndUpdateBtn).removeClass('wait-cursor')
.data("posting", false); //clear it out, ready to post again
$j("#cbEditClubName").colorbox.close();
}
});
}
With this approach if you're doing a POST the data for "posting" is true, and future clicks just abandon out...not until the response comes back and your success code runs is the button re-enabled. It's the same effect but no duplicate handlers and no re/un-binding.

Resources