Allowing ampersand (&) in textarea - javascript

I googled for this but without luck.
I have a textarea in a form that I'm trying to send via ajax with jQuery. My problem is when the textarea contains ampersand (&) it breaks. That is any text contained after & will not be fetched including the ampersand (&). I am sending the data as follows:
message = "What are the concerns you are looking to address? "+othr+".\n";
var dataString = 'name=' + name + '&email=' + email + '&company=' + company + '&message=' + message + '&othr=' + othr + '&vpb_captcha_code=' + vpb_captcha_code + '&submitted=1';
$.ajax({
type: "POST",
url: "contactus-contact-form.php",
data: dataString ,
I read encodeURIComponent() and tried implementing the same but it does not work. Any pointers?
EDIT:The following fails to obtain the text values:
message = "What are the concerns or security issues you are looking to address? "+othr+".\n";
var data0 = {name: + name + email: + email + company: + company + message: + message +
othr: + othr + vpb_captcha_code: + vpb_captcha_code + submitted: "1"};
$.ajax({
type: "POST",
url: "contactus-contact-form.php",
data: data0,
contentType: "application/json; charset=utf-8",
dataType: "json",

& is the character used to separate key/value pairs in form encoded data. You need to escape it if you want to use as part of the data.
The easiest way to do that is to let jQuery take care of building the form encoded string for you. Pass an object to the data argument:
$.ajax({
type: "POST",
data: {
name: name,
email: email,
company: company,
message: message,
othr: othr,
vpb_captcha_code: vpb_captcha_code,
submitted: 1
},
// etc
If you really want to do it manually, then the encodeURIComponent function will work:
var dataString = "name=" + encodeURIComponent(name) + "&email=" + encodeURIComponent(email) // etc etc etc

i met this problem,
for a specific reason I needed to display & instead of & in a textarea.
To do so, i replaced "&" by "&"
I hope it's help

ou can resolve your problem using encodeURIComponent() function .You have just change the code as below.I think you have set the textarea value to variable othr.You can just encode this variable only using encodeURIComponent(othr).That mean You can parse the textarea value using encodeURIComponent method.
message = "What are the concerns you are looking to address? "+othr+".\n";
var dataString = 'name=' + name + '&email=' + email + '&company=' + company + '&message=' + message + '&othr=' + encodeURIComponent(othr) + '&vpb_captcha_code=' + vpb_captcha_code + '&submitted=1';
$.ajax({
type: "POST",
url: "contactus-contact-form.php",
data: dataString ,
});
or
message = "What are the concerns or security issues you are looking to address? "+othr+".\n";
var data0 = {name: + name + email: + email + company: + company + message: + message +
othr: +encodeURIComponent(othr) + vpb_captcha_code: + vpb_captcha_code + submitted: "1"};
$.ajax({
type: "POST",
url: "contactus-contact-form.php",
data: data0,
dataType: "json",

Related

How to send and retrieve information/

I have a php file saven on a different domain, and Im using this piece of code to send the username and with that get the info of the user.
Im trying to do something like this, but this is not working is there a way to do it.
var dataString = "username="+username+"";
var url = "";
$.ajax({
type: "POST",
url: url,
data: dataString,
crossDomain: true,
cache: false,
success: $.getJSON(url, function(result)
{
console.log(result);
$.each(result, function(i, field)
{
var id = field.id;
var username = field.username;
var email = field.email;
$('#profile-info').append("ID: " + id + "<br>Username: " + username + "<br>Email: " + email + "<br><br>");
});
})
});
Replace the $.getJSON() function you have for the success calback provided by the jQuery ajax function, and you can pass directly the username through the data parameter as { username : username }, because it's already defined.
Then when you receive successfully your data you can iterate over each result using the jQuery $.each function.
Do you really need to set the cache parameter to false?, just to know.
Also if you want use let instead of var, those variables will be just within the $.each "block".
<script>
var url = '';
$.ajax({
type: "POST",
url: url,
data: { username: username },
crossDomain: true,
cache: false,
success: function(result) {
console.log(result);
$.each(result, function(i, field) {
let id = field.id,
username = field.username,
email = field.email;
$('#profile-info').append("ID: " + id + "<br>Username: " + username + "<br>Email: " + email + "<br><br>");
});
}
});
</script>

Using jquery ajax vs native xhr

I'm not too familiar with JQuery, and I'm trying to make a post request using jquery ajax.
I was previously using xhr, and I'm not totally sure if I'm reworking it correctly. If someone could give me some feedback, that would be greatly appreciated!
Here is my original code with xhr:
j("#saveButton").click(function() {
var ID = j(".selected-list")[0].getAttribute('id');
var subject = j('input').val();
var blurb = j("#blurb_stream").val();
var date = j('datepicker').val();
if(blurb.length != '' && ID != undefined && subject.length != ''){
xhr.open("POST", envUrl + "streams/" + ID + "/touches?subject=" + subject + "&body=" + blurb + "&schedule_on=" + date, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log('saved!');
} else {
alert('not working');
}
}
xhr.send();
}
});
Here is my adjusted code using ajax:
j("#saveButton").click(function() {
var ID = j(".selected-list")[0].getAttribute('id');
var subject = j('input').val();
var blurb = j("#blurb_stream").val();
var date = j('datepicker').val();
var data = new FormData();
data.append("date", "date");
data.append("ID", "ID");
data.append("subject", "subject");
data.append("blurb", "blurb");
// check this!
if(blurb.length != '' && ID != undefined && subject.length != ''){
j.ajax({
url: 'envUrl + "streams/" + ID + "/touches?subject=" + subject + "&body=" + blurb + "&schedule_on=" + date',
type: "POST",
data: data,
success: function(){
alert(1);
}
});
}
}
Way too complex. With JQuery AJAX is slim. Here I replace all data.append() with an inline object. I've also removed the query string because it's the same information as in the data block. I've also fixed the URL line, which has some misplaced quotes:
j.ajax({
url: envUrl + "streams/" + ID + "/touches",
type: "POST",
data: { "date": date, "ID": ID, "subject": subject, "blurb": blurb },
success: function () {
alert(1);
}
});
From here you can replace the date/ID/subject/blurb with your fetch methods. Example:
j.ajax({
url: envUrl + "streams/" + ID + "/touches",
type: "POST",
data: {
"date": j('datepicker').val(),
"ID": j(".selected-list")[0].getAttribute('id'),
"subject": j('input').val(),
"blurb": j("#blurb_stream").val()
},
success: function () {
alert(1);
}
});
The whole script is now:
j("#saveButton").click(function () {
j.ajax({
url: envUrl + "streams/" + ID + "/touches",
type: "POST",
data: {
"date": j('datepicker').val(),
"ID": j(".selected-list")[0].getAttribute('id'),
"subject": j('input').val(),
"blurb": j("#blurb_stream").val()
},
success: function () {
alert(1);
}
});
});
You have a mistake in your url param, try taking the single quotes out:
j.ajax({
url: envUrl + "streams/" + ID + "/touches?subject=" + subject + "&body=" + blurb + "&schedule_on=" + date,
type: "POST",
data: data,
success: function(){
alert(1);
}
});
Also, a little bit of background on using HTTP requests.
In general there are two primary ways of passing data to the server. One method is via URL params, in this case it would be a GET request, and you pass the params on the query string (like you've done in your URL).
The other way is via POST. With the POST verb, you pass data in the body of the request in a delimited format. In this case, you would provide the ajax call with the data: param. Doing both is redundant.
Following best practices, you shouldn't use a GET request to modify data (except in some rare circumstances). If you're modifying data, you should use a POST, PUT, PATCH or other verb.

Javascript url 404 error

I'm have a problem loading a site. Using this code:
$.ajax({
type: "POST",
//url: '#Url.Action("/TellFriendPopup")',
url: '/Property/TellFriendPopup',
data: { "SenderName": SenderName, "senderMail": senderMail, "receiverMail": receiverMail, "comments": comments, "urlLink": urlLink, "subjectId": subjectId },
success: function (data) {
$("#result").html("<ul><li>Name: " + data.nameret + "</li><li>Email: " + data.emailret + "</li><li>Message: " + data.messageret + "</li></ul>");
$(".dialog").dialog("close");
},
The problem is that I had to move the code to a JavaScript file, instead of the MVC4 View, where i could use the #Url.Action method. But it is not working in JavaScript. It Just gives me this error POST http://localhost:54717/Property/ContactPopup 404 (Not Found). The reason as I can see is that it's the Globalization that it's missing. Because the url should look like this http://localhost:54717/da/Property/ContactPopup or http://localhost:54717/en/Property/ContactPopup
You could get the first folder of the pathname. As long as that is where the language code is on every page.
var language = location.pathname.split("/")[1];
url: language + '/Property/TellFriendPopup'
You can have language in hidden field.
var language = document.getElementById('language`).value;
url: '/' + language + '/Property/TellFriendPopup'
Can you try changing this: url: '/Property/TellFriendPopup',
to this url: '../Property/TellFriendPopup',

$ajax is not working with ASP.Net

I am debugging my solution on localhost and this piece of code is not hitting the server
var cartInfo = $j("#ctl00_BaseContentPlaceHolder_ctl00_updateShoppingCart").html();
var dataString = 'name=' + name.val() + '&email=' + email.val() + '&phone=' + phone.val() + '&date=' + date.val() + '&cart=' + cartInfo;
$j.ajax({
type: "POST",
url: "LightBoxContactSender.aspx",
data: dataString,
success: OnSuccess,
error: OnError
});
What am I missing here?
the are 2 potential problems
the url
the data
aspx assumes webforms, the page life cycle, etc. when all you want is to send response and get a reply. instead try targeting either a
web service (asmx)
generic handler (ashx)
a static pagemethod think ajax server hanlders embedded within a page object
second is the data. instead of passing a string as the data try passing a json object
data = {
name: "john",
email: "john#email.com",
...
}
Since you are passing the cartInfo as an html, it should be url encoded before it is posted. I think this is wat causing this issue. Try this
var cartInfo =
$j("#ctl00_BaseContentPlaceHolder_ctl00_updateShoppingCart").html();
var dataString = 'name=' + name.val()
+ '&email=' + email.val()
+ '&phone=' + phone.val()
+ '&date=' + date.val()
+ '&cart=' + encodeURIComponent(cartInfo);
$j.ajax({
type: "POST",
url: "LightBoxContactSender.aspx",
data: dataString,
success: OnSuccess,
error: OnError
});
As suggested by in other answer you can also pass data as a key/value pair object to ajax method, jQuery will take care the rest but you still have to encode the html content.
Url Doesnt call any method ?
url: "LightBoxContactSender.aspx",
If yoy are trying to call a WebMethod inside aspx
url :"LightBoxContactSender.aspx/callStaticMethod",
Try to form Data as
dataString = "{'name=' + '"+name.val()+"'}"

Post Forms Using Javascript URL

I'm trying to submit a form to a website not my own (salesforce.com with their web-to-lead function) and I'm doing it through a javascript modal window.
Basically once all the entries are tested and made sure there are no errors, I use this:
if(error_count == 0) {
$.ajax({
type: "POST",
url: "[salesforce url]",
data: "first_name=" + first_name + "&last_name=" + last_name + "&email=" + email + "&firm=" + firm + "&[salesforceid]=" + AUM + "&[salesforceid]=" + custodian + "&[salesforceid]=" + custodian_other,
error: function() {
$('.error').hide();
$('#sendError').slideDown('slow');
},
success: function () {
$('.error').hide();
$('.success').slideDown('slow');
$('form#callToAction').fadeOut('slow');
}
});
}
If tested the form without using javascript and the url works, so I'm thinking maybe the way javascript handles the url is the issue?
The issue: the data is not getting successfully submitted to Salesforce. Again, regular HTML form works, javascript doesn't. So I've identified it as a javascript issue.
You cannot make a XHR cross domain request unless the receiving server has allowed it and the browser supports CORS. You can however do a blind submit like this which will assume success:
var $form = $("<form>", {
method: "POST",
action: "[salesforce url]",
target: "my-iframe"
}).appendTo("body");
var $iframe = $("<iframe>", {
name: "my-iframe"
}).bind( "load", function () {
$('.error').hide();
$('.success').slideDown('slow');
$('form#callToAction').fadeOut('slow');
$iframe.remove();
$form.remove();
}).appendTo("body");
$.each(("first_name=" + first_name + "&last_name=" + last_name + "&email=" + email + "&firm=" + firm + "&[salesforceid]=" + AUM + "&[salesforceid]=" + custodian + "&[salesforceid]=" + custodian_other).split("&")), function (index, value) {
var pair = value.split("=");
$form.append("<input>", {
type: "hidden",
name: pair[0],
value: pair[1]
});
});
$form.submit();
+1 for Jim Jose. This sort of thing could be interpreted as an XSS attack against the user, so most likely the browser will not allow it.
You could check out your browser's error logs, see if there's any security errors when you try to run your script. If that doesn't do anything, try to install a tool like Firebug and see if it can pinpoint the problem.
You could also improve your error handling by trying a different sort of method signature for the error function, like this:
error: function(jqXHR, textStatus, errorThrown) {...}
This way you can check what sort of error is being thrown from the Ajax call.

Categories