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.
Related
First question on StackOverflow so I hope i get this right. I have a AJAX call to a JS function :
function addOptionText(str)
{
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("0").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","AddText.php?q="+str,true);
xmlhttp.send();
}
And Here is my HTML code :
<body>
<FORM NAME ="form6" onclick= "addOptionText(this.value)" >
Text Input:
<INPUT TYPE = "TEXT" VALUE placeholder ="Nume Field" NAME ="Text_Field">
<INPUT TYPE = "Submit" Name = "Edit" VALUE = "Add" >
</FORM>
<p id="0"> </p>
</body>
The php file only contains :
<html>
<body>
<?php
$name = ($_GET['q']);
echo "nume";
?>
</body>
</html>
But the function doesn't appear to be used as the paragraph doesn't change. New to php here and trying to understand how it works so I'm thinking something might've slipped me.
EDIT
I had more than one "submit" id's so that's why it didn't work. I changed the "submit" id from to and now all's working as intended.
Unfortunately, your code is all over the place.
<FORM NAME ="form6" onclick= "addOptionText(this.value)" > is wrong for a multitude of reasons.
First, we don't use onclick on the form itself but on the submit button. Secondly the value you put in the parameter doesn't in any way represent the value of the text box.
Since you want just to display the value of your textbox and not to navigate to a different page, modify your <form> tag, so that it doesn't have an action = "some page" attribute, because that way it will automatically redirect you to the page you specify and thus the AJAX request is rendered useless. Instead, modify your tag so that it looks like this:
<form name = "form6" onsubmit = "return false;">Provided that you specify your input/button type to submit: type= "submit", using the onsubmit event and setting it to return false will prevent the form from sending you over to a new page.
When using Vanilla JavaScript and not jQuery, I believe its more efficient to use IDs, so as to identify your HTML elements easier in JavaScript.
Your PHP code doesn't mean anything at all. Before doing anything else, you need to evaluate if, indeed, the q was sent over to the PHP file with the GET method. To do that, use in your php file:if (isset($_GET["q"])): // Your codeendif;
The line: echo "nume" you wrote will output "nume" regardless of what you have actually sent to your php file with the AJAX request.
In my opinion is pretty useless to still provide support for Internet Explorer 5 and 6. Not many people use it, unless for whatever reason they are mentally bound to it.
Analytically, how your files should be:
HTML:
<body>
<form name = "form6" onsubmit = "return false;">
Text Input:
<input type = "TEXT" placeholder ="Nume Field" id = "textfield" name = "Text_Field"/>
<input id = "submit" type= "submit" Name = "Edit" value= "Add"/>
</form>
<p id = "0"> </p>
<script src = "YOUR JAVASCRIPT FILE" type = "text/javascript"></script>
</body>
JavaScript:
var textfield = document.getElementById("textfield");
var submit = document.getElementById("submit");
submit.onclick = function() {
'use strict';
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("0").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "AddText.php?q=" + textfield.value, true);
xmlhttp.send();
};
PHP:
<?php
if (isset($_GET["q"])):
echo ($_GET["q"]);
endif;
?>
Here i want to pass the 'q' value from ajax to controller function in codeigniter.
ajax code:
function getdata(str)
{
if (str == "") {
document.getElementById("yer").innerHTML = "";
return;
} else {
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("bus").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","<?php echo site_url('money_c/taxcalculator1'); ?>?q="+str,true);
xmlhttp.send();
window.location="<?php echo site_url('money_c/taxcalculator'); ?>"
}
}
controller:
function taxcalculator1()
{
$bt=$_GET['q'];
echo $bt;
}
Here i want to pass the 'q' value from ajax to controller function in codeigniter.
As soon as you have started the Ajax request sending with this:
xmlhttp.send();
You leave the page with this:
window.location="<?php echo site_url('money_c/taxcalculator'); ?>"
… which aborts the Ajax request, removes the place you are trying to edit with innerHTML and destroys the JavaScript that would be trying to do that anyway.
If you want to use Ajax then:
Put the data you want to show to the user the response from taxcalculator1
Use onreadystatechange to show it to the user
Don't leave the page before that happens (remove the window.location line).
If you want to load an entirely new page:
Don't use Ajax
Just submit a form to a URL
Display the data you want the user to see (in the form of an HTML document) in the response to that request
I am having a simple html page for login. The html will look like,
<form action="createUsers.html" method="post" onsubmit="return loginValidation();">
I am using the ajax for it. if the user is not available, it will display error msg in the login page. else it will navigate the user to createUsers.html page.
The javascript file will look like and it will call the servlet,
if((document.getElementById("user").value !="")&& (document.getElementById("pass").value != "")){
var params = "&user=" + uname + "&pass=" + upwd;
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 result = xmlhttp.responseText;
}
}
xmlhttp.open("POST","login",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params);
alert(result)
if(result=="success"){
return true;
}
else if(result=="failure") {
document.getElementById("errormsg").innerHTML=xmlhttp.responseText;
return false;
}
}
This ajax call will check for the user in the database and it will return success if the user is available.
The problem is that, always the code is calling the else if statement, even if the value of result is success. Even the alert statement is also displayed as success. I am not sure why it is not comparing the result=="success" statement ?
AJAX are by default asynchronous calls...
Your callback function is actually returning value (true/false) to xmlHttp object through onreadystatechange but not to your validation function which is associated to HTML window DOM object. Your validation function simply returning true to your form submit event and that's why you anyway make it navigate/submit to next page...
You should call form.submit from your callback function itself on success result, you just need to retrieve form element object in your callback. And add "return false" in 'onSubmit' to avoid form getting submitted automatically.
Hope you understood the problem.
if ((document.getElementById("user").value != "") && (document.getElementById("pass").value != "")) {
var params = "&user=" + uname + "&pass=" + upwd;
// declare it here
var result;
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) {
// accessing to parent scope`s variable
result = xmlhttp.responseText;
callback(result);
}
}
xmlhttp.open("POST", "login", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
function callback (data){
var result = data;
alert(result)
if (result == "success") {
return true;
}
else if (result == "failure") {
document.getElementById("errormsg").innerHTML = xmlhttp.responseText;
return false;
}
}
}
Your callback function is actually returning value (true/false) to onreadystatechange but not to your validation function. Your validation function simply returning true to your form submit event and that's why you anyway make it navigate/submit to next page...
You should call form.submit from your callback function itself on success result, you just need to retrieve form element object in your callback. And add "return false" in 'onSubmit' to avoid form getting submitted automatically.
Hope you understood the problem.
I got this registration code which was working fine but I decided to add AJAX to make it more dynamic but when I run it, my PHP code was saving null value to database.
This is what I know so far: whenever a user writes information in signup page it goes to AJAX and the ajax pass it along to php and then php saves the info into database and it echo a message and then it goes to ajax and then it displays the message. All of this works the only problem is that my php code is saving null value no matter what i write in signup page.
and i think this is the code thats not working properly but i just dont know the other way
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "signip_parse.php?username="+username+"&password="+password;
the following is rest of my code. this is the page were user puts information and its saved as signup.php
<head>
<script src = "ajax.js"></script>
<div id="content">
</head>
<body>
<form action="signip_parse.php" method="post" id="registration_form">
<p>Name <input type="text" name="username" id = "username"/></p>
<p>Password <input type="password" name="password" id = "password"/></p>
<p><input type = "button" value="sign up" id="submit" onclick = "hello()"/>
<input type="button" value="Back" onclick="return back()"/></p>
</form>
<div id="ack"><p>1</p></div>
</div>
</body>
and this is the ajax code that I got it from w3school ajax example and i saved it as ajax.js
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");
}
return xmlhttp;
}
var HTTP = loadXMLDoc();
function hello(){
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "signip_parse.php?username="+username+"&password="+password;
HTTP.onreadystatechange=function()
{
if (HTTP.readyState==4 && HTTP.status==200)
{
document.getElementById("ack").innerHTML=HTTP.responseText;
}
}
HTTP.open("POST", url ,true);
HTTP.send();
}
and last this is the signip_parse.php where i managed to spell signup wrong
<?php
include_once("connect.php");
$user = mysql_real_escape_string( $_POST["username"]);
$password = mysql_real_escape_string( md5 ($_POST["password"]));
$sql = "INSERT INTO users (username, password) VALUES ('$user','$password')";
if(mysql_query($sql)){
echo "You have been successfully registered";
}
else{
echo "Something went wrong try again";
}
?>
Any help would be great. thanks guys
and yes i know md5 is broken but this is just a demo and intend to used something else.
Since you're sending a request as post, its important to add this on your XMLHttpRequest object:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
And just combine them inside, no need to separate some parts. It would look something like this:
<script type="text/javascript">
function hello() {
var xmlhttp = new XMLHttpRequest();
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("ack").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST", 'signip_parse.php', true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("username="+username+"&password="+password);
}
</script>
Here's what it would look like
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Ref: https://stackoverflow.com/a/12860140/3859027
You should consider also (if you're using PHP 5.5 or greater) to use PHP's native password hashing and replace that md5() instead. If you're below v5.5 then you could use the its compatibility pack
There's a form users fill out and click the submit button. The data gets sent back to the server and based on the servers server's response the form is submitted or not (and the page is redirected or not). The problem is the form always submits and the page redirects before the server's response is received.
function SubmitForm(name, data1)
{
var result;
var checkResult = function(result)
{
alert("final value is: "+result)
return result
}
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)
{
result = true
}
else
{
document.getElementById("report").innerHTML = "blah blah blah"
result = false
}
checkResult(result)
}
}
xmlhttp.open("POST", "Checkdata1.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send("name="+encodeURIComponent(name.value)+"&data1="+encodeURIComponent(data1.value))
//return false
}
Here's the HTML for the form that calls the above JavaScript function.
<form onsubmit="return isPasswordCorrect(document.getElementById('name'), document.getElementById('txtField1'))" action="nextpage.php" method="GET">
I know the idea is for the function to return false to prevent the form from being submitted, but how do I get it to wait long enough for the server to reply through Ajax? By the way, I haven't needed JQuery and if it's not necessary I'd prefer not to start using it now.
I would use a <button> that doesn't submit the form (the type isn't "submit"):
<form ...>
...
<button onclick="SubmitForm(...)">Submit</button>
</form>
Then at the end of SubmitForm, you can put:
document.querySelector("form").submit();
When you want to submit the form.