ajax field insert without loading second page bug - javascript

So I went through this tutorial http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/ and instead of using php I created my own classic asp page, but one thing is bugging me when trying to put spaces in the input boxes they do not show up for example if I put bill gates in the name field it shows up as billgates
any ideas
$(".btn22").bind("click", function() {
var name = $("input#yourname").val();
if (name === "") {
$("input#yourname").focus();
return false;
}
var email = $("input#youremail").val();
if (email === "") {
$("input#youremail").focus();
return false;
}
var message5 = $("#limitedtextarea").text();
if (message5 === "") {
$("#limitedtextarea").focus();
return false;
}
var sku5 = $("#sku5").val();
var dataString = 'yourname='+ name + '&youremail=' + email + '&message=' + message5 + '&sku5=' + sku5;
$.ajax({
type: "POST",
url: "actions/newreview.asp",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<br><br><p class='big red'>Thanks for the review.</p>")
.hide()
.fadeIn(1500, function() {
$('#message');
});
}
});
return false;
});
});
'asp looks like this
name = request.form("yourname")
email = request.form("youremail")
sku = request.form("sku5")
comment = request.form("message")
then inserts names into a database, but it has already gotten rid of the spaces before this point

You'll have to post your markup here for us to tell what's going on for sure, but have you set the input type to type='text'?

looks like you are doing your own encoding of the form data. Not sure if that's the problem but it could be. jQuery includes a utility that does this for you.
dataString = $("#JqAjaxForm").serialize();
reference: http://api.jquery.com/serialize/
Some other comments:
you may wish to produce a javascript object, rather than just use form encoding. In this case jQuery will serialize it into json, if you use dataType:json on the post() method.
use Javascript in your classic ASP page. It may make things a little simpler for you, to use the same language on client (browser) and server.

figured it out just added name = escape(name) add the %20 in and then take it out to add spaces in my asp code
thanks everyone

Related

AJAX POST of tinyMCE contents - Character encoding of table entities

I'm using the tinyMCE editor plugin in my webpage.
When I use a simple HTML page post to post the contents to the backend PHP and save them to a database or file, all seems OK.
When I try to do the same using an AJAX post, I am finding it impossible to prevent encoding issues.
In particular (I'll escape it here) \&\n\b\s\p\; is being converted to  and a "-" character is being converted to �
I've tried a few suggestions but with little luck.
The suggestion is that it is either an issue with my charset or encoding.
My save function is as follows:
function letterSave(newfile,fname){
var newDate = new Date;
var uniq=newDate.getTime();
var input = $('#myTextareastdletter');
var contents=input.val();
var context='<?=(!strcmp($sessobj->mode,"SA_ViewAbs")?"A":"S");?>';
// alert(fname);
$.ajax({
type: "POST",
url: '<?=auto_version("./SVajaxSaveDocContents.php")?>?duff='+uniq,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {'S_sessid' : '<?=$sessobj->sessionid?>', 'context' : context, 'contents' : encodeURIComponent(contents), 'fname' : fname, 'newfile' : newfile},
success: function(data){
data = JSON.parse(data);
fname=data[0];
newLetterList=data[1];
if (fname != 'FAIL') {
alert ('OK: Letter Contents Saved to File ('+fname+').');
var versionOutput = $('#popupOutput');
versionOutput.html('');
var box = $('#popupDisplay');
var cover=$('#coverDiv');
box.css({
display:"none"
});
cover.css({
display:"none"
});
var letterOutput = $('#AbsenceLetters');
letterOutput.html(newLetterList);
} else {
alert ('Sorry: Failed to Save Letter Contents!');
}
},
error: function(data){
alert ('Sorry: Failed to Save Letter Contents!');
// console.log(data);
// console.log('error');
}
});
}
As you can see, I've been playing with setting the contentType and using encodeURIComponent().
Any help would be appreciated.
Cheers
In order to avoid these encoding issues, don't use .val on the textarea that the tinyMCE instance is attached to. Instead, you can utilize tinyMCE's built-in getContent method like so:
tinyMCEInstance.getContent()

Javascript value cuts off after '&' character

So I'm relatively new with Javascript and Ajax, and using them to submit data to the database for live updating, but I'm noticing that when there is a '&' character entered into my input/textareas, when I gets the value, it cuts the string off after the '&'.
I've tested the value by using the alert function after the lines of code below, and the full string is there, but not exactly sure how to fix this.
I tried to replace the '&' character with & but can't get it to work. Here is what I used to get the values and the replace I tried to use. Note: I'm using the nicEditor and have to use the first line of the code to get the text from the proper field that stores the text inside the editor.
var boxval = $('#statusContentForum').find('.nicEdit-main').text();
var dataString = 'statusContent='+ boxval;
var dataString = dataString.replace(/&/g, '&');
var dataString = dataString.replace(/\|&;\$%#"<>\(\)\+,/g, "");
and used these characters to test it.
abcdefghijklmnopqrstuvwxyz 1234567890-=`~!##$%^&*()_+{}[]|\"':;,<.>?/
but it only results in this
abcdefghijklmnopqrstuvwxyz 1234567890-=`~!##$%^
Have any of you encountered this before? I'd appreciate any help, and if you need more code let me know. I can provide it.
*********UPDAT FULL CODE *********
Here is the full code.
The JS/AJAX:
$(function() {
//Update Message...
$(".update_button").click(function() {
//var boxval = $("#statusContent").val();
var boxval = $('#statusContentForum').find('.nicEdit-main').text();
var dataString = 'statusContent='+ boxval;
//var dataString = dataString.replace(/>/g, '>');
//var dataString = dataString.replace(/</g, '<');
var dataString = dataString.replace(/&/g, '&');
var dataString = dataString.replace(/\|&;\$%#"<>\(\)\+,/g, "");
if(boxval=='') {
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
// alert(dataString);
// throw new Error("Something went badly wrong!");
$.ajax({
type: "POST",
url: "ajax/statusPost.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").prepend(html);
$("ol#update li").slideDown("slow");
var clearVal = nicEditors.findEditor("statusContent");
clearVal.setContent("");
$("#flash").hide();
}
});
} return false;
});
});
The HTML if you need it.
<form name="newstatus" id="statusContentForum" action="profile.php" method="post" class="commentForm">
<textarea name="statusContent" id="statusContent" placeholder="What's on your mind?"></textarea>
<input type="submit" value="Update" name="submit" class="update_button"/>
</form>
You are manually constructing an application/x-www-form-urlencoded string, but aren't encoding & correctly. To represent a & as data in that format you need to replace it with %26.
The encodeURIComponent function will do this for you.
However, you are using jQuery so you shouldn't do it manually at all. Pass data an object instead of a string.
data: {
statusContent: boxval
},
I'm assuming you're familiar with other programming languages, and perhaps even key words or sensitive characters. Always remember to look into that as a first solution to your issue. In this case, that's what was going on. If you encode the string for that variable you're setting it should work just fine.
Try console logging it.
console.log(encodeURIComponent('My Var: ' + dataString));
See here for more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

simple form validation with jquery serialize() function

$(document).ready(function(){
$('#send').click(function() {
var names = $('#appontment_form').serialize();
//this is how my names variable look like
//doctor=Dr.Fathmath+Shahuda&date=2013-02-27&time=1900+-+1700&phone=
var doc = $(names).filter('doctor');
if(doc !='')
{
$.ajax({
type: "post",
url: "../../includes/jqueryRequireFiles/appointmentSave.php",
data:names,
success: function(data)
{
$('#confir').text('Your Appointment Received..');
}
});
return false;
}
});
});
I have a appontment form. when i click send link it will grab all the values in the textboxs and put it in the names variable through serialize() function. i want to filter the names variable and find out if any of the field is left not filled.. if only if then i will make the ajax part.. but its not working...any help
When you use $.serialize() the variable content looks like ?key=value1&key=value2. If you want to validate the form, just do it without serialize like
var found_errors = false;
if($('#formfield1').val().trim() == "") {
//Handle errors if field is empty
found_errors = true;
}
And if no errors are found, serialize the form and send it.
Consider using jQuery validation plugin.
http://docs.jquery.com/Plugins/Validation

JQuery, function does not see text field value

please don't judge my JS skills, I'm complete beginner in it. =))
So I have a function that register user, But I want to make "create_sample_user" button to fill text fields with some data. This way people can quickly check the website, without typing names, email and so on...
But the problem is: Register button works fine when I type username and all other fields by my self. But Doesn't work(I assume it just doesn't 'see' the values of the text fields) when I fill them with "create_sample_user" button.
function create_sample_user() {
var button = $("#create-sample-user");
button.click(function() {
var ranNum = 1 + Math.floor(Math.random() * 100);
var uname = 'Sample_'+ranNum;
$("#id_username").val(uname);
$("#id_email").val(uname+'#'+uname+'.com');
$("#id_password").val(uname);
$("#id_password2").val(uname);
});
}
function register_user() {
$("#register-user").click(function() {
$.ajax({
url: "/registration/register_user/",
type: "POST",
dataType: "text",
data: {
username : $("#id_username").val(),
email : $("#id_email").val(),
password : $("#id_password").val(),
password2 : $("#id_password2").val(),
},
success: function(data) {
parsed_data = $.parseJSON(data);
if (data) {
alert("User was created");
window.location = parsed_data.link;
}
else {
alert("Error");
}
}
});
});
}
THE ANSWER:
whole thing didn't work because of one character in this line of code:
`var uname = 'Sample_'+ranNum;`
For some reason _ character was the problem, and AJAX didn't want take it.
in other words:
var uname = 'Sample'+ranNum;
This line would do the trick :=)
Okay, replace your create_sample_user() method with this:
$(document).ready(function() {
var button = $("#create-sample-user");
button.click(function() {
var ranNum = 1 + Math.floor(Math.random() * 100);
var uname = 'Sample_'+ranNum;
$("#id_username").val(uname);
$("#id_email").val(uname+'#'+uname+'.com');
$("#id_password").val(uname);
$("#id_password2").val(uname);
});
}​);​
Also, try removing the function register_user() function wrapper.
This should do it. It should pop up the success alert box as well (I changed your AJAX URL to use the AJAX echo for jsFiddle):
http://jsfiddle.net/MQ6Cq/4/
UPDATES (since you posted your code - I will update this with bugs as I find them):
You have two $(document).ready() calls now - delete the first one (THIS WAS EDITED)
You have have to remove the lines function register_user() { and the closing brace from around the register user click handler
I made a tiny update to my earlier fiddle, just in case it helps with testing, and changed the request type to "GET". Open your browser's console (F12), right-click and turn on logging for XMLHttpRequests. Then run it and you will see that the AJAX is successfully transmitting the data. I don't know what is wrong with your other stuff but I don't have a server that I can test it on and I'm not getting enough feedback to know what's going on after you try each suggestion (or even if you're trying them). I just hope this helps you solve your problem.
Good Luck! :)
Your code should work. Here's a jsfiddle (simplified version of it)
If you look at the console, you'll see the data is well formatted.
The only thing I see in your code is that create_sample_user() is not called so the click event isn't applied to the button. But I guess you've just omitted to put it in the question
create_sample_user();
$('#register-user').click(register_user);
function create_sample_user() {
var button = $("#create-sample-user");
button.click(function() {
var ranNum = 1 + Math.floor(Math.random() * 100);
var uname = $("#id_username").val('Sample_'+ranNum);
$("#id_email").val(uname.val()+'#'+uname.val()+'.com');
$("#id_password").val(uname.val());
$("#id_password2").val(uname.val());
});
}
function register_user() {
data = {
username : $("#id_username").val(),
email : $("#id_email").val(),
password : $("#id_password").val(),
password2 : $("#id_password2").val(),
}
console.log(data);
}
$("#create-sample-user").click(create_sample_user);
$('#register-user').click(register_user);
function create_sample_user() {
var ranNum = 1 + Math.floor(Math.random() * 100);
var uname = $("#id_username").val('Sample_' + ranNum);
$("#id_email").val(uname.val() + '#' + uname.val() + '.com');
$("#id_password").val(uname.val());
$("#id_password2").val(uname.val());
}
function register_user() {
data = {
username: $("#id_username").val(),
email: $("#id_email").val(),
password: $("#id_password").val(),
password2: $("#id_password2").val(),
}
console.log(data);
}

get form data with javascript and then submit it to a php file using ajax

I am having some trouble working out how to get data from a form to post via ajax. I have the following code but it doesn't seem to be sending though the data from elements like checkboxes and radio buttons. Instead it is sending though all the fields. ie if there is a set of radiobuttons it is sending through all the possibilities not just the checked ones. The form can be made up of any type of element and have an undermined amount of elements in it, so I need to iterate through in the way I am. That part seems to be working, but I can't seem to get the javascript to grab the selected data. Do I need to manually check each element's type and then check to see if it checked etc?
myString = "";
my_form_id = "1";
my_url = "phpscript.php";
elem = document.getElementById("form_" + my_form_id).elements;
for(var i = 0; i < elem.length; i++)
{
if (i>0) { myString += "&"; }
myString += elem[i].name + "=" + elem[i].value;
}
$.ajax({
type: "POST",
url: my_url,
data: myString,
success: function(data) {
// process the post data
}
});
`
Since you're using jQuery, you can drastically simplify it all:
var my_form_id = "1";
var my_url = "phpscript.php";
var form = $("#form_" + my_form_id);
$.ajax({
type: "POST",
url: my_url,
data: form.serialize(),
success: function(data) {
// process the post data
}
});
jQuery's serialize method does all the work for you. But if you wanted to do it by hand, then yes, you would have to check each field.

Categories

Resources