Member Avatar for Member #743307

Hi everyone. I am starting to learn AJAX and JavaScript and I am trying to make a popup login form and I am having trouble posting the data entered in the textboxes. It is fine when I post one piece of data but when I try to post two I get into difficulties. The code is below. If I have not made anything clear I will try to comment back with some more information.

Thanks in advance,
Cameron

<html>
<head>
<script type="text/javascript">
 
var time_variable;
 
function getXMLObject()  //XML OBJECT
{
   var xmlHttp = false;
   try {
     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
   }
   catch (e) {
     try {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
     }
     catch (e2) {
       xmlHttp = false   // No Browser accepts the XMLHTTP Object then false
     }
   }
   if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
     xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
   }
   return xmlHttp;  // Mandatory Statement returning the ajax object created
}
 
var xmlhttp = new getXMLObject();	//xmlhttp holds the ajax object
 
function ajaxFunction() {
  var getdate = new Date();  //Used to prevent caching during ajax call
  if(xmlhttp) { 
  	var username = document.getElementById("username");
    xmlhttp.open("POST","testing.php",true); //calling testing.php using POST method
    xmlhttp.onreadystatechange  = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send("username=" + username.value); //Posting txtname to PHP File
	}
}

 
function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
       document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element 
     }
     else {
        alert("Error proccessing form. Please try again");
     }
   }
}
</script>
<body>
<div align="center">
<form name="login">
<table width="50%" cellpadding="7">
<tr>
	<td>
    Username
    </td>
    <td>
    :
    </td>
    <td>
   <input type="text" name="username" id="username" maxlength="12" style="background-image:url(images/coins.ico); background-repeat:no-repeat; background-position:right;" class="login-user" />
    </td>
</tr>
<tr>
	<td>
    Password
    </td>
    <td>
    :
    </td>
    <td>
    <input type="password" name="password" id="password" maxlength="12" style="background-image:url(images/login-password.png); background-repeat:no-repeat; background-position:right;" class="login-pass" />
    </td>
</tr>
<tr>
	<td>&nbsp;
    
    </td>
    <td>&nbsp;
    
    </td>
    <td>
   <input type="button" value="Submit" onclick="ajaxFunction();" />
    </td>
</tr>
</table>
<div id="message" name="message"></div> 
</form>
</body>
</head>
</html>

I have tried doing this

var username = document.getElementById("username");
var password = document.getElementById("password");
    xmlhttp.open("POST","testing.php",true); //calling testing.php using POST method
    xmlhttp.onreadystatechange  = handleServerResponse;
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send("username=" + username.value);
 xmlhttp.send("password=" + password.value);

but it doesn't work.

Dani AI

Generated

Nice question, @doctorphp. And +1 to for pointing out that send() must be called exactly once. A clean, modern way to post multiple fields today is fetch with URLSearchParams (the browser will handle encoding for you):

// Post username + password as x-www-form-urlencoded
const form = document.forms.login;
const body = new URLSearchParams({
  username: form.username.value,
  password: form.password.value
});

fetch('testing.php', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
  body,
  credentials: 'same-origin'  // include PHP session cookies
})
.then(r => r.text())
.then(html => { document.getElementById('message').innerHTML = html; })
.catch(console.error);

Re: your follow-up about uploading an image (Post #4): use FormData. Do not set the Content-Type header; the browser will add the correct multipart boundary. Add a file input (e.g. <input type="file" id="image" name="image">) and:

// Upload an image + fields with Ajax
const form = document.forms.login;
const fd = new FormData();
fd.set('username', form.username.value);
fd.set('password', form.password.value);
fd.set('image', document.getElementById('image').files[0]);

fetch('testing.php', {
  method: 'POST',
  body: fd,                 // no manual Content-Type
  credentials: 'same-origin'
})
.then(r => r.text())        // or .json() if your PHP returns JSON
.then(msg => { document.getElementById('message').innerHTML = msg; })
.catch(console.error);

Quick tips:

  • PHP will read fields in $_POST['username'], $_POST['password'], and the file in $_FILES['image'].
  • For cross-origin requests, configure CORS and keep credentials aligned with your cookie policy.
  • Always use HTTPS and validate on the server; JavaScript checks are just convenience.

Recommended Answers

All 4 Replies

WRONG:

xmlhttp.send("username=" + username.value);
 xmlhttp.send("password=" + password.value);

You cannot call send() multiple times. You must call it exactly once. To pass multiple parameters you must separate each value with an ampersand and you should encode each value:

xmlhttp.send("username=" + encodeURIComponent(username.value) + "&password=" + encodeURIComponent(password.value) );
Member Avatar for Member #743307

Thank you very much. I really appreciate your help.

Member Avatar for Member #743307

How would I upload a file (image) using this method?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.