Form submission determiend on Ajax response - javascript

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.

Related

Ajax trying to execute PHP page brings me to a new page

I am trying to get a live chat working using PHP and mysql and AJAX. It is almost completely functioning, except I cant seem to figure out how to submit the chat message without reloading a page. I have a page, sendchat.php, that takes input from the previous page and enters the data into a database. I am trying to use a text input field and when the user clicks the enter key, it would execute the PHP page with the details needed to send to sendchat.php without actually loading or refreshing the page. This is what I have so far:
<form id="send-message-area">
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeydown="onChatEnter(this);"></textarea>
</form>
</div>
</td></tr></table>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
function onChatEnter(str) {
if(event.key === 'Enter') {
$.ajax({
type: "GET",
url: "sendchat.php?msg=" + str ,
success : function() {
// here is the code that will run on client side after running clear.php on server
}
});
}
</script>
All it does is try to load the url, but its not trying to find sendchat.php or send the data. Instead it just tries to load a blank page. Where am I going wrong here? Everything seems spelled correctly and case sensitive. I check if the user pressed enter when they press a key. If they did, I am loading an AJAX function to execute a PHP page. Yet, it is not doing that. Just for FYI, I do not want a button there to be clicked.
EDIT:
I tried the suggestions below and still nothing. I decided to try a different approach now. Still doesn't work.
<script>
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").innerHTML="";
return;
}
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 (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","sendchat.php?msg="+str,true);
xmlhttp.send();
}
}
</script>
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeypress="updatechat(this.value);"></input>
Try this:
$("#send-message-area").submit(function(e) {
e.preventDefault();
e.stopPropagation();
});
I am not sure how.. But I fixed it.. I think it had to do with giving the input a name along with the ID. See below:
<script language="javascript" type="text/javascript">
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").innerHTML="";
return;
}
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 (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
var planetloc = document.getElementById("loc").value;
chaturl = "sendchat.php?msg="+str+"&loc="+planetloc;
sendie.value="";
xmlhttp.open("GET",chaturl,true);
xmlhttp.send();
}
}
//-->
</script>
This was the code I used for the html:
<p>Your message: </p>
<input type='text' id='sendie' name='sendie' maxlength = '100' onkeypress='updatechat(this.value);'></input>
<input type='hidden' id='loc' name='loc' value='$chatroom'></input>";
I also added chaturl to combine the ajax page I needed along with the parameters passed to it. It seemed by creating a variable for that it solved other issues too.

How to pass ajax variable value to controller in codeigniter

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

Login form validation using xmlHttpRequest

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.

Ajax code is not working

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.

Username and Password in URL

I am trying to load an XML file that asks for a username and password.
The code I'm using is as follows that I am trying to send the username and password in the URL:
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false);
The full code of my page looks like this:
<html>
<body>
<textarea id="test1" name="test1" cols="90" rows="30">
XML file will be displayed here
</textarea><br>
<script type="text/javascript">
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("test1").value=xmlhttp.responseText;
} else
{
alert('Panel not communicating.Reason: '+xmlhttp.status);
}
}
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false);
xmlhttp.send();
</script>
</body>
</html>
Anyone know what I am doing wrong?
First, add this function to create the authorization header contents:
function make_base_auth(user, password)
{
var tok = user + ':' + pass;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
Then, call the function and store the return value in a separate variable:
var auth = make_basic_auth('admin', 'admin');
Lastly, pass the value of auth to the XMLHttpRequest object:
xmlhttp.setRequestHeader('Authorization', auth);
xmlhttp.send();
Attribution: http://coderseye.com/2007/how-to-do-http-basic-auth-in-ajax.html
I ended up getting it working by doing the following:
Change:
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false);
To:
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false,"username","password");
See this question for a similar scenario. How to use Basic Auth with jQuery and AJAX? Note one answer states that IE does not support credentials in a URL (as you are attempting to do).

Categories