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

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")

Related

when ajax post success i want to refresh a particular <div> in page

i want to refresh a particular div on ajax success, im using the below code but the whole page getting refreshed.
<script type="text/javascript">
$('#post_submit').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
return false;
});
return false;
});
</script>
you have an extra return false which is inside the $.ajax block which most probably causes an error so your form isn't submitted via ajax. If you remove that, you shouldn't have any issues.
Use the submit event of the form and remove the return false from the ajax callback:
$('#myFormId').on('submit', function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
Remove the return false from inside your $.ajax function. Its a syntax error. The $.ajax function only expects a json object as an argument. "return false" cannot be part of a json object. You should keep the JavaScript console open during testing at all times - Press Ctrl-Shift-J in Chrome and select console to see any JS errors.
Also suggest you use <input type=button> instead of <input type=submit> or <button></button>

AJAX avoid repeated code

I'm using Symfony2.1 with Doctrine2.1
I'd like to use AJAX for many features on my site , editing a title , rate an article , create an entity on the fly , etc.
My question is simple :
Do I need to create a JQuery function for each functionnality , like this :
$('#specific-functionality').bind('click', function(e){
var element = $(this);
e.preventDefault();
// the call
$.ajax({
url: element.attr('href'),
cache: false,
dataType: 'json',
success: function(data){
// some custom stuff : remove a loader , show some value, change some css
}
});
});
It sounds very heavy to me, so I was wondering if there's any framework on JS side, or a specific method I can use to avoid this. I was thinking about regrouping items by type of response (html_content , boolean, integer) but maybe something already exists to handle it nicely !
From what I understand, you are asking for lighter version of JQuery ajax method. There are direct get/post methods instead of using ajax.
$.get(element.attr('href'), {'id': '123'},
function(data) {
alert(data);
}
);
To configure error function
$.get(element.attr('href'), {'id': '123'}, function(data) {alert(data);})
.error(function (XMLHttpRequest, textStatus, errorThrown) {
var msg = jQuery.parseJSON(XMLHttpRequest.responseText);
alert(msg.Message);
});
Also, you can pass callback function to do any synchronous operations like
function LoadData(cb)
{
$.get(element.attr('href'), { 'test': test }, cb);
}
And call
LoadData(function(data) {
alert(data);
otherstatements;
});
For progress bar, you use JQuery ajaxStart and ajaxStop functions instead of manually hiding and showing it. Note, it gets fired for every JQuery AJAX operation on the page.
$('#progress')
.ajaxStart(function () {
//disable the submit button
$(this).show();
})
.ajaxStop(function () {
//enable the button
$(this).hide();
});
Instead of $('#specific-functionality').bind('click', function(e){, try this:
$(".ajax").click(function(){
var url = $(this).attr("href") ;
var target = $(this).attr("data-target") ;
if (target=="undefined"){
alert("You forgot the target");
return false ;
}
$.ajax(....
And in html
<a class="ajax" href="..." data-target="#some_id">click here </a>
I think it is the simplest solution. If you want some link to work via ajax, just give it class "ajax" and put data-target to where it should output results. All custom stuff could be placed in these data-something properties.

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
});

ajax form submission

I am using a cakephp form. I have a dropdown select box. If dropdown value changes then the form should submit.Is there any method similar to form submission like this.form.submit for ajax forms. Any help?
If jquery is okay for you you can do
$('#myDropdown').change(function() {
$(this).closest('form').submit();
});
if you want ajax replace line 2 as follows
var myForm = $(this).closest('form');
$.post(myForm.attr('action'), myForm.serialize(), function(data)
{
/*do something on success*/
}
If you use jQuery you could use the .serialize() method and AJAXify a form like this:
$(function() {
$('#myform').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
// TODO: process the results
}
});
return false;
});
});
Another possibility is to use the excellent jQuery form plugin.
You can use dropdown elemnts onChange event
Example
$('.target').change(function() {
alert('Handler for .change() called.');
});

Disable Button while AJAX Request

I'm trying to disable a button after it's clicked. I have tried:
$("#ajaxStart").click(function() {
$("#ajaxStart").attr("disabled", true);
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
},
error: errorhandler,
dataType: 'json'
});
$("#ajaxStart").attr("disabled", false);
});
but the button is not getting disabled. When I remove $("#ajaxStart").attr("disabled", false); the button gets disabled.
While this is not working as expected, I think the code sequence is correct. Any help will be appreciated.
Put $("#ajaxStart").attr("disabled", false); inside the success function:
$("#ajaxStart").click(function() {
$("#ajaxStart").attr("disabled", true);
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
$("#ajaxStart").attr("disabled", false);
},
error: errorhandler,
dataType: 'json'
});
});
This will ensure that disable is set to false after the data has loaded... Currently you disable and enable the button in the same click function, ie at the same time.
In your code, you just disable & enable the button on the same button click,.
You have to enable it inside the completion of AJAX call
something like this
success: function(response){
$("#ajaxStart").attr("disabled", false);
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
},
I have solved this by defining two jquery functions:
var showDisableLayer = function() {
$('<div id="loading" style="position:fixed; z-index: 2147483647; top:0; left:0; background-color: white; opacity:0.0;filter:alpha(opacity=0);"></div>').appendTo(document.body);
$("#loading").height($(document).height());
$("#loading").width($(document).width());
};
var hideDisableLayer = function() {
$("#loading").remove();
};
The first function creates a layer on top of everything. The reason the layer is white and completely opaque, is that otherwise, IE allows you to click through it.
When doing my ajax, i do like this:
$("#ajaxStart").click(function() {
showDisableLayer(); // Show the layer of glass.
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
hideDisableLayer(); // Hides the layer of glass.
},
error: errorhandler,
dataType: 'json'
});
});
I solved this by using global function of ajax
$(document).ajaxStart(function () {
$("#btnSubmit").attr("disabled", true);
});
$(document).ajaxComplete(function () {
$("#btnSubmit").attr("disabled", false);
});
here is documentation link.
The $.ajax() call "will not block" -- that means it will return immediately, and then you enable the button immediately, so the button is not disabled.
You can enable the button when the AJAX is successful, has error, or is otherwise finished, by using complete: http://api.jquery.com/jQuery.ajax/
complete(XMLHttpRequest,
textStatus)
A function to be
called when the request finishes
(after success and error callbacks are
executed). The function gets passed
two arguments: The XMLHttpRequest
object and a string categorizing the
status of the request ("success",
"notmodified", "error", "timeout", or
"parsererror"). This is an Ajax Event.

Resources