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.
Related
I have an anchor link with no destination, but it does have an onClick event:
<li><a href onClick='deletePost()'> Delete </a> </li>
I understand that I cannot directly execure PHP code blocks in JavaScript due to the nature of PHP and it being a server side language, so I have to utilize AJAX to do so.
When the delete link is clicked, I need it to execute this query (del_post.php)
<?php include("connect.php");
$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = 'id' ");
?>
I have tried to understand AJAX using similar past questions, but due to being relatively new, I cannot completely grasp it's language. Here is what I have tried:
function deletePost() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
}
}
But clicking the link just changes the URL to http://localhost/.
I believe the (main) problem is your empty "href" attribute. Remove that, or change it to href="#" or old school href="javascript:void()" (just remove it, imo).
It's been a while since I used XMLHttpRequest and not something like jQuery's .ajax, but I think you need to do it like so (mostly you need to .open/send before you watch for the state change):
var xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq) {
xmlHttpReq.open('GET', 'your-uri-here.php', true/false);
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
console.log('success! delete the post out of the DOM or some other response');
}
else {
console.log('there was a problem');
}
}
xmlHttpReq.send();
}
Can you please provide your : del_post.php file?
Normally you can show a text or alert in a
<div id="yourname"></div>
by using callback in an AJAX request :
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("yourname").innerHTML = xmlhttp.responseText;
}
This response is coming from your PHP file for example :
function remove_record(ARG){
if ($condition==true)
echo "TRUE";
else
echo "FALSE";
}
You should remove href attribute from anchor tag and style the element with CSS.
Also, your script should look like this:
<script>
function deletePost() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Do something if Ajax request was successful
}
};
xhttp.open("GET", "del_post.php", true);
xhttp.send();
}
</script>
You are trying to make the http request inside the callback.
You just need to move it outside:
function deletePost() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
Removing the href attribute will prevent the refresh. I believe that is valid in HTML5.
Ok... I'm just a hobbyist, so please forgive me any inaccuracies in the typing but this works: A format I use for an ajax call in an <a> element is:
<a href="javascript:" onclick="functionThatReallyCallsAjax()">
So that I have more flexibility(in case I need to check something before I send the ajax). Now, for an ajax call you need:
What file to call
What to do with the response from the file you called
What to do if an I/O error happens
So we have this function - not mine, leeched amongst thousands from somewhere - probably here :) - and probably well known, my apologies to the author, he is a genius: This is what you call for the ajax thing, where 'url' is the file you want to 'ajax', 'success' is the name of the function that deals with results and error is the name of the function that deals with IO errors.
function doAjaxThing(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
You will naturally need to include the success+error functions:
function dealWithResponse(textFromURL)
{
//textFromURL is whatever, say, a PHP you called in the URL would 'echo'
}
function ohNo()
{
//stuff like URL not found, etc.
alert("I/O error");
}
And now that you're armed with that, this is how you compose the real call inside the function you called at the <a>:
function functionThatReallyCallsAjax()
{
//there are probably many scenarios but by having this extra function,
//you can perform any processing you might need before the call
doAjaxThing("serverFile.php",dealWithResponse,ohNo);
}
One scenario might be when you need to pass a variable to the PHP you didn't have before. In this case, the call would become:
doAjaxThing("serverFile.php?parameter1=dogsRock",dealWithResponse,ohNo);
And now not only you have PHP sending stuff to JS, you have JS sending to PHP too. Weeeee...
Final words: ajax is not a language, its a javascript 'trick'. You don't need to fully understand what the first 'doAjaxThing' function does to use this, just make sure you are calling it properly. It will automatically 'call' the 'deal WithResponse' function once the response from the server arrives. Notice that you can continue doing your business (asynchronous - process not time-tied) till the response arrives - which is when the 'deal WithResponse' gets triggered -, as opposed to having a page stop and wait (synchronous - time tied) until a response arrives. That is the magic of ajax (Asynchronous JAvascript and Xml).
In your case you want to add the echo("success") - or error! - in the PHP, so that the function 'dealWithResponse' knows what to do based on that info.
That's all I know about ajax. Hope this helps :)
Question as stated above. I am using older browsers (IE8 and FF8) due to corporate policy. I can't fix this but my research says this isn't the issue...(yeah right;)
I'm using PHP 5.5.12 on Apache 2.4.9 with a MySQL (5.6.17) back end. The site is a CMS that has grown organically over several years.
I have a user admin page that adds, updates, and deletes accounts. However, no matter what I have done the form submits. The worst example is if the admin chooses to delete an account and when asked 'Do you really wish to DELETE...?' and cancels, it is still deleted! I've copied my JavaScript and an excerpt from the PHP/HTML below.
I have tried a few changes to my JavaScript like returning after setting the window.event.returnValue but I've always gotten the same results. I've been reading for several days now and keep coming up blank! I've tried onSubmit instead of onClick but it really doesn't suit the site, besides it didn't work either.
I'm beginning to think the age of the browsers is the issue. I run this with Safari on my home development box fine. Any help would be appreciated.
JavaScript
<script language="JavaScript">
function frmVerify(check, loginid, login) {
if (check == 'add') {
Uname=add_user.login_name.value;
Pass1=add_user.password.value;
Pass2=add_user.password2.value;
if(Uname=='') {
alert('A user name must be assigned to an account.');
window.event.returnValue=false;
}
if(Uname == login) {
alert('You cannot create an account with your own username (' + login + ')');
window.event.returnValue=false;
}
if(Pass1 != Pass2) {
alert('Entered passwords are not the same! Make sure the password and verification fields match.');
window.event.returnValue=false;
}
if(Pass == '') {
alert('Assigning a password is required when creating an account!');
window.even.returnValue=false;
}
} else if(check == 'update') {
Uname=eval('edU_'+loginid+'.login_name.value');
Pass1=eval('edU_'+loginid+'.password.value');
Pass2=eval('edU_'+loginid+'.password2.value');
if(Uname == '') {
alert('A user name must be assigned to an account.');
window.event.returnValue=false;
}
if(Pass1 != Pass2) {
alert('Entered passwords do not match! Make sure the passowrd and verification fields match.');
window.event.returnValue=false;
}
} else if(check == 'del') {
Uname=eval('edU_'+loginid+'.login_name.value');
if(Uname == '') {
request = 'Do you really wish to DELETE this user account?';
} else {
request = 'Do you really wish to DELETE user: ' + Uname + '?';
}
var answer = confirm(request);
if(answer) {
window.event.returnValue=true;
} else {
window.event.returnValu=false;
}
}
}
</script>
In the PHP/HTML I have
echo "<form name=\"delU_$login_id\" id=\"delU_$login_id\" mehtod=\"POST\">";
echo "<input type=\"image\" src=\"./images/delete.png\" value=\"Delete\" onClick=\"return frmVerify('del', '$login_id', '$username');\">";
echo "</form>";
window.event.returnValue (which you don't always spell correctly anyway) is non-standard and shouldn't be used.
You're using 1990s style intrinsic event attributes instead of addEventListener, so just:
return false;
If you were using addEventListener then you would:
event_object.preventDefault();
where event_object is the first argument to your event handler function.
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.
Hello i'm using this code. i have a problem in this. when i enter input in my input box, it is fine. but when i press enter the page is refreshing for a sec and the input box is auto clearing.
<script>
function book_suggestion() {
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "book-suggestion.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
The reason your page is reloading is because <form> elements catch enter presses.
Catching an enter press will submit the form.
Submitting a form without an action="" attribute will submit to the same page.
Submitting to a page that doesn't handle the request will simply reload the page, and your form input will be reset to blank.
To fix this, disable submit-on-enter by using javascript to catch a keypress equal to 13 and return false or cancel the event.
<input type=text id=book onKeyUp="book_suggestion( event )">
... [snip] ...
function book_suggestion( e ){
if( e.which == 13 ){
e.preventDefault();
e.stopPropagation();
return false;
}
... [snip your code] ...
That should do the trick.
For what it's worth, people on Stack Overflow don't generally like to modify your code at your request. This is a simple fix that can be found by Googling for the keywords ("catch keypress", "cancel event", etc.).
If I understand you, you want to submit yourself form data. You should return false within book_suggestion() function. And add onsubmit to <form> element. Make sure it should have return. Like that:
<form onsubmit="return book_suggestion();">
Here's how the situation looks :
I have a couple simple forms
<form action='settings.php' method='post'>
<input type='hidden' name='setting' value='value1'>
<input type='submit' value='Value1'>
</form>
Other small forms close to it have value2, value3, ... for the specific setting1, etc.
Now, I have all these forms placed on the settings.php subpage, but I'd also like to have copies of one or two of them on the index.php subpage (for ease of access, as they are in certain situations rather frequently used).
Thing is I do not want those forms based on the index.php to redirect me in any way to settings.php, just post the hidden value to alter settings and that's all.
How can I do this with JS ?
Cheers
Yes, you could use an ajax call to send a request to the settings.php file. You'd probably want that PHP code to return something that the JavaScript can use to know if the request was successful or not (for example, using JSON instead of HTML).
Here is an ajax getData function.
function getData(dataSource, targetDiv){
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP");
}
if(XMLHttpRequestObject) {
var obj = document.getElementById(targetDiv);
XMLHttpRequestObject.open("GET", "settings.php?form="+dataSource+"&t="+new Date().getTime());
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
use this function to send the form to your setting.php file which should return confirmation message to index.php(inside targetDiv).
Parameters of the function
1) dataSource - is the variable value that you send to settings.php
2) targetDiv - is the div on index php that with display the response from settings.php
Hope it makes sense.