I am having issues sending a Post request ASP.Net using AJAX and JavaScript. My intentions are to send multiple values to a database and insert them. I have an html page with the following functions calling ASP request using AJAX.
.html file:
// Builds AJAX request and sends it to ASP page
function sendInfo(x,y,z){
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=stateChanged;
xmlhttp.open("POST","Update.asp",true);
xmlhttp.send("addy="+encodeURIComponent(x)+
"&lat="+encodeURIComponent(y)+
"&lng="+encodeURIComponent(z));
}
// Checks the ready state of the sent response
function stateChanged() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
else {
document.getElementById("txtHint").innerHTML="Error with ready state: " + xmlhttp.readyState + " and status: " + xmlhttp.status;
}
}
Here is my .asp file:
<%
conn = Server.CreateObject("ADODB.Connection");
conn.Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" + Server.MapPath("Project.mdb"));
var addy=Request.Form("addy");
var lat=Request.Form("lat");
var lng=Request.Form("lng");
var sql="INSERT INTO Location_Info (Address,Latitude,Longitude)"
sql= sql + " VALUES "
sql= sql + "('" + addy + "',"
sql= sql + "'" + lat + "',"
sql= sql + "'" + lng + "')"
rs = conn.Execute(sql);
Response.Write("Your record has been placed into the database.");
rs.Close();
conn.Close();
%>
Whenever I run my page and enter the proper information to be sent, it only returns the else case of "Error with ready state: 4 and status: 500". This status of 500 is a general error and I am unsure of how to debug my program, as I have even tried commenting everything in the .asp file and only having 'Response.Write("text");' code, but to no avail, still status:500 error.
If someone can help me with what I am doing wrong, it would be greatly appreciated.
Related
I have a browser action I've implemented it as an AddOn.
I'm testing my construction of the AddOn within my domain
between two machines as server and a client.
I'm stuck at AJAX failing with status code 0.
I set up Apache to enable CORS to make sure that the code is behaving as expected.
I added this line to the apache config and enabled headers:
Header set Access-Control-Allow-Origin "*"
The javascript code: UPDATED
function sendData(data){
var requestdata = 'data1=one&data2=two&data3=three';
var xhr = new XMLHttpRequest();
xhr.open("POST","http://server/test/test.php");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onloadstart = function(){
console.log("Onload status: " + xhr.status);
}
xhr.onerror = function(ev) {
console.log("OnError Status: " + xhr.status + ", Loaded: " + ev.loaded + ", Total: " + ev.total);
}
xhr.onreadystatechange = function() {
console.log(xhr.status);
if (xhr.status !== 200){
console.log("Failure :( + Status: " + xhr.status);
//console.log(requestdata);
console.log("Ready State: " + xhr.readyState + ", Status: " + xhr.status +", Response Text: " + xhr.responseText);
} else {
alert("Success!");
}
}
xhr.send(requestdata);
}
test.php
<?php
require '../lib/Database.php';
error_reporting(E_ALL);
$db = new Database('test');
var_dump($db);
json_encode($_POST);
?>
Have I done this AJAX implementation correctly?
If I have, and I have made adjustments for CORS, why is it failing with status code 0?
UPDATE
This is an AddOn I am testing in Firefox.
From the "matches" parameter in manifest.json, navigating to the page in question retrieves data from the page using Vanilla JS on the DOM.
The collected data is held in an object.
The data object is delivered
This is a picture of what's returned in the browser:
UPDATE2
I replaced the POST url with http://httpbin.org/post to see if the data is going anywhere. Nope.
This is my first request for help at stackoverflow, so, please, be gentle.
I've searched stackoverflow for questions on this, but haven't found anything that addresses my issue in a way that has allowed me to solve my problem.
I'm trying to use php to send an email containing a user's password from a webpage. I'm using Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/600.7.12 (KHTML, like Gecko) Version/6.2.7 Safari/537.85.16 as my browser--but I need it work from any major modern browser.
Now https://pie.gd/test/script-link-events/ seems to indicate that is not supported by my browser, nor by any Mac browser, but that doesn't seem to be consistent with my experience--none of my browser's consoles through an error with my use of onreadystatechange.
The javascript code I'm using is:
function forgotEmail(str_code)
{
bool_debug = <?php echo $bool_debug ?>;
if (bool_debug) { alert("php/forgotEmail.php?"+str_code+" is being called."); }
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} // if (window.XMLHttpRequest)
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} // if (window.XMLHttpRequest) else
xmlhttp.onreadystatechange = function()
{
alert("readyState = " + xmlhttp.readyState + "\nstatus=" + xmlhttp.status)
if (xmlhttp.readyState==4)
{
alert("readyState = " + xmlhttp.readyState + "\nstatus=" + xmlhttp.status)
if (xmlhttp.status==200)
{
alert("An email with your password has been sent to the account you gave with your CO Gold submission. It may take a few minutes to arrive. Please also check your spam folder.");
} // if (xmlhttp.status==200)
} // if ((xmlhttp.readyState==4) && (xmlhttp.status==200))
else
{
alert("There was a problem sending the email with your password. Please click 'Forgot Password' again. If you get this alert a third time, please email...");
} // if ((xmlhttp.readyState==4) && (xmlhttp.status==200)) else
} // xmlhttp.onreadystatechange = function()
xmlhttp.open("GET", "php/forgotEmail.php?"+str_code);
} // function forgotEmail(str_code)
and the relevant code from the php page being called by AJAX is:
…
$headers = 'From: <a valid email address>'."\r\n";
// the message
$str_body = $row_psswd['NameFirst'].",\n\n"
.'Your password is: '.$row_psswd['psswd']."\n\n";
// use wordwrap() if lines are longer than 70 characters
$str_body = wordwrap($str_body,90);
// send email
$return = mail($row_psswd['Email'], "Forgotten Password", $str_body, $headers);
echo str_replace("\n", "<br />\n", $str_body);
echo "<br />\n<br />\n";
echo (($return) ? 'email sent' : 'email not sent');
Now, when I call the php page by hand, the email gets sent no problem.
But when I click on the HTML button in the webpage that calls the javascript, no email gets sent. I know the php page is being called correctly, because I get:
php/forgotEmail.php?code=JIxRIt is being called.
from my first debug alert in the javascript code. But I only get one alert from within the xmlhttp.onreadystatechange = function():
readyState = 1
status=0
and then the "things haven't worked" alert:
There was a problem sending the email with your password. Please click 'Forgot Password' again. If you get this alert a third time, please email…
So it would appear that readyState is never taking on the values 2, 3 or 4--not taking on the value 4 indicates that the email isn't getting sent, right?
But the fact that that I'm getting an
readyState = 1
status=0
makes me think that onreadystatechange is, in fact, supported by Safari (for the Mac).
I hope I've stated the issue clearly and that somebody will be able to help me with this as it's frustrating the #$^&$%# out of me.
You need to use the send() method to send your request to the server
xmlhttp.send()
Also, you should to move your "thing did not work" code because, right now any readyState that is not 4 will trigger it.
xmlhttp.onreadystatechange = function()
{
alert("readyState = " + xmlhttp.readyState + "\nstatus=" + xmlhttp.status)
if (xmlhttp.readyState==4)
{
alert("readyState = " + xmlhttp.readyState + "\nstatus=" + xmlhttp.status)
if (xmlhttp.status==200)
{
alert("An email with your password has been sent to the account you gave with your CO Gold submission. It may take a few minutes to arrive. Please also check your spam folder.");
} // if (xmlhttp.status==200)
} // if ((xmlhttp.readyState==4) && (xmlhttp.status==200))
else
{
alert("There was a problem sending the email with your password. Please click 'Forgot Password' again. If you get this alert a third time, please email...");
} // if ((xmlhttp.readyState==4) && (xmlhttp.status==200)) else
} // xmlhttp.onreadystatechange = function()
becomes
xmlhttp.onreadystatechange = function()
{
alert("readyState = " + xmlhttp.readyState + "\nstatus=" + xmlhttp.status)
if (xmlhttp.readyState==4)
{
alert("readyState = " + xmlhttp.readyState + "\nstatus=" + xmlhttp.status)
if (xmlhttp.status==200)
{
alert("An email with your password has been sent to the account you gave with your CO Gold submission. It may take a few minutes to arrive. Please also check your spam folder.");
} // if (xmlhttp.status==200)
else
{
alert("There was a problem sending the email with your password. Please click 'Forgot Password' again. If you get this alert a third time, please email...");
} // if ((xmlhttp.readyState==4) && (xmlhttp.status==200)) else
} // if ((xmlhttp.readyState==4) && (xmlhttp.status==200))
} // xmlhttp.onreadystatechange = function()
This is a sample javascript code from http://locationdetection.mobi to detect geo location using google API.
(Original zip file contains a php file, html, and this javascript code)
As you see in the code below, on the last part of this javascript code there is one line of code to render the result of location detection to html file.
How to generate result into a text file instead of render to browser?
// this is called when the browser has shown support of navigator.geolocation
function GEOprocess(position) {
// update the page to show we have the lat and long and explain what we do next
document.getElementById('geo').innerHTML = 'Latitude: ' + position.coords.latitude + ' Longitude: ' + position.coords.longitude;
// now we send this data to the php script behind the scenes with the GEOajax function
GEOajax("geo.php?accuracy=" + position.coords.accuracy + "&latlng=" + position.coords.latitude + "," + position.coords.longitude +"&altitude="+position.coords.altitude+"&altitude_accuracy="+position.coords.altitudeAccuracy+"&heading="+position.coords.heading+"&speed="+position.coords.speed+"");
}
// this is used when the visitor bottles it and hits the "Don't Share" option
function GEOdeclined(error) {
document.getElementById('geo').innerHTML = 'Error: ' + error.message;
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(GEOprocess, GEOdeclined);
}else{
document.getElementById('geo').innerHTML = 'Your browser sucks. Upgrade it.';
}
// this checks if the browser supports XML HTTP Requests and if so which method
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// this calls the php script with the data we have collected from the geolocation lookup
function GEOajax(url) {
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.send(null);
}
// this reads the response from the php script and updates the page with it's output
function updatePage() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
document.getElementById("geo").innerHTML = '' + response;
}
}
You can't create text files from the frontend, well at least not without configuring some flags in the browser, so you need to send the data to your backend language, create the file and then download it
I wrote a cgi-script with c++ to return the query-string back to the requesting ajax object.
I also write the query-string in a file in order to see if the cgi script works correctly.
But when I ask in the html document for the response Text to be shown in a messagebox i get a blank message.
here is my code:
js:
<script type = "text/javascript">
var XMLHttp;
if(navigator.appName == "Microsoft Internet Explorer") {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
XMLHttp = new XMLHttpRequest();
}
function getresponse () {
XMLHttp.open
("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" +
document.getElementById('fname').value + "&sname=" +
document.getElementById('sname').value,true);
XMLHttp.send(null);
}
XMLHttp.onreadystatechange=function(){
if(XMLHttp.readyState == 4)
{
document.getElementById('response_area').innerHTML += XMLHttp.readyState;
var x= XMLHttp.responseText
alert(x)
}
}
</script>
First Names(s)<input onkeydown = "javascript: getresponse ()"
id="fname" name="name"> <br>
Surname<input onkeydown = "javascript: getresponse();" id="sname">
<div id = "response_area">
</div>
C++:
int main() {
QFile log("log.txt");
if(!log.open(QIODevice::WriteOnly | QIODevice::Text))
{
return 1;
}
QTextStream outLog(&log);
QString QUERY_STRING= getenv("QUERY_STRING");
//if(QUERY_STRING!=NULL)
//{
cout<<"Content-type: text/plain\n\n"
<<"The Query String is: "
<< QUERY_STRING.toStdString()<< "\n";
outLog<<"Content-type: text/plain\n\n"
<<"The Query String is: "
<<QUERY_STRING<<endl;
//}
return 0;
}
I'm happy about every advice what to do!
EDIT: the output to my logfile works just fine:
Content-type: text/plain
The Query String is: fname=hello&sname=world
I just noticed that if i open it with IE8 i get the query-string. But only on the first "keydown" after that IE does nothing.
You don't have to use javascript: in on___ handler, just onkeydown="getresponse();" is enough;
IE>=7 supports XMLHttpRequest object, so directly checking if XMLHttpRequest exists is better than checking whether navigator is IE. Example:
if(XMLHttpRequest) XMLHttp=new XMLHttpRequest();
else if(window.ActiveXObject) XMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
inside your getresponse() function, try to add below code at the beginning (before open):
try{XMLHTTP.abort();}catch(e){}
Because you're using a global object, you may want to "close" it before opening another connection.
Edit:
Some browser (maybe Firefox itself?) do not handle non-"text/xml" response very well in default state, so to ensure things and stuffs, try this:
function getresponse () {
try{XMLHttp.abort();}catch(e){}
XMLHttp.open("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" +
document.getElementById('fname').value + "&sname=" +
document.getElementById('sname').value,true);
if(XMLHttp.overrideMimeType) XMLHttp.overrideMimeType("text/plain");
XMLHttp.send(null);
}
My problem had nothing to do with the code...
I was testing my script on the local IIS7 and I opened the html-page with double-clicking on the file. But you have to open the webpage via browser (localhost/mypage.htm) because otherwise for the browser the html and the executable have different origins. which is not allowed.
I am using ajax call to a remote server which is supposed to return a javascript block in response . My ajax call is something like :
var m3_u = (location.protocol=='https:'?'https://ads.admarvel.com/fam/javascriptGetAd.php':'http://ads.admarvel.com/fam/javascriptGetAd.php');
var m3_r = Math.floor(Math.random()*99999999999);
var queryString = '?partner_id='+partnerId;
queryString += '&site_id='+siteId;
queryString += '&target_params=' + targetparams_str;
queryString += '&version=1.5';
queryString += '&language=javascript';
queryString += '&format=wap';
queryString += '&cb='+m3_r;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
alert(xmlhttp);
xmlhttp.onreadystatechange=function()
{
alert(xmlhttp.readyState);
if (xmlhttp.readyState==4)
{
alert("response "+xmlhttp.responseXML);
console.log(xmlhttp.responseXML);
//document.getElementById('ad').innerHTML = xmlhttp.responseText;
//document.write("<scr"+"ipt type='text/javascript'>");
//document.write(xmlhttp.responseText);
//document.write("<\/scr"+"ipt>");
}
}
xmlhttp.open("GET",m3_u+queryString,false);
xmlhttp.setRequestHeader('Content-Type','text/javascript');
xmlhttp.send();
But the response that I am getting is null .
When I hit the url in the broser , it properly returns me a javascript code block .
What is the right way to do this?
I think you are trying to do Cross site XMLHTTPRequest.
You have to handle Cross Site XMLHttpRequest differently. If you implement in Java you may follow below URL
http://mytechbites.blogspot.com/2009/07/cross-domain-xmlhttprequest-calls.html
Otherwise use jQuery.ajax.