i have a problem with a script javascript. I have an object with inside some function and variable. In one of these function i make an ajax request and inside the error handler i call a function defined in the same object but the debugger say that the function is "not available" but the variables defined in the object are visible...
This is the portion of Javascript with the object:
Utils = {
"defaultErrorMessage" : "Ci scusiamo per il disagio ma qualcosa è andato storto, probabilmente è una cosa temporanea, ritenta in un altro momento",
"base_url" : $('#base_url').val(),
getApiUri : function(name) {
return window.location.protocol + "//" + window.location.host + PATH[ENV] + name + ENV == 'stub' ? '.json' : '';
},
callServer : function(uri, data, successCallback) {
$.ajax({
type: "POST",
url: this.base_url + "index.php/" + uri,
data: data,
dataType: "json",
cache: false,
beforeSend: function(XMLHttpRequest)
{
waitingDialog.show('Caricamento...');
},
success:
function (data) {
//alert(data); //as a debugging message.
successCallback(data);
},
error: function (xhr, ajaxOptions, thrownError) {
//alert("Qualcosa di storto: "+ xhr.status + " messaggio: " + xhr.responseText);
this.showModalDialog('error','Siamo spiacenti :(', this.defaultErrorMessage);
},
complete: function() {
waitingDialog.hide();
}
});
},
hideAllMessages: function ()
{
var messagesHeights = new Array(); // this array will store height for each
for (i=0; i<myMessages.length; i++)
{
messagesHeights[i] = $('.' + myMessages[i]).outerHeight();
$('.' + myMessages[i]).css('top', -messagesHeights[i]); //move element outside viewport
}
},
showMessage: function(type, title, message) {
var title = (typeof title !== 'undefined') ? title : '';
var message = (typeof message !== 'undefined') ? message : '';
this.hideAllMessages();
if (title != '')
$('.'+type + ' h3').html(title);
if (message != '')
$('.'+type + ' p').html(message);
$('.'+type).animate({top:"0"}, 500);
},
showModalDialog: function(type, title, message, withOK) {
var withOK = (typeof withOK !== 'undefined') ? withOK : false;
$div = $('<div id="error" title="'+title+'">');
$div.append('<p>'+message+'</p>');
if (!withOK) {
$div.dialog({
modal: true,
maxHeight: 500
}).prev(".ui-dialog-titlebar").css("background", colorDialog[type]);
}
else {
$div.dialog({
modal: true,
maxHeight: 500,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
}).prev(".ui-dialog-titlebar").css("background", colorDialog[type]);
}
},
validateEmail: function(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
};
Why this.showModalDialog is not available in the error handler? I have tried also without "this" but is the same...
this doesn't always work in callback functions because the context changes so this is referring to something that is no longer your Utils object. The way to fix this is by keeping a variable to remember what your context is when you need it. In your callServer function, before the ajax call, add var self = this. And then when you need to reference showModalDialog, you can call it with self.showModalDialog();
callServer : function(uri, data, successCallback) {
var self = this;
$.ajax({
...
self.showModalDialog();
The problem is that this represents your object in callServer, but it doesn't have the same meaning inside the function you're passing to your Ajax call, there instead represents the object you're passing to $.ajax() as argument.
You need to pass it as another variable like self.
Inside callServer
var self = this;
Inside you error handler
self.showModalDialog();
Related
On a page I have a list of dates which I want to edit via AJAX.
Example:
<li>January 2015<a data-update_url="/frame_date/22/update/" class="update" id="update_framedate_22" href="javascript:void(0)">Edit</a>
When the user clicks on the Edit link, I catch element id and the edit link.
Than AJAX requests the update form from the server. And now I have to place the form instead of the element with the mentioned id.
In other words, in frame_date_update_show_get I need element's id. In the example below, I keep it in the global variable date_id. But inside me there is a protest: I was always taught that global variables is a bad practice. But in this case I don't know how to get along without the global variable date_id.
Could you give me some piece of advice: is my code acceptable or there is a better way to cope with the problem.
function frame_date_update_show_get(data){
$("#" + date_id).replaceWith(data);
}
function frame_date_update_get_data(){
date_id = this.getAttribute('id')
var cuaghtUrl = this.getAttribute('data-update_url');
$.ajax({
method: 'get',
url: cuaghtUrl,
success: frame_date_update_show_get,
error: fail
});
}
var date_id = ""
Use an anonymous function as success callback function and then call frame_date_update_show_get with an additional date_id parameter:
function frame_date_update_show_get(data, date_id) {
$("#" + date_id).replaceWith(data);
}
function frame_date_update_get_data() {
var date_id = this.getAttribute('id')
var cuaghtUrl = this.getAttribute('data-update_url');
$.ajax({
method: 'get',
url: cuaghtUrl,
success: function(data) {
frame_date_update_show_get(data, date_id);
},
error: fail
});
}
I would use contenteditable combined with AJAX this way:
function dateChange(options){
switch( options.action ) {
case 'update':
if( options.id && options.text && options.updateUrl ) {
$.ajax({
method: 'post',
url: options.updateUrl,
data: {
id: options.id,
html: options.text
},
success: function(response) {
options.element.html( response );
options.element.removeClass('editing');
},
error: function(err) {
console.log( 'request failed: ' + err.text );
}
});
};
break;
default:
console.log( 'action invalid' );
return false;
break;
};
};
var editTimeout = null;
$('li[data-update-url]').on('input', function(e) {
var thisText = $(this);
thisText.addClass('editing');
clearTimeout( editTimeout );
editTimeout = setTimeout(function() {
var updateUrl = thisText.data('updateUrl');
var id = thisText.data('id');
dateChange({
'action': 'update',
'element': thisText,
'id': id,
'updateUrl': updateUrl,
'text': thisText.html()
});
}, 1000);
});
.editing {
color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-update-url="/echo/html/" data-id="update_framedate_22" contenteditable>January 2015</li>
</ul>
Check how it works on JSFiddle.
This code would be easy to expand for other actions you may need, as delete, add.
function Edit() {
var mode = 2; // 2 For Edit
var Fid = 0;
var viewName = 'MemberEditor';
var actionURL = '#Url.Action("setViewMode", "Member")';
$.ajax({
type: "POST",
data: {
Mode: mode,
lFeatureId: Fid,
ViewName: viewName
},
url: actionURL,
success: function (result) {
setViewMode(result);
}
});
}
this is the function where in i am calling setViewMode(result).
but somehow it is sot being called properly..
function setViewMode(data) {
for (keyVar in data) {
if (keyVar.search("Btn") != -1) {
jQuery('#' + keyVar).attr("disabled", data[keyVar]);
} else {
jQuery('#' + keyVar).prop("readonly", data[keyVar]);
}
}
}
The control isn't getting transferred to the loop. Can anyone help please?
I think you are getting back a JSON string. Use .$parseJSON(data) to get the contents stored.
im trying to make a script that changes P lines to input fields, let user edit them and then revert back to p lines after a check in an external php document through ajax. However the problem seems to be that I cant use this within the ajax part, it breaks the code. How can I solve that? Do I need to post the HTML?
$(document).ready(function () {
function changeshit(result, that) {
if (result == "success") {
$(that).closest('div').find('input').each(function () {
var el_naam = $(that).attr("name");
var el_id = $(that).attr("id");
var el_content = $(that).attr("value");
$(that).replaceWith("<p name='" + el_naam + "' id='" + el_id + "'>" + el_content + "</p>");
});
$(".editlink").replaceWith("Bewerken");
} else {
alert(result);
}
}
$(".editinv").on('click', 'a', function () {
var editid = $(this).attr("id");
var edit_or_text = $(this).attr("name");
if (edit_or_text == "edit") {
$(this).closest('div').find('p').each(function () {
var el_naam = $(this).attr("name");
var el_id = $(this).attr("id");
var el_content = $(this).text();
$(this).replaceWith("<input type='text' name='" + el_naam + "' id='" + el_id + "' value='" + el_content + "' />");
});
$(".editlink").replaceWith("Klaar");
} else if (edit_or_text == "done") {
var poststring = "";
$(this).closest('div').find('input').each(function () {
var el_naam = $(this).attr("name");
var el_id = $(this).attr("id");
var el_content = $(this).attr("value");
poststring = poststring + '' + el_naam + '=' + el_content + '&';
});
poststring = poststring + 'end=end'
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function (result, this) {
changeshit(result, this);
}
});
}
});
});
Yes, the common solutions is declare a var example self = this and use that variable
var self = this;
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function(result) {
changeshit(result, self);
}
});
}
In that way, the this context is save in the variable.
Try the following:
Right under $(".editinv").on('click', 'a', function () { add
$(".editinv").on('click', 'a', function () {
var element = this;
And then change this to:
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function (result) {
changeshit(result, element);
}
});
That is if I am understanding correctly what you are trying to do
If you simply add:
context: this
to the $.ajax options then the success handler will automatically be called with the correct value of this, so you won't need the that parameter.
You'll then also no longer need the extra function wrapper around the success callback, so you can just use:
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this, // propagate "this"
success: changeshit // just pass the func ref
});
There are a few ways you can achieve this
1) If you read the docs (jQuery.ajax) you'll see that you can supply a context to the ajax method
context
Type: PlainObject This object will be made the context of all Ajax-related callbacks. By default, the context is an object that
represents the ajax settings used in the call ($.ajaxSettings merged
with the settings passed to $.ajax).
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this,
success: function(result) {
// the context sent above would become the context of this function when called by jquery
changeshit(result, this);
}
});
Using it this way you could even do it like the bellow code
function changeshit (result) {
var $that = $(this);
if (result == "success") {
$that.closest('div')... // cool ha ?
};
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this,
success: changeshit
});
2) You can take advantage of closures ( read more here or search google ), so your code would become
var context = this;
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function(result) {
// here you can use any variable you declared before the call
changeshit(result, context);
}
});
As a side note, i would recommend you use variable/object caching, so declare var $this = $(this) at the top of the function and use it thruought your function, instead of calling $(this) each time you need it.
I'm having some trouble using JQUERY Post function.
I have 2 functions that call JQUERY Post function.
Both of them is working fine, but the callback function is never called (handleLike).
When I call handleLike manually, it's works perfect.
(Even if handleLike has just an alert inside, the callback function is not called)
Could you please help me with this thing?
<script type="text/javascript">
$(document).ready(function() {
function handleLike(v_cb){
alert("Call back chamou!");
$('#erro').html(v_cb.mensagem);
if (v_cb.class == 'map'){
var elemento = $('#maplike');
}else{
var elemento = $('#commentlike'+v_cb.id);
}
if (!(elemento.hasClass('disabled'))){
elemento.addClass("disabled");
var likes = elemento.find('font').text();
likes++;
elemento.find('font').html(likes);
}
}
$('#maplike').click(function() {
//var map_id = $('#like').find('font').attr('value');
var id = $(this).attr("name");
if (!($(this).hasClass('disabled'))){
var JSONObject= {
"mensagem":"Testando Json",
"id":86,
"class":"map"
};
handleLike(JSONObject);
alert("Teste");
$.post(
'/cmap/maps/like',
{ id: id },
handleLike,
'json'
);
}
});
$('[id*="commentlike"]').click(function() {
//var map_id = $('#like').find('font').attr('value');
var id = $(this).attr("name");
if (!($(this).hasClass('disabled'))){
$.post(
'/cmap/comments/like',
{ id: id },
handleLike,
'json'
);
}
});
});
</script>
Diagnostic, not solution
Rationalizing and adding an error handler, you should get something like this :
$(document).ready(function() {
function handleLike(v_cb){
alert("Call back chamou!");
$('#erro').html(v_cb.mensagem);
var elemento = (v_cb.class && v_cb.class == 'map') ? $('#maplike') : $('#commentlike'+v_cb.id);
if (!elemento.hasClass('disabled')){
var f = elemento.addClass("disabled").find('font');
f.html(++Number(f.text()));
}
}
function ajaxError(jqXHR, textStatus, errorThrown) {
alert('$.post error: ' + textStatus + ' : ' + errorThrown);
};
$('#maplike').on('click', function() {
var $this = $(this);
if (!$this.hasClass('disabled')) {
$.post('/cmap/maps/like', { id: $this.attr("name") }, handleLike, 'json').fail(ajaxError);
}
});
$('[id*="commentlike"]').on('click', function() {
var $this = $(this);
if (!$this.hasClass('disabled')) {
$.post('/cmap/comments/like', { id: $this.attr("name") }, handleLike, 'json').fail(ajaxError);
}
});
});
untested
Barring mistakes, there's a good chance the error handler will inform you of what's going wrong.
I follow the Kevin B tip and use $ajax method.
It was a parseerror. Sorry.
The return of v_cb was not a json, it was a html. I correct my return, and everything was ok.
I have created a javascript and a WebMethod. It works in IE but not in firefox and chrome
MyWebMethod
[WebMethod]
public string Send(string name, string email, string message)
{
try
{
MailMessage objMailMessage = default(MailMessage);
objMailMessage = new MailMessage();
objMailMessage.From = new MailAddress(email, name,System.Text.Encoding.UTF8);
objMailMessage.To.Add("feedback#abc.in");
objMailMessage.Subject = "Feedback";
objMailMessage.Body = "<b>Name :</b> " + name + "<br/><br/>";
objMailMessage.Body += "<b>Email :</b> " + email + "<br/><br/>";
objMailMessage.Body+= "<b>Message :</b> "+message;
objMailMessage.IsBodyHtml = true;
objMailMessage.Priority = MailPriority.High;
CommonFunctions.CommonFunctions.SendEmailMessage(objMailMessage);
return "success";
}
catch (Exception ex)
{
Logger.Log.Error(ex);
return "Fail";
}
}
MYScript
$.ajax({
datatype: 'text',
type: 'POST',
url: options.url,
data: { name: $(this_id_prefix + '#name').val(), email: $(this_id_prefix + '#email').val(), message: $(this_id_prefix + '#message').val() },
success: function (data) {
$(this_id_prefix + '#loading').css({ display: 'none' });
var xmlDoc = data;
var returnvalue = xmlDoc.childNodes(1).firstChild.nodeValue;
if (returnvalue == "success") {
$(this_id_prefix+'#callback').show().append(options.recievedMsg);
setTimeout(function () {
$(this_id_prefix + '.holder').show();
$(this_id_prefix + '#callback').hide().html('');
}, 2000);
if(options.hideOnSubmit == true) {
//hide the tab after successful submition if requested
$(this_id_prefix+'#contactForm').animate({dummy:1}, 2000).animate({"marginLeft": "-=450px"}, "slow");
$(this_id_prefix+'div#contactable_inner').animate({dummy:1}, 2000).animate({"marginLeft": "-=447px"}, "slow").animate({"marginLeft": "+=5px"}, "fast");
$(this_id_prefix+'#overlay').css({display: 'none'});
}
} else {
$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
setTimeout(function(){
$(this_id_prefix+'.holder').show();
$(this_id_prefix+'#callback').hide().html('');
},2000);
}
},
error:function(){
$(this_id_prefix+'#loading').css({display:'none'});
$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
}
});
I am not able to get return value from webmethod to script. In Success funcation I want to check that if(data=="Success") but here I am not able to check that. Is there anything wrong in script like datatype or any other issue? Here var returnvalue = xmlDoc.childNodes(1).firstChild.nodeValue; is not working. It works locally fine but after publish to server it's not working. It return object xmldocument in data. It's not returing string. I have changed datatype to text