firebug: "no element found" error when doing a jquery ajax call to an ashx handler - asp.net

Each of my calls to an ashx handler is causing me to get the "no element found" error in Firefox but my website does not crash when performing calls to that handler. I also get a "HierarchyRequestError:Node cannot be inserted at the specified point in the hierarchy". Below is the code that is giving me those two errors:
$.post("checkout_model.ashx?a=CheckSession", function (data) {
// if session is still available
alert(data);
if ($.trim(data).length > 0) {
$.post("checkout_model.ashx?a=SaveAddress", $("#addressdetails").serialize(), function (data) {
$("#addressresult p.result").remove();
$("#addressresult").prepend(data);
});
storeCookies();
// update orderdetails
$.post("checkout_model.ashx?a=GetCartContent", function (data) {
$("#orderdetails").html(data);
});
var address = $("#AddressLine1").val();
if ($("#AddressLine2").val() != "") address += ", " + $("#AddressLine2").val();
address += ", " + $("#Suburb").val();
$("#tabaddress").text("Step 1: Modify Address: " + address);
$("#accordion").accordion("option", "active", 1);
$("#tabaddress").addClass("modifyaddress");
$("#tabpayment").removeClass("disabled"); // enable step 3
} else {
$("#addressdetails").html("<p class='error'>Your order has timed out. You will need to <a href='viewcart.aspx'>select the items</a> to purchase again.</p>")
}
});

If your ajax response includes a "Content-Type" header with the value "text/xml", Firefox expects the response to be valid XML with a single root element. If it is not, Firefox issues the "no element found" error.
As for the second error, it may be that in either of the following lines the value of "data" is not valid HTML or contains tags like <html> or <body>:
$("#addressresult").prepend(data);
$("#orderdetails").html(data);

Add the responseType request.
var xhr = new XMLHttpRequest();
xhr.open('POST', '...', true);
xhr.responseType = 'json';
See this for more details:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType

Related

angular2 http delete

I use http.delete for remove my data.
This code in my service [MyService]:
deleteData(id){
let headers = new Headers(),authtoken = localStorage.getItem('token');
headers.append("Authorization", 'Bearer' + authtoken);
headers.append('X-Requested-With', 'XMLHttpRequest')
headers.append('Content-Type', 'application/json;')
return this.http.delete('http://link/'+id, { headers: headers })
.map((resp:Response)=>resp.json())
.catch((error:any) =>{return Observable.throw(error);});
}
This code in my component:
private delete(id):void{
console.log(id); //show`s id
this.myService.deleteData(id)
.subscribe((data) => {console.log(data)});
}
Show`s error "caused by: A network error occurred". My mistake was elsewhere. It is work.
There is nothing wrong in your code what i can see and you are not getting any error from server either. Try to call the same end point from postman and match the headers and check your Internet connection.

Beego POST request body always empty

I'm working with Beego's convenience methods for parsing request body values and have the following:
Router file:
apiNamespace := beego.NewNamespace("/api")
apiNamespace.Router("/sessions/google/new", &controllers.SessionsController{}, "get:GoogleNewSession")
beego.AddNamespace(apiNamespace)
Controller code:
func (c *SessionsController) URLMapping() {
c.Mapping("GoogleNewSession", c.GoogleNewSession)
}
func (c *SessionsController) GoogleNewSession() {
// Always serve JSON
defer func() {
c.ServeJson()
}()
// This is always blank
log.Printf("'Received %+v'", c.Ctx.Input.RequestBody)
c.Ctx.ResponseWriter.WriteHeader(200)
return
// truncated
}
Front end JS (super-agent):
request
.post('/sessions/google/new')
.use(prefix)
.send({ code: authCode })
.set('Accept', 'application/json')
.end(function(err, res){
console.log("******* request", res.request)
if (res.ok) {
var body = res.body;
console.log('yay got ' + JSON.stringify(res.body));
} else {
console.log("***** err", err);
console.log("***** not ok", res.text);
}
});
When the superagent request fires off, I can see in the logs that the path is getting correctly matched. However, the c.Ctx.Input.RequestBody is always empty.
I have tried using something else to fire the request such as Postman but to no avail. In GET requests I am able to retrieve query params correctly.
Any clues or suggestions to help fix or debug this issue?
You need to configure "copyrequestbody = true" in configuration file "conf/app.conf".
The default is false so the content is not copied to c.Ctx.Input.RequestBody.
The example is shown section "Retrieving data from request body" in the document. (http://beego.me/docs/mvc/controller/params.md)

Router.url() returning undefined in Email.send()

I am trying to construct an email for some users. Code is running server-side. In the email I would like to have a link for the users to click on, but I am not having much luck.
I am trying to use Router.url() to set the href of an anchor. I can do console.log() and see the Router object is at least defined, but the link ends up being strange.
The code looks like this:
Meteor.methods({
sendSubmissionEmail: function(responseId) {
// Let other method calls from the same client start running,
// without waiting for the email sending to complete.
this.unblock();
var formResponse = FormResponses.findOne({_id: responseId});
var toEmails = [];
_.each(Roles.getUsersInRole('ADMIN').fetch(), function(user) {
if (user.profile && user.profile.receivesResponseEmails) {
var email = _.findWhere(user.emails, {verified: true});
if (!email) {
console.log('No verified email address was found for ' + user.username + '. Using unverified email instead.');
email = _.first(user.emails);
}
if (email) {
toEmails.push(email.address);
}
}
});
if (toEmails && toEmails.length > 0) {
console.log('Sending an email to the following Admins: ' + toEmails);
console.log('Router: ', Router);
Email.send({
from: 'noreply#strataconsulting.us',
to: toEmails,
subject: 'Form Response for Form "' + formResponse.form_title + '" Ready For Approval',
html: '<p>Form Response for Form ' + formResponse.formTitle + ' is now ready for your approval.</p>'
});
}
}
});
And the resulting email:
====== BEGIN MAIL #0 ======
MIME-Version: 1.0
From: noreply#strataconsulting.us
To: testuser4#codechimp.net
Subject: Form Response for Form "undefined" Ready For Approval
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable
<p>Form Response for Form Test Form One is now ready for your approval.</p>
====== END MAIL #0 ======
First, there is a strange "3D" appearing prior to the first " of the href, then the return or Router.url() is always undefined. Just to make sure the call was right, I simulated it in Chrome's dev tools console by doing the following:
var fr = FormResponses.findOne({_id: '1234567890'});
Router.url('editResponse', fr);
As expected this spits out the full URL path to my editResponse route with the correct ID set. Is Router.url() a client-only call? If so, how do I get the URL to a route server-side? All routes are defined for both client and server.
Here:
var fr = FormResponses.findOne({_id: '1234567890'});
Router.url('editResponse', fr);
You're passing the result of the Find as a parameter. It'll look like
{ _id: ..., otherStuff: ...}
But in your code you're not passing an object, you're just passing a string:
Router.url('editResponse', formResponse.id)
That explains the "undefined".
The 3D is very odd.

upload image with data to server Titanium

i have some data i need to upload it to the server with an image using
multipart/form-data
but i getting request time out this is my data
var data={
property_name:p_n_txt.value,
friendly_name:f_txt.value,
property_type:clicked,
size:space_Slider.getValue(),
price:price_Slider.getValue(),
number_of_bedrooms:bedrooms_Slider.getValue(),
number_of_bathrooms:bathrooms_Slider.getValue(),
number_of_parkings:p_space_Slider.getValue(),
location:a_txt.value,
features:13,
payment_method:4,
image1_name:"image0.png",
image1:Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory,Ti.App.Properties.getString("filename")),
};
and the httpclient is
var xhr = Ti.Network.createHTTPClient({
onload: function() {
var myData = JSON.parse(this.responseText);
console.log(this.responseText);
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e.error);
console.log(this.status);
console.log(e.error);
},
timeout : 20000
});
xhr.open('POST','http://url/');
xhr.setRequestHeader("enctype", "multipart/form-data");
xhr.setRequestHeader("Content-Type", "image/png");
// xhr.setRequestHeader("Content-Type", "image/jpeg");
xhr.send(data);
});
here is should form data not a json so there is no need to add json.stringify
but i have 4 cases i tried with them
first :with stringify i got HTTP 415 if i added contentType "image/png"
and HTTP 500 if i didn't added
second without stringify when i add added contentType "image/png" i got request time out
and when i didn't add it i get HTTP 413
any idea on how to accomplish this cause i found many question about it but no one was helpful for me
thanks
Why don't you try with encoding your image as base64encoded and pass it on and at the server end just decode it and you would be go enough to proceed.
Ti.Utils.base64encode(image.toBlob()).toString();
This can be sent to server and no headers would be required to sent.

Problem catching errors occured in jquery ajax method

I am using jquery ajax method on my aspx page to call a web method in the code behind.If the call fails,for any reason I would like to catch the error and display a meaningful message to the user.Following is my jquery ajax method code.
$.ajax(
{
type:"POST",
url:"Default.aspx/createitem",
data:JSON.stringify({question : question, answer : ans, url : url, category : cat, maincat : maincat, validfrom : validfrom, validuntil :validuntil}),
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function(msg)
{
alert(msg.d);
//success code goes here
},
Error:function(xhr, status, error) {
// Boil the ASP.NET AJAX error down to JSON.
var err = eval("(" + xhr.responseText + ")");
// Display the specific error raised by the server (e.g. not a
// valid value for Int32, or attempted to divide by zero).
alert(err.Message);
}
});
But in case of any error like 'missing parameter' or something neither the success function nor the error function is getting executed an I had to check the response in firebug.Please could someone tell me what am I doing wrong?
Thanks.
Error:
should be
error:
lowercase

Resources