Not getting data value from [object XMLDocument] after success Ajax - javascript

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

Related

Error part in jQuery is missing

I build following JavaScript part and everything works fine. But I'm not sure if the code is completely right. Because in my script I only use success: function() but I don't use error. Is it a MUST to have error in a jQuery AJAX call?
Currently I'm catching the errors in my php controller function and echo them in the success part.
$(document)
.ready(function() {
var groupName = '';
var groupid = '';
$(".grp")
.click(function() {
$('.text-danger')
.html('');
groupName = $(this)
.data('groupname');
groupid = $(this)
.attr('id');
$('.text')
.html(groupName);
$('#dataModal')
.modal({
show: true
});
});
jQuery(".grpval")
.click(function(e) {
e.preventDefault();
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
, });
jQuery.ajax({
url: "{{ route('request_group') }}"
, method: 'post'
, data: {
'Gruppe': groupid
}
, success: function(data) {
if (typeof data.successsuccess != 'undefined') {
jQuery('.alert-success')
.show();
jQuery('.alert-success')
.html('<p>' + data.successsuccess + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else if (typeof data.successdberror != 'undefined') {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + data.successdberror + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else {
jQuery.each(data.errors, function(key, value) {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + value + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
});
}
}
});
});
});
EDIT: Here is the function from my Controller:
public function setGroupRequest(Request $request){
$validator = \Validator::make($request->all(), [
'Gruppe' => [new ValidRequest]
]);
$groupid = $request->input('Gruppe');
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
try{
$groups_request = new GroupRequest();
$groups_request->idgroups = $groupid;
$groups_request->iduser = Auth::id();
$groups_request->request_active = 1;
$groups_request->save();
$db_status = 'success';
}catch(\Exception $e){
$db_status = 'error';
}
if($db_status == 'success'){
return response()->json(['successsuccess'=>'Record is successfully added']);
}else{
return response()->json(['successdberror'=>'DB Error! Values could not be saved.']);
}
}
Error handling is required as you never know different things on the internet might result in failure of request for example,
Network failure.
Lost database connection
Unauthorised access/access denied
Any variable being not defined
There is nothing wrong in your way of writing PHP error in success, but writing it in $ajax error callback function is preferred as it helps in separating error & success logic.
In fact you can add a jquery error callback function as well to your $ajax which will handle all the errors originating from above mentioned internet failures.
You can add error function, which will receive any type of error coming from backend.
jQuery.ajax({
url: "{{ route('request_group') }}",
method: 'data: {
'Gruppe': groupid
},
success: function(data) {
//code here
},
error: function (jqXHR, exception) {
//error handling
}
})
In your PHP file,
if ($query) {
echo "success"; //whatever you want to show on success.
} else {
die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure
}
This way you can catch PHP error as well as any internet Network errors in your jquery ajax.

jQuery AJAX post returns 403 error

I have the following script for AJAX to do login, but with some passwords that contain characters like "!##" it will return 403 error and will not submit to the PHP.
$(document).ready(function () { // When the document is ready
$('#login').click(function (e) { // We attach the event onchange to the select element
e.preventDefault();
var form_info = "";
$('#login_form *').filter(':input').each(function(){
if(this.value !== ""){
form_info += this.name;
form_info += "=";
form_info += encodeURIComponent(this.value);
form_info += "&";
}
});
form_info += "function_name=login";
var form = $('#login_form').serialize() + "&function_name=login";
$.ajax({
url: "function_ajax.php", // path to you php file
type: "post", // We want a POST request
dataType: 'html',
data: form_info,
statusCode:
{
404: function () {
alert('Could not contact server.');
},
500: function () {
alert('A server-side error has occurred.');
}
},
error: function ()
{
alert('A problem has occurred.');
},
beforeSend: function ()
{
alert(form_info);
alert(form);
},
complete: function ()
{
},
success: function (data) { // The function to execute if the request is a -success-,
if(data === "1"){
if (document.referrer !== "") {
window.location.href = document.referrer;
}
else{
window.location.href = "some_domain"
}
}
else if (data === "2")
{
alert("invalid");
}
else {
alert("empty");
}
}
});
});
});
You will find that I'm trying both ways to encode each element and the serialize just to check if I'm getting the same result, and I'm getting the same result, but still, it's getting this error.
If I try to encode the whole serialize, then I will not get the error but in PHP, the $_POST array will have the first key as the data I'm sending with no value.
encodeURIComponent($('#login_form').serialize()) + "function_name=login"
then the $_POST will be like
array(
[email=email#gmail.com&password=pass123!##&function_name=login]=>
)
which will not be useful for me.

Javascript call to function not available

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

Ajax call successful, but error block is executing

I'm trying to save a post to my database which it does, however the ajax error block is executing. It states ok in its response though so I looked around on some of the other questions and it seemed like I wasn't returning a Json object so I tried a few things:
Creating a NameValule variable and adding ("Success","true") and converting it to Json by Json.Encode(NameValue);
Returning a string in the format of Json:"{ \"Result\":[{\"Success\":\"true\"}]}";
Changing the dataType to "text json" "text/json"
The error block still executes for some reason, any ideas?
//Save it all in an object to be passed in ajax
var Post = {
Id: postID,
Title: postTitle.val(),
Author: postAuthor,
Date: postDate,
Content: postContent.val(),
metaDescription: metaDescription.val(),
metaKeywords: metaKeywords.val(),
metaID: metaId.text(),
Page: $(document).attr('title')
};
//save to database
$.ajax({
url: url,
type: 'POST',
dataType: "text json",
data: { data: JSON.stringify(Post) },
success: function (result) {
console.log("result: " + result);
if (result == "Success") {
// postContent.append("<br/><p>Edit Successful!</p>");
alert('Edit successfull');
//window.location.replace(window.location.href);
}
else {
postContent.replaceWith("<div>" + result + "</div>");
}
},
error: function (xhr, status) {
console.log('ajax error = ' + xhr.statusText);
}
});
Here is the response page:
#using WebMatrix.Data;
#functions{
public string EditPost()
{
var db = Database.Open("StarterSite");
var post = Request.Unvalidated["data"];
var result = Json.Decode(post);
var error = new System.Collections.Specialized.NameValueCollection();
/* Id: postID,
Title: postTitle,
Author: postAuthor,
Date: postDate,
Content: afterEdit,
Page: $(document).attr('title')
*/
if(string.IsNullOrEmpty(result["Id"]))
{
error.Add("Error", "Id empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["Author"]))
{
error.Add("Error", "Author empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["Content"]))
{
error.Add("Error", "Content empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["Date"]))
{
error.Add("Error", "Date empty");
return Json.Encode(error);
}
//Page and Title only ones that can be empty
var cmd = "UPDATE Posts SET ID='" + result["Id"]
+ "',Author='" + result["Author"]
+ "',Content='" + result["Content"]
+ "',Date='" + result["Date"]
+ "',Title='" + result["Title"]
+ "',Page='" + result["Page"]
+ "' WHERE ID='" + result["Id"] + "';";
try { db.Execute(cmd); }
catch (Exception e)
{
error.Add("Error",e.Message);
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["metaDescription"]))
{
error.Add("Error", "metaDescription empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["metaKeywords"]))
{
error.Add("Error", "metaKeywords empty");
return Json.Encode(error);
}
//Post was edited successfully add/update meta info
int parseResult = 0;
Int32.TryParse(result["metaID"], out parseResult);
if (parseResult > 0)//metaID is supplied
{
cmd = "UPDATE MetaInfo SET Description='" + result["metaDescription"]
+ "',Keywords='" + result["metaKeywords"]
+ "',postID='" + result["Id"]
+ "' WHERE ID='" + result["metaID"] + "';";
}
else //metaID is not supplied
{
cmd = "INSERT INTO MetaInfo (Description,Keywords,postID) VALUES('"
+ result["metaDescription"] + "','"
+ result["metaKeywords"] + "','"
+ result["Id"] + "');";
}
try
{
db.Execute(cmd);
}
catch (Exception e)
{
error.Add("Error",e.Message);
return Json.Encode(error);
}
//End Update meta info
error.Add("Success", "true");
return Json.Encode(error); //"{ \"Result\":[{\"Success\":\"true\"}]}";
}
}
#{
var result = EditPost();
}
#result
For anyone else that may have this same problem here was how I finally solved it: Just use Html.Raw(result) to send back only the json instead of extra stuff that gets added for some reason.
Can't be sure without knowing the requirements for the url. My guess would be that the data property is the reason you're off. I'm guess Post is an object defined elsewhere. When you send your request, the server will likely interpret the data field as an object not a string. Try to change {data: JSON.stringify(Post)} to just JSON.stringify(Post)
try with adding async: true, line after type: 'POST',
Problem is with your JSON response.
"{ \"Result\":[{\"Success\":\"true\"}]}";
There added slashes before double quotes(").
You can see the actual error thrown by jQuery using below updated error block:
error: function (xhr, status, errorThrown ) {
console.log(errorThrown )
Solution:
Remove slashes from your response try response like below:
'{ "Result":[{"Success":"true"}]}'
Hope this will help you.
Regards,

javascript alert in an if else statement not triggering

If the first part of the statement fails I am trying to send an alert. But I cannot figure out why the alert is not triggering. Yes, I have forced the statement to fail.
$("#btnSubmit").click(function (e)
{
if (<?php echo $browser; ?> >= 1)
{
var user = $("#ownerPost input").val();
var oid = <?php echo $Owner; ?>;
$.ajax(
{
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);
}
}
);
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}
else
{
alert("You must log in to follow");
}
}
);
Here is the output from view source:
The actual number is 56 and makes the statement true and that is correct. It is when the statement is false that it will not trigger the else and hence the alert.
If I place an alert right before the else it will show the alert because first part is true.
$("#btnSubmit").click(function (e)
{if (56 >= 1){
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data){
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);} });
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}else{alert("You must log in to follow");}});
I think you have a syntax error. I was going to suggest a try/catch, but that will not help with a syntax error. Please edit your question and put in the "view > page source" as the others have suggested. Also, can you use Firebug, or equivalent to view the console?
EDIT:
I do get the alert with this code. Note that I set browser to 0.
blah = function(e) {
if (0 >= 1) {
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type : 'POST',
url : 'follow.php',
data : "oid=" + oid,
dataType : 'json',
success : function(data) {
var id = data[0];
var name = data[1];
$('#output2')
.html("<b>id: </b>" + id + "<b> name: </b>" + name);
}
});
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
} else {
alert("You must log in to follow");
}
};
blah.call();

Categories

Resources