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()
Related
I made a simple chat. It's working properly, but not behaving as expected. When a user submits a message, the user's name, time and message are supposed to display.
It so happens that the username and response appear first and the time seems to be inserting itself after a slight delay (that's the lag). I can't figure out why, especially since the response is (or at least seems to be) sent as a whole and nothing is being inserting once the response is sent from the server...
Here's the link to the chat. You can input dummy username and dummy messages.
And here are the important pieces of code:
PHP
while ($row = $result->fetch_assoc()) {
$time = date('g:ia', $row['time']);
echo "<p class=\"message\"><i>{$row['username']}</i> ($time): {$row['content']}</p>";
}
JavaScript
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
document.getElementById('messagesArea').innerHTML = ajax.responseText;
}
};
Your culprit is this section of the script:
var content = document.getElementById('messageBox').value;
if ( content === '') {
return;
} else {
var ajax = new XMLHttpRequest();
var username = document.getElementById('signedin').innerHTML;
document.getElementById('messageBox').value = '';
ajax.open('POST', 'postmessage.php', true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
// if there are errors echoed from the PHP file
if (ajax.responseText != "") {
document.getElementById('mysqliError').innerHTML = ajax.responseText;
return;
}
document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
}
};
ajax.send('username=' + username + '&content=' + content);
}
Notice this line: document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
You are inserting the message, without the time, into #messagesArea. Then, in getRecentMessages later, it is set to fetch the entire chat log from displaymessages.php and overwrite #messagesArea with the content of the output, which does have the time.
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.
I have a registration form and when everything checks out and the registration button (submit button for the form) is clicked, it runs all of the following code. the /xhrCreateUser method in my PHP controller further validates, sanitizes, and inserts the POST data into a database. For simple error checking for now, if the echo from the /xhrCreateUser method is true, then it alerts the user that the account has been created and it redirects the page. However, when the redirect method is called, the browser offers to save the password when the user is redirected. I would like this behavior to happen on something like a login form, but not a registration form. If the redirect is not called, the Offer to save the password does not trigger, so obviously it is that that is triggering chrome to offer to save the password. I don't get why this is happening, it does not do employ this behavior in Firefox. Is it something to do with me posting the value of a password input element or something?
I imagine chrome does this to support ajax login forms, but its also doing this on my registration form, which is not ideal.
register.addEventListener('click', function(e){
if(validateName(0)){
if(validateName(1)){
if(validateUsername(2)){
if(validateEmail(3)){
if(validatePassword(4)){
//Start XML HTTP Account Insertion
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function register(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var result = xmlhttp.responseText;
console.log(result);
if(result.indexOf('true') > -1){
alert("Account has been created, you will be redirected");
redirect();
//redirect
} else {
alert("Something went wrong, that's all we know. Please refresh the page and try again.");
}
}
}
xmlhttp.open("POST", "user/xhrCreateUser", true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(JSON.stringify({firstname:firstname.value, lastname:lastname.value, username:username.value, email:email.value, password:password.value}));
} else {
//password is bad
//toggle error classes for CSS here
forceError(4);
password.focus();
}
} else {
//email is bad
//toggle error classes for CSS here
forceError(3);
email.focus();
}
} else {
//username is bad
//toggle error classes for CSS here
forceError(2);
username.focus();
}
} else {
//lastname is bad
//toggle error classes for CSS here
forceError(1);
lastname.focus();
}
} else {
//firstname is bad
//toggle error classes for CSS here
forceError(0);
firstname.focus();
}
});
Solved
Making the POST synchronous and not asynchronous worked by changing true to false in the xmlhttp.open line worked.
So I have this program in which the user enters a city and a country. The program looks in the database to see if the city doesn't already exists, if it does I show a warning message using ajax, if not i add the city to the database.
This is the form:
<form action="addCity.php" method="get" onsubmit="return validateCityInfoForm();">
onsumbit I call the javascript function validateCityInfoForm() that looks like this:
function validateCityInfoForm() {
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)
{
if (xmlhttp.responseText == "true") {
document.getElementById("checkIfCityExistsWarning").style.display = "block";
document.getElementById("checkIfCityExistsWarning").innerHTML = "This city already exists!";
return false;
}
}
}
xmlhttp.open("GET", "checkIfCityExists.php?city=" + cityInput + "&country=" + countryInput, true);
xmlhttp.send();
}
checkIfCityExists.php echoes "true" if the city already exists in the database and "false" otherwise.
The problem is that it always adds the city in the db even though the city already exists.
checkIfCityExists.php returns "true" but it doesn't seem to matter.
I really don't know what the problem is, any help would be greatly appreciated.
Thanks!
here is checkIfCityExists.php:
<?php
include ('database_connection.php');
$city = mysqli_real_escape_string($dbc, $_GET['city']);
$country = mysqli_real_escape_string($dbc, $_GET['country']);
//check if the city and country already exists in the database
$query_verify = "SELECT * FROM city WHERE name = '$city' AND country = '$country'";
$result_verify = mysqli_query($dbc, $query_verify);
if(mysqli_num_rows($result_verify) == 0) { //if the city does not appear in the database
echo "false";
}
else {
echo "true";
}
?>
You are trying to make an asynchronous call to do validation. By the time the call comes back it is too late because the form already is submitted.
Tha Ajax call does not pause the code execution, it makes the call and the rest of the code happens.
What you would need to do it break it up into two steps, make the Ajax call and when the onreadystatechange comes back, submit the form.
The problem is, your onsubmit has no return.
So validateCityInfoForm() returns undefined which does not prevent the Browser from executing the action. validateCityInfoForm() should return false to prevent the Browser from submitting the form. And then in the onreadystatechange call form.submit() if necessary.
I am trying to send some parameters through xmlHttpRequest.send(params) written in a JS file to my servlet where I try to get the parameters by req.getParameter("some_Parameter"); it returns null on the servlet. though if i send the parameters by appending them in url it works fine. but when the url will be large it will break the code. so please someone help me out.
Thanks in advance.
function doHttpPost(theFormName, completeActivity)
{
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
var xmlMessage = buildPOST(theFormName, completeActivity);
var responseTxt;
try {
xmlhttp.Open(document.forms[theFormName].method, document.forms[theFormName].action+'?'+xmlMessage, false);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
responseTxt = xmlhttp.responseText;
}
}
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
enableDisableLinks(true);
setPointer();
xmlhttp.Send();
if(xmlhttp.Status != 200) {
alert("Post to server failed");
}
} catch (e) {
responseTxt = "Exception while posting form data: Error No: " + e.number + ", Message: " + e.description;
}
resetPointer();
enableDisableLinks(false);
var expectedTxt = "Form Data had been successfully posted to the database."
if(responseTxt.toString() == expectedTxt.toString()) {
// MNP: New requirement from Jeanne, should not refresh CM page, commenting it off for now
//if(completeActivity) {
// if (typeof (ViewCaseDetailBtn) != 'undefined') {
// ViewCaseDetailBtn.click();
// }
//}
return true;
} else {
alert (responseTxt);
}
return false;
}
BUGS
//IE only - shooting yourself in the
// Not all IE versions use ActiveX!
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); foot.
//JavaScript case sensitive, open !== Open
xmlhttp.Open(document.fo...
//JavaScript case sensitive, send !== Send
xmlhttp.Send();
//JavaScript case sensitive, status !== Status
xmlhttp.Status
AND if you are using synchronous, it does not call the onreadystatechange.
If you are using POST, the value needs to be in send("valuestosendup") not on the querystring.
This code shows why you should really use a framework to make Ajax calls and to not roll your own.