Send AJAX data while adding MANUAL line breaks - ajax

I am fetiching data from a form and send it out as a mail. This works fine so far, but currently the result appears on one line and I would love to have a line break between these two rows.
So insted:
User: Max Mustermann Recipient: Karl Gunter
it should read
User: Max Mustermann
Recipient: Karl Gunter
I have tried \r\n as well as <br> but nothing changed. What am I doing wrong?
$("#submit").on("click", function () {
var user = encodeURIComponent("User: " + $("#username").val() + "\r\n");
var recipient = encodeURIComponent("Recipient: " + $("#recipient").val() + "\r\n");
$.ajax({
url: "/SendMail",
type: "post",
data: "subject=Test" + "&body=" + user + recipient,
}).done(function (response) { ... });
});

You're the one adding the line breaks so you know they're safe. Does it work to not encode the line breaks?
var user = "User: " + encodeURIComponent($("#username").val()) + "\r\n";
var recipient = "Recipient: " + encodeURIComponent($("#recipient").val()) + "\r\n";
Or change \r\n to an HTML break.

Related

HTML5 Post Request Body

function sendPost(){
alert("IN SEND POST");
var username = document.myForm.username.value;
var password = document.myForm.password.value;
alert("username"+username);
alert("password"+password);
console.log("in java script");
var url = "some url";
alert("IN url SEND POST");
var data = "<MESSAGE><HEADER><LOGIN>005693</LOGIN></HEADER><SESSION><LATITUDE>0.0</LATITUDE><LONGITUDE>0.0</LONGITUDE><APP>SRO</APP><ORG>MNM</ORG><TRANSACTION>PRELOGIN</TRANSACTION><KEY>PRELOGIN/ID</KEY><TYPE>PRELOGIN</TYPE></SESSION><PAYLOAD><PRELOGIN><ID>005693</ID><USERNAME>005693</USERNAME><PASSWORD>tech#2014</PASSWORD></PRELOGIN></PAYLOAD></MESSAGE>";
console.log("2")
var req;
if(window.XMLHttpRequest) {
console.log("2");
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
}
else if(window.ActiveXObject) {
console.log("3");
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
console.log("4");
req.onreadystatechange=function()
{
console.log("5");
if (req.readyState==4 && req.status==200)
{
console.log("ready state accepted");
xmlDoc=req.responseXML;
console.log("xmlDoc"+xmlDoc);
alert("xmlDoc"+xmlDoc);
txt="";
x=xmlDoc.getElementsByTagName("FIRSTNAME");
y=xmlDoc.getElementsByTagName("LASTNAME");
console.log("Response achieved"+x);
}
}
req.open("POST",url,true);
console.log("6");
req.setRequestHeader("Content-type","application/xml");
req.send(data);
console.log("7");
return true;
}
I get a response in rest client perfectly as i Want as seen in image
In Google Chrome --> I get status as 0 and ready state as 1 and then 4
In Internet Explorer --> I get status as 200 OK and ready state goes from 1 , 2, 3, 4 but a blank xml is returned
In rest client I get a perfect hit and an xml is returned
I tried asking question in different ways but some say its a cross origin problem
If yes please lemme know the solution via code in javascript
Please guide
Firstly, I suggest rewriting your code with jQuery's help. This would compact your code, make it cross-platform, and easier to read and maintain:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function sendPost(){
$.ajax({
url: "some url",
type: "POST",
contentType: "text/xml",
data:
"<MESSAGE><HEADER><LOGIN>005693</LOGIN></HEADER>" +
"<SESSION><LATITUDE>0.0</LATITUDE><LONGITUDE>0.0</LONGITUDE>" +
"<APP>SRO</APP><ORG>MNM</ORG><TRANSACTION>PRELOGIN</TRANSACTION>" +
"<KEY>PRELOGIN/ID</KEY><TYPE>PRELOGIN</TYPE></SESSION>" +
"<PAYLOAD><PRELOGIN><ID>005693</ID>" +
"<USERNAME>" + $("#username").val() + "</USERNAME>" +
"<PASSWORD>" + $("#password").val() + "</PASSWORD>" +
"</PRELOGIN></PAYLOAD></MESSAGE>",
dataType: 'xml',
success: function(data) {
var firstname = $(data).find("FIRSTNAME").text();
var lastname = $(data).find("LASTNAME").text();
alert('Hello ' + firstname + ' ' + lastname);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});
}
</script>
Secondly, a javascript that origins from your server (e.g. www.myserver.com) can't communicate with other servers (i.e. you can't request data from www.anotherserver.com). Well you CAN, but if so you'd need to ensure the answer sent from www.anotherserver.com would be in JSONP format - and then you would just change "dataType" in the example above to "jsonp" to be able to access the result like "data.firstname" and "data.lastname".
Anyway, in your case I would create a local proxy on my own webserver (in the same folder where you have the above .HTML-file) that would forward the request to the other server and return the result. Thus:
$.ajax({
url: "myproxy.php",
type: "POST", ...
And then in myprox.php, something like this (I'm just assuming PHP here, but this could be easily ported to ASP.NET or ASP Classic):
<?php
// myproxy.php forwards the posted data to some other url, and returns the result
$clientContext = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: text/xml; charset=utf-8',
'content' => http_get_request_body()
)
));
print file_get_contents("some url", false, $clientContext);
?>
To clarify: This would make your HTML-page talk to myproxy.php (which lives on the same server [even in the same directory]), then myproxy.php talks to the server at "some url" which returns the data to myproxy.php, which in it's turn returns the data to your script.
Best of luck!
The server says it is sending text/plain data, not XML, so the browser won't populate req.responseXML. The data should be in req.responseText.
I'm not sure but can you please add a semicolon (;) at the end of the line below. There is a possibility that it doesn't work because of missing semicolon.
console.log("2")
change to
console.log("2");

Error while posting photo through facebook api only on IE9

This is a javascript function to make an upload of a photo to facebook, via facebook api.
It works everywhere, except in Internet Explorer 9
var sTagsPostcard =
'[{tag_uid:' + sIdProfile + ',x:' + aPositonsTags[sIdLayoutPostcard][0] + ',y:' + aPositonsTags[sIdLayoutPostcard][1] + '},' +
'{tag_uid:' + sIdFriend + ',x:' + aPositonsTags[sIdLayoutPostcard][2] + ',y:' + aPositonsTags[sIdLayoutPostcard][3] + '}]';
var the_url = $('input[name="hdnDomain"]').val() + 'media/postcards/' + sPathPostcard
$.ajax({
type: "POST",
url: "https://graph.facebook.com/" + sIdProfile + "/photos",
data: {
message: 'MESSAGE',
url: the_url,
format: "json",
access_token: sToken,
tags: sTagsPostcard
},
success: function(data){
if($('html').hasClass('touch'))
$('form[name="frmCustomLayout"]').submit();
else
window.parent.location.href = 'https://apps.facebook.com/[APPLICATION_NAME]/?st=' + N_STEP_THANKS;
},
error:function(a,b,c){
if($('html').hasClass('touch')){
$('input[name="st"]').val(N_STEP_RESULT);
$('form[name="frmCustomLayout"]').submit();
}
else
window.parent.location.href = 'https://apps.facebook.com/[APPLICATION_NAME]/?st=' + N_STEP_RESULT;
}
});
The execution enters the error() and not the success() function, and those are the parameters a,b,c:
a: object error (or sth like that)
b: error
c: no transport
Any ideas for IE9?? thanks in advance
The javascript ajax calling the graph.facebook api it seems not to work in browsers like IE9 / IE8.
The trick to solve it was to make an ajax call to a local script, and through that use the facebook api to do the same post.
In this way in all browsers the posting is working,

ajax jquery an empty error callback on success server operation

I make an ajax call:
$.ajax({
url: 'Login.aspx/AuthenticateRegularUser',
type: 'POST',
contentType: 'application/json; charset=utf-8',
async: true,
dataType: "json",
data: '{ "emailAddress": "' + emailAddress + '","password": "' + password + '","verificationCode": "' + verificationCode + '" }',
success: function(Result) {
if (Result != "") {
var ClientResponse = JSON.parse(Result.d);
if (ClientResponse.Success) {
//DO SUCCESS
}
else {
//DO FAIL
}
}
},
error: function(xhr, textStatus, errorThrown) {
//DO ERROR
}
});
Most of the times everything is working fine, and I get success callback.
But one of my clients has a problem that sometimes the operation completed successfully on the server, but I get an error callback with an empty error.
jqXHR is empty, textStatus = "" and null errorThrown.
any idea why?
Could it be the different type of browser?? Could be an IE related issue. Maybe ask the client to use firefox instead.
Could be IE interpret javascript differently to firefox, I had similar sort of issue before at work. Microsoft always try to have its own standard for javascript, html, css. Also check data: '{ "emailAddress": "' + emailAddress + there are seems to have too many Quotation mark.
Thanks
Try, need to remove ' infront of data and syntax like as mentioned below
data: { "emailAddress": emailAddress, "password": password, "verificationCode": verificationCode },
instead of
data: '{ "emailAddress": "' + emailAddress + '","password": "' + password + '","verificationCode": "' + verificationCode + '" }',
Ref: http://api.jquery.com/jQuery.ajax/

CRM 2011 json data.d.results undefined but URL shows data

I'm trying to do a simple odata query and the call is successful, but the results are always undefined. I've thrown the URL into the description, copy and pasted it, and it works just fine. I've tested dozens of different ways to see what the object is, and the results are undefined. What am I missing??
UPDATE: As mentioned below, part of the problem was referencing data.d.results. When I referenced data.d.results[0], I actually got the error message "Unable to get property '0' of undefined or null reference." I wanted to add that here because I found almost NO help when searching for that error message.
The final answer was a combination of:
data.d for only one result
correct casing for system fields; "resProd.Description" as opposed to "resProd.description."
Back to orig Question:
Below is the code I'm using:
function setOPDefaults() {
// Create lookup
var lookupItem = new Array();
lookupItem = Xrm.Page.getAttribute("productid").getValue();
if (lookupItem != null)
{
var guid = lookupItem[0].id;
}
var crmOrg = window.location.pathname.split('/')[1];
var serverUrl = window.location.protocol + "//" + window.location.host + (crmOrg == 'userdefined' ? '' : '/' + crmOrg);
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var ODATA_PREP = serverUrl + ODATA_ENDPOINT;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
// Tried both of the following URLS (obviously not at the same time)
url: ODATA_PREP + "/ProductSet(guid'" + guid + "')",
url: "http://crm/<<orgname>>/XRMServices/2011/OrganizationData.svc/ProductSet(guid'67BA90A3-39D8-E211-8D1E-0050569A6113')",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
var resProd = data.d.results;
alert(resProd.length); // This is undefined
// Below is where I load the URL into description just for testing.
// When I copy and paste this URL into the browser, it pulls up results with correct data
Xrm.Page.getAttribute("description").setValue(ODATA_PREP + "/ProductSet(guid'" + guid + "')");
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Ajax call failed: " + textStatus + " - " + errorThrown + " || " + XmlHttpRequest.responseText);
}
});
}
You're acessing just one record, so try put something like that:
data.d
data.d.results is used for multiple results. Another thing you can do to validate the results is put your url directly in browser.
In such cases, I use Fiddler. You can use it to debug your http/https trafic.
Or. If you have crm 2011 RU 12, you can use built-in Chrome debugger. Press F12. In console tab - right click -> Log XMLHttpRequest

Django, CRSF Token , POST REQUEST. Works on browser however not on mobile phone

As question is being asked in the header.
I'm trying to be more specific here then, pardon my English.
I'm currently working on a jquerymobile website with django on openshift.
I had a login page which uses ajax and sending post request. I've did something like.
var account = '{"Email" : "' + username + '" , "Password" : "' + password + '"}';
$.ajax({
url: "/Account/Login",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
},
type: "POST",
data: { "account" : account },
success: function(data) {
var obj = eval("(" + data + ")");
if (obj.Status == "100")
{
if(typeof(Storage)!=="undefined")
{
sessionStorage.user = username;
window.location = "/";
}
}
else if (obj.Status == "101")
{
invalid parameters sent.
}
else if (obj.Status == "102")
{
email doesnt exist / email & password pair doesn't match.
}
},
});
Basically the obj.Status is a json reply with Status & Message. username and password are inputs by user. I've also tried by using putting data sent the csrfmiddlewaretoken and it's the same result.
So any solutions? By the way I'm testing it on iPhone 4S and Google Chrome. Thanks in advance people :)
Add {% csrf_token %} inside your template page.
In Javascript:
var input = document.getElementsByName('csrfmiddlewaretoken')[0]
var csrftoken = input.getAttribute('value');
And csrfmiddlewaretoken: csrftoken into your POST request data
On the view instead use the #ensure_csrf_cookie decorator from django.views.decorators.csrf

Resources