Why "space" is not supported in the ajax post method? - javascript

Below is my html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
<script type="text/javascript">
function Data_Check()
{
var xmlHttp;
try
{
xmlHttp=new XMLHttpRequest(); }
catch (e)
{
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)
{
alert(xmlHttp.responseText);
}
}
var RES = document.getElementById("Remarks").innerHTML;
var params ="RES="+RES;
xmlHttp.open("POST","Data_Check.asp",true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
}
</script>
</head>
<body>
<textarea id="Remarks" rows="5" name="Remarks" cols="79" style="font-family: Arial; font-size: 11px">please, accept my submit form.</textarea>
<br>
<img id="Submit" onclick ="return Data_Check();" border="0" src="submit.png" width="145" height="28">
</body>
<img
</html>
Here i facing the problem is,
When i submit "Remarks" textarea innerhtml to my "Data_Check.asp"
<%
RES = Request.Form("RES")
%>
and this remarks save in my sql database.( database field is "Remarks_text" and datatype is "text")
In the data base textarea data is read ("please, accept my submit form.") textarea data with out space.
like this
please,acceptmysubmitform.
I need to save
please, accept my submit form.
hoping your support

Try url encoding:
var RES = encodeURIComponent(document.getElementById("Remarks").value);

Change
document.getElementById("Remarks").innerHTML;
to
document.getElementById("Remarks").value;

I suspect spaces are not supported in URLs or HTTP headers, hence old URLs had %20 instead of a space. Modern browsers and servers now do this behind the scenes.
I found replacing spaces with %20 using formValues = formValues.replace(/ /gi,"%20"); prior to sending solved the problem.

Yes this is fixed!
Example :
var dataString = "textcontent="+test.replace(/ /gi,"%20");

Related

Ajax won't Display on web page

I am currently trying to use a Ajax in netbeans using JavaScript and PHP file. The following code I should click the button and the contents of the php fill should appear but it doesn't. When I use firebug in firefox the response shows the full php file has returned but will not display on webpage. Why???
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttp() {
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;
}
}
}
return xmlHttp;
}
function MakeRequest() {
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
My PHP file is
<?php
echo "This is a php response to your request!!!!!!";
?>
Apart from the fact that HTML code is barely decent, why not use jQuery?
<button id="get" onClick="return false;">jQuery get</button>
<div id="result"></div>
<script type="text/javascript">
$("#get").click(function() {
$.get( "ajax.php", function( data ) {
$( "#result" ).html( data );
});
});
</script>
PHP is server side and is not made to be run on the client side. Your response should come from a URL and not the contents of a file. Ensuring that your response contains on HTML and not PHP should lead you to your solution.
Try replacing your PHP file with
<p>This is a php response to your request!!!!!!</p>
If this enables you to show your content, you have your problem and solution.

not entering in "xmlhttp.onreadystatechange=function() {"

I am following my old question post that I suddenly enter in a new problem that is: my code is not entering in this line "xmlhttp.onreadystatechange=function()". I also checked by marking alert. so I unable to understand. can somebody tell me why this is not happening?
<html>
<head>
<script>
function changeThis(){
xmlHttp = new XMLHttpRequest();
var formInput = document.getElementById('theInput').value;
/* formInput will be undefined */
document.getElementById('newText').innerHTML = formInput;
/* also undefined */
// var xmlHttp = null;
xmlhttp.onreadystatechange=function() //help
{
alert("y"); // not entering help?????
if (xmlhttp.readystate==4 && http.status==200)
{
document.getElemenById('newText').innerHTML=xmlhttp.reponseText;
}
if(xmlhttp.status == 404)
{
var temp = "NO file found";
document.getElementById('newText').innerHTML=temp;
}
xmlHttp.open( "GET", "file2.php", true);
xmlHttp.send();
}
}
</script>
</head>
<body>
<p>You wrote: <span id='newText'></span> </p>
<textarea id="theInput" style="height:200px;">Write Here</textarea>
<input type='button' onclick='changeThis()' value='See what you wrote'/>
</body>
</html>
Move this:
xmlHttp.open( "GET", "file2.php", true);
xmlHttp.send();
outside of the onreadystatechange handler; your current code won't try to submit the HTTP request until after the HTTP request is already making progress. (Hat-tip to judder for editing your question to indent your code properly, making this problem obvious.)
Edited to add: Also, as Pavlo points out, you need to consistently write xmlHttp. JavaScript variable-names are case-sensitive, so xmlhttp is a completely different variable.

javascript code is not working in browser?

Here is my code it will send get request and renders some content of the response in html.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mytitle</title>
</head>
<body>
<script type="text/javascript">
function httpGet() {
var xmlHttp = null;
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, false);
xmlHttp.send();
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
</script>
<input type="text" id="city" />
<input type="button" value="submit" onclick="httpGet()" />
<div id="placeholder"></div>
</body>
</html>
this code is working perfectly when i run in eclipse browser. but its failing in Browser.
I have checked browser configuration for script enabling and its enabled. and also no issue with browser configuration.
Im new to javascript http requests.
Please suggest
I read somewhere that the Eclipse browser doesn't adhere to the same origin policy [Wikipedia]. That's why it is possible to make an Ajax request to an external URL, something that is not possible by default in a "normal" browser.
And indeed if I try to run your code [jsFiddle], I get the following error:
XMLHttpRequest cannot load http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
There are multiple ways to work around the same-origin policy [SO]. In your case it seems that the service supports JSONP [SO].
With JSONP, your not making an Ajax call to the server, but instead you are using the URL with a dynamically created script element. Script elements are not restricted by the same-origin policy and therefore can load data (code) from other servers.
The server will return a JavaScript file which contains a single function call. The name of the function is specified by you via a query parameter. So, if the JSON response is usually:
{"message":"accurate","cod":"200", ...}
by adding the argument callback=foo to the URL, the server returns
foo({"message":"accurate","cod":"200", ...});
(follow this URL to see an example for your service)
This response can be evaluated as JavaScript. Note that you can not turn every JSON response into JSONP. JSONP must be supported by the server.
Here is a complete example:
// this function must be global since the script is executed in global scope
function processResponse(obj1) {
document.getElementById("placeholder").innerHTML =
obj1.message + " " + obj1.list[0].name;
}
function httpGet() {
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
// the following line is just to explictly show the `callback` parameter
url += '&callback=processResponse';
// ^^^^^^^^^^^^^^^ name of our function
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
DEMO
If you google for JSONP, you will find more information [Wikipedia] and tutorials.
I think ur xmlhttprequest instance is not getting created. It is some time browser dependent try this..
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{ your code }
In addition to needing a cross browser xmlhttpquest (which for that alone I'd use jQuery), you also need to wait for the document ready before accessing the city by id... that is, move your script block after your city definition (and I think you may need a form, depending on browser).
Perhaps something like this
<body>
<form>
<input type="text" id="city" />
<input type="button" value="submit" onclick="httpGet()" />
</form>
<script type="text/javascript">
function httpGet() {
if (typeof (document.getElementById("city")) == 'undefined') {
alert("Maybe console.log our alarm... but the sky appears to be falling.");
}
var xmlHttp = null;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
}
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp.open("GET", url, false);
xmlHttp.send();
}
</script>
<div id="placeholder"></div>
</body>
function httpGet() {
var xmlHttp = null;
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, false);
xmlHttp.onreadystatechange = function(){
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
xmlHttp.send();
}

Ajax POST request does not work

I don't know what I am doing wrong, but all looks good. I am working on localhost and I am having trouble trying to load a file.
This is my code. I am working in NetBeans and console is clear without any errors.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo_post.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
When I execute this code, I get no results.
In between your .open() and .send() invocations, set your request header like so:
xmlhttp.open("POST", "demo_post.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
At least, that's how you'd do it if you didn't want to use jQuery.
As some of the comments suggest - you need to look in the error console of the Browser. NOT NETBEANS. Also, understand how to set breakpoints in JS, etc.
Below is an example of what you are trying to achieve using jQuery which is much simple than using pure Javascript.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
// jQuery allows you to use selectors rather than onClick, etc
// So when anything with a class called "loadData" is clicked this function will run
$(".loadData").click(function (event) {
$.ajax({
url: 'demo_post.php', // The URL that your making the request to
type: 'POST', // Type - GET or POST
dataType: 'html', // DataType - can be html, json or jsonp
cache: false, // true or false - whether you want data to be cached
data: 'foo=bar', // Any data that your submitting with the request.
error: function (error_response) {
// An error has occured so empty your #myDiv and put the error in there.
$("#myDiv").empty().append(error_response.status);
},
success: function (response) {
// Everything has worked - empty #myDiv and put the replace with response
$("#myDiv").empty().append(response);
}
});
});
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" class="loadData">Request data</button>
<div id="myDiv"></div>
</body>
</html>
You can find more information on jQuery here: http://api.jquery.com and more specifically on jQuery's AJAX functions here - http://api.jquery.com/jQuery.ajax/
i found that your code is actually designed for GET method.And in this case is not important to use POST instead of get.(because no parameter is passed and also its not a form..) and also agrees to #Jackson
<!DOCTYPE html>
<html>
<head>
<!--you can use online js file but in here i download the js file from code.jquery.com/jquery-2.0.3.min.js and kept it in localhost same folder -->
<script type="text/javascript" src="/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","demo_post.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>

onreadystatechange function not being called

For some reason, onreadystatechange call back function is not being called in asynchronous mode. I tested the post in synchronous mode and confirmed that post itself is working fine (commented out testing code I used to check post in synchronous mode). The problem occurs both in safari and firefox latest version. Can someone please tell me what I am doing wrong here? Thank you.
<html>
<head>
<script>
function recordScore(str)
{
if (str.length==0)
{
return;
}
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="http://hellworld3.appspot.com/findcountry";
var params = "screenname="+document.getElementById("screenname1").value+"&score="+document.getElementById("score1").value;
alert("params: "+params);
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange = function()
{
alert("entered call back function. readstate value is: "+xmlHttpreadyState+". Response Text is: "+xmlHttp.responseText);
if (xmlHttp.readyState==4)
{
document.getElementById("message").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlHttp.send(params);
//Testing code for synchronous mode
//alert("Http get status is: "+xmlHttp.status);
//alert("Http ready state value is: "+xmlHttp.readyState);
//alert("Http get response text is: "+xmlHttp.responseText);
//document.getElementById("message").innerHTML=xmlHttp.responseText;
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>
</head>
<body>
<form name="testform">
Screename:
<input type="text" id="screenname1" name="screenname">
<br/>
Score:
<input type="text" id="score1" name="score" onchange="recordScore(this.value)">
<br/>
<p id="message">test</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
you have an error in the onreadystatechange function:
alert("entered call back function. readstate value is: "+xmlHttpreadyState+". Response Text is: "+xmlHttp.responseText);
xmlHttpreadyState should be xmlHttp.readyState
After I fixed that, it worked for me in FF3
Correct me if I'm wrong, but for POST don't you need to do a setRequestHeader for Content-Length like so;
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader('Content-length',(params?params.length:0));
xmlHttp.send(params);
This might correct your problem.

Categories