I have <form> on my page containing a <textarea>, and I want to send the text entered in it using Ajax. The text goes to a PHP page, where I insert it into a SQL database.
The problem I am facing is that whenever I write + or & in the <textarea>, JavaScript treats them as special characters in the URL. How can I escape them?
function getMessageResponse() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch(e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
document.getElementById('response').innerHTML = xmlHttp.responseText;
document.myform.post.value = '';
retrieve();
}
}
var url = "wall4.php";
url = url+"?post=" + document.myform.post.value;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
Encode your parameter:
url = url + "?post=" + encodeURIComponent(document.myform.post.value);
Related
How can I load html in a div when I click a button?
I have function but it does not work:
function ajaxFunction(id, url){
document.getElementById("sh").style.visibility = 'hidden';
var xmlHttp;
try {// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4) {
//Get the response from the server and extract the section that comes in the body section of the second html page avoid inserting the header part of the second page in your first page's element
var respText = xmlHttp.responseText.split('<body>');
elem.innerHTML = respText[1].split('</body>')[0];
}
}
var elem = document.getElementById(id);
if (!elem) {
alert('The element with the passed ID doesn\'t exists in your page');
return;
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
And I have button to click it.
<button type="button" name="new metere" value="" class="button" onclick="ajaxFunction('test','newmetere.html');">new metere</button>
when I put newmetere.php Function does not work and get garbage value.
Try jQuery's load () : it's a fast and simple way to load content from another page asynchronously in a web page using Ajax!
I posting my value through ajax and using the response the details will be displayed.I am getting the problem while retreiving the data.But i dono where i have mistaked,then this is the error getiing displayed frequently
"There was a problem while using XMLHTTP:\n";
in all browsers mainly in the chrome,could any one help me...
this is my code,
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer 6+
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// Internet Eplorer 5
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX. Download a newer browser to view this page.");
return false;
}
}
}
// insert server response into HTML element
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
MM_check_session(xmlHttp.responseText);
var b_gc = document.getElementById(insert).value;
document.getElementById(insert).value = xmlHttp.responseText;
var shippingid = getCheckedValue('checkout_form', 'shippingid');
closeMessage();
MM_calc_shipping(shippingid);
if (b_gc == xmlHttp.responseText) {
MM_register();
} else {
error = 1;
document.getElementById('payment_error').innerHTML = xmlHttp.responseText;
document.getElementById(insert).value = '';
}
} else {
closeMessage();
alert("We can't process your request.Please refresh(reload) the page to proceed further:\n"
+ xmlHttp.statusText);
}
}
}
displayStaticMessage(
'<img src=' + config_MM_loader_image_path + ' alt=\'loading...Please wait\'>',
false);
xmlHttp.open("POST", serverScript, true);
xmlHttp.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
xmlHttp.setRequestHeader('Content-length', parameters.length);
xmlHttp.setRequestHeader('Connection', 'close');
xmlHttp.send(parameters);
any help
You seem to be incorrectly tagged as php. Also have you considered jQuery for the ease of ajax whilst using it.
as for your question could you post the code on the page where the ajax request is going to as the code here looks fine..
Edit:
Where is serverScript set?
change serverScript for the ajax page you are calling?
http://msdn.microsoft.com/en-us/library/windows/desktop/ms757849%28v=vs.85%29.aspx
I am applying the following Javascript in a check form function:-
var msg1="";
function check_si_form_info(form,mark,edit){
if(mark==10 || mark=="all"){
if(form.email.value==""){
si_check_email.innerHTML="";
si_check_email.style.height="0px";
form.email.style.backgroundColor="#FFFFFF";
}else{
var i=form.email.value.indexOf("#");
var j=form.email.value.indexOf(".");
if((i<0)||(j<0)){
si_check_email.innerHTML="The email address format is incorrect!";
si_check_email.style.height="auto";
form.email.style.backgroundColor="#FFD5FF";
return false;
}
else{
var email = form.email.value;
xmlhttp=new XMLHttpRequest(); //HERE!!!!
xmlhttp.open('get','si/check_si_email.php?email='+email,true);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
msg1 = xmlhttp.responseText;
if(msg1 == '1'){
si_check_email.innerHTML="email address has been used!";
si_check_email.style.height="auto";
form.email.style.backgroundColor="#FFD5FF";
}else if(msg1 == '2'){
si_check_email.innerHTML="";
si_check_email.style.height="0px";
form.email.style.backgroundColor="#FFFFFF";
}else if(msg1 == '3'){
si_check_email.innerHTML="";
si_check_email.style.height="0px";
form.email.style.backgroundColor="#FFFFFF";
}
}//200
}//4
}//onreadystatechange
xmlhttp.send(null);
}
if (msg1 == '1'){
return false;
}
}
}
}
In IE 7 or above, the scripts work perfectly well. But in IE6, the browser always mention the "XMLHttpRequest()" is not defined. If I wish to define it, where and what shall I input?? Thanks a lot!
In IE6 you need to use new ActiveXObject('Microsoft.XMLHTTP') to create the XHR object.
var xmlhttp;
try {
xmlhttp = new XMLHttpRequest(); // real browsers
} catch(e) {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); // <=IE6
}
But you should really use jQuery, it does all the dirty work for you.
Additionally dropping IE6 support wouldn't be a bad thing.
xmlhttp=new XMLHttpRequest();
if(!xmlhttp && typeof ActiveXObject != "undefined"){
try{ xmlhttp=new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){xmlhttp=false;}
if(!xmlhttp)try{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){xmlhttp=false;}
}
In the article on AJAX on Wikipedia you have an example how to enable support of AJAX within IE 5, IE 5.5 and IE 6. The example is as follows:
/*
Provide the XMLHttpRequest constructor for Internet Explorer 5.x-6.x:
Other browsers (including Internet Explorer 7.x-9.x) do not redefine
XMLHttpRequest if it already exists.
This example is based on findings at:
http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
*/
if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
//Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant
throw new Error("This browser does not support XMLHttpRequest.");
};
So I've got an AJAX project which uses the XmlHttpRequest object to dynamically retrieve data from the server-side (in my case, I use JSON with PHP/MySQL in case that's relevant). Pretty much all my HTML elements are created dynamically via the javascript DOM, so it's the .js files doing the work.
Here's a typical .js file I use to get server-side info from PHP and then build the html:
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch(e) {
var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
for(var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++) {
try {
xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
} catch(e) {}
}
}
if (!xmlHttp) alert("Error creating XmlHttpRequest object.");
else { return xmlHttp; }
}
function initialize_main() {
if (xmlHttp) {
try {
xmlHttp.open("GET", "main_php.php", true);
xmlHttp.onreadystatechange = handleMainStateChange; //call a function when the state changes
xmlHttp.send(null);
} catch(e) {
alert("Can't connect to server: " + e.toString());
}
}
}
function handleMainStateChange() {
if (xmlHttp.readyState==4) {
if (xmlHttp.status==200) {
try {
init_main();
} catch(e) {
alert("Error reading the response: " + e.toString());
}
} else {
alert("There was a problem retrieving data: " + xmlHttp.statusText);
}
}
}
function init_main() {
var data = JSON.parse(xmlHttp.responseText);
//now do stuff with the DOM or w/e
}
So as I said everything is cool in firefox and chrome. But internet explorer tells me: "Error reading the response: TypeError: Object doesn't support this property or method". I'm a bit new to AJAX as you might guess, so thanks for any help!
I would highly recommend that you use JQuery so that you can write Javascript that doesn't care about the type of browser (JQuery does this for you): http://jquery.com/
Try using this function, for me it works for all browser
function getXMLHTTP()
{
var xmlhttp = false;
try
{
xmlhttp = new XMLHttpRequest();
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1)
{
xmlhttp = false;
}
}
}
return xmlhttp;
}
function ajaxFunction(phpFunction){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.subCat').html(ajaxRequest.responseText);
$('.subCat').ready(function(){
$('.subCat').fadeIn();
});
}
}
var url = "products.php?func=" + phpFunction;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
This function works great, and has no problems. But if I add:
function refreshProduct(idNum, phpFunction){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.' + idNum).empty();
$('.' + idNum).html(ajaxRequest.responseText);
});
}
}
var url = "products.php?func=" + phpFunction + "&idNum=" + idNum;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
When I try to execute ajaxFunction('returnAllProducts') I get:
syntax error
});\n
from
$('.' + idNum).html(ajaxRequest.responseText);
}); <<<----
and
ajaxFunction is not defined
javascript:ajaxFunction('returnAllProducts')()
So my questions are:
a) how do I convert this over to jquery? I've read over some jquery ajax tutorials, but I wasn't able to make the connection how to do what I am doing here.
b) How do I get both functions to work? I know the PHP behind them works fine, but I can't even test if refreshProduct() works properly right now.
You seem to be missing a }
this is your code, properly indented...
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.'idNum).empty();
$('.'idNum).html(ajaxRequest.responseText);
});
When it should be
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.'idNum).empty();
$('.'idNum).html(ajaxRequest.responseText);
}
});
Also, the two } after this should be deleted, rendering your code like this:
function refreshProduct(idNum, phpFunction){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.' + idNum).empty();
$('.' + idNum).html(ajaxRequest.responseText);
}
});
var url = "products.php?func=" + phpFunction + "&idNum=" + idNum;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
As for rewriting this using jQuery, it's really easy:
function ajaxFunction(phpFunction){
var url = "products.php?func=" + phpFunction;
$.get(url, function(data) {
$('.subCat').html(data).ready(function(){
$('.subCat').fadeIn();
});
});
}
function refreshProduct(idNum, phpFunction){
var url = "products.php?func=" + phpFunction + "&idNum=" + idNum;
$.get(url, function(data) {
$('.' + idNum).empty().html(data);
});
}