I am new to AJAX and learning it. I am searching a food item in my HTML textbox and trying to communicate with the server to know if the item is available. The respective status of the item should be shown in the div tag below the textbox but it is not showing.
I haven't studied jQuery yet and would like to know the below things:
How to get the response from the server in plaintext using AJAX and JavaScript, and display it in the div tag below the textbox (advise the changes to be made in the code).
What change should I make in JavaScript code to send the AJAX request in POST method (I know about the changes in PHP code)?
//index.html
<head>
<script type="text/javascript" src="food.js">
</script>
</head>
<body>
<h3>The Cheff's Place</h3>
Enter the food you want to order
<input type="text" id="userInput" name="input" onkeypress="sendInfo()"></input>
<div id="underInput"></div>
</body>
</html>
//food.js
var request;
function sendInfo() {
var v = document.getElementById("userInput").value;
var url = "index.php?food=" + v;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request.readyState == 0 || request.readyState == 4) {
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send(null);
} catch (e) {
alert("Unable to connect to server");
}
}
}
function getInfo() {
if (request.readyState == 4) {
if (request.status == 200) {
var val = request.responseText;
document.getElementById('underInput').innerHTML = val;
}
}
}
//index.php
<?php
header('Content-Type: text/plain');
$food = $_GET['food'];
$foodArray = array("paneer", "butter", "chicken", "tandoori", "dal");
if (in_array($food, $foodArray))
{
echo "We do have " .$food;
}
elseif($food == "")
{
echo "Kindly enter some food";
}
else
{
echo "We do not sell " .$food;
}
?>
I ran your code. It's working fine. Just replace onkeypress with onkeyup.
<input type="text" id="userInput" name="input" onkeyup="sendInfo()"></input>
Using JQuery (Assuming you have included jquery file or cdn) :
Include the following snippet in script tag at the end of the body.
$("#userInput").keyup(function(){
$.get("index.php", { food: $("#userInput").val() })
.done(function(data) {
$("#underInput").html(data)
})
});
below is my code fo ajax which sends a string data via post method, the request is successful but I get an empty response. I had checked the readystate and status both are proper and the php file is in the same directory.
function getData(str)
{
if (str == "")
{
} else
{
if (window.XMLHttpRequest)
{
var dat = new XMLHttpRequest();
} else
{
dat = new ActiveXObject("Microsoft.XMLHTTP");
}
dat.open("POST","userdat.php",true);
dat.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
dat.onreadystatechange = function ()
{
if (dat.readyState == 4 && dat.status == 200)
{
alert(dat.responseText);
$('#dataReT').text(dat.responseText);
}
}
dat.send("userid=" + str);
}
}
content of my php file:
<?php
$id=$_REQUEST['userid'];
echo $id;
?>
there is no userid in $_REQUEST. Try to add this to your php file:
if(array_key_exists('userid',$_REQUEST)) {
echo $_REQUEST['userid'];
} else {
echo 'no userid.';
}
You may send userid value from your javascript file
I have form as follows, it require to sent an action to my java Servlet to do an update to the database.
How do I submit the form without the page get reloaded here?
Currently with action="myServlet" it keep direct me to a new page. And if I remove the action to myServlet, the input is not added to my database.
<form name="detailsForm" method="post" action="myServlet"
onsubmit="return submitFormAjax()">
name: <input type="text" name="name" id="name"/> <br/>
<input type="submit" name="add" value="Add" />
</form>
In the view of my Java servlet, request.getParameter will look for the name and proceed to add it into my db.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if (request.getParameter("add") != null) {
try {
Table.insert(name);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
In my JavaScript part, I have a submitFormAjax function
function submitFormAjax()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
alert(xmlhttp.responseText); // Here is the response
}
var id = document.getElementById("name").innerHTML;
xmlhttp.open("POST","/myServlet",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name=" + name);
}
A similar question was asked here
Submit form without reloading page
Basically, do "return false" after invoking the function. Something like this should work:
<form name="detailsForm"
method="post"
action="myServlet"
onsubmit="submitFormAjax();
return false;"
>
This is how I used to implement Ajax in JS without JQuery. As am a PHP and JS guy I cant possibly help you with Java Servlet side but yes heres my little help from JS side. This given example is a working example.See if it helps you.
// HTML side
<form name="detailsForm" method="post" onsubmit="OnSubmit(e)">
// THE JS
function _(x){
return document.getElementById(x);
}
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/json");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function OnSubmit(e) // call this function on submit
{
e.preventDefault();
var username = _("name").value;
if (username == "")
{
alert("Fill out the form first");
}
else
{
var all = {"username":username};
all = JSON.stringify(all);
var url = "Myservlet";
var ajax = ajaxObj("POST", url);
ajax.onreadystatechange = function()
{
if(ajaxReturn(ajax) == true)
{
// The output text sent from your Java side in response
alert( ajax.responseText );
}
}
//ajax.send("user="+username+");
ajax.send(all);
}
}
Thanks
Change the code in form
onsubmit="submitFormAjax(event)"
Change your JS code
function submitFormAjax(e)
{
e.preventDefault();
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
}
......
................
...............
return false; //at last line
I develop a Validation Form with Javascript All think as right
but I want when Al think are accepted send the information to the php file
How I can make that ?
The HTML code :
<?php
if(isset($_GET['submit'])){
$message = '';
$email = '';
$name ='';
$message = $_GET['comment'];
$email = $_GET['commentMail'];
$name = $_GET['commentName'];
$to = "emailme";
$subject = 'New Message';
$message = " Le nom : ".$name."<br><br>".$message."<br><br> Email : ".$email;
$header = "$email";
if(mail($to, $subject, $message, $header)){
echo '<b style="color: green">Messange Send</b>';
}
else{
echo '<b style="color: red">Sommthing wrong</b>';
}}
?>
<html>
<head>
<title>Contact</title>
<meta charset="UTF-8">
</head>
<body onload="randNums()">
<form>
<input id="commentName" onkeyup="validateName()" name="name" type="text" placeholder="Name"><label id="commentNamePrompt"></label><br>
<input id="commentMail" onkeyup="validateMail()" name="mail" type="text" placeholder="Mail"><label id="commentMailPrompt"></label><br>
<input id="commentPhone" onkeyup="validatePhone()" name="phone" type="text" placeholder="Phone"><label id="commentPhonePrompt"></label><br>
<textarea id="comment" onkeyup="validateComment()" name="commente" placeholder="Message here"></textarea><label id="commentPrompt"></label><br>
<span id="digit1"></span> +
<span id="digit2"></span> =
<input id="captcha" size="2" onkeyup="validateCaptcha()"><label id="captchaPrompt"></label><br>
</form>
<button href="index.php" name="submit" onclick="validateCommentForm()" > Send</button><label id="commentFormPrompt"> </label>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
js code
function randNums(){
var rand = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
document.getElementById("digit1").innerHTML = rand;
document.getElementById("digit2").innerHTML = rand2;
}
function validateName(){
var name = document.getElementById("commentName").value;
if (name.length == 0){
producePrompt("Name *", "commentNamePrompt", "red");
return false;
}
if(!name.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/))
{
producePrompt("name wrong","commentNamePrompt","red");
return false;
}
producePrompt("accept", "commentNamePrompt", "green");
return true;
}
function validatePhone(){
var phone = document.getElementById("commentPhone").value;
if(phone.length == 0){
producePrompt("phone *", "commentPhonePrompt", "red");
return false;
}
if(phone.length != 10){
producePrompt("10 numbers", "commentPhonePrompt", "red");
return false;
}
if(!phone.match(/^[0-9]{10}$/))
{
producePrompt("phone wrong","commentPhonePrompt","red");
return false;
}
producePrompt("Accept", "commentPhonePrompt", "green");
return true;
}
function validateMail() {
var mail = document.getElementById("commentMail").value;
if(mail.length == 0){
producePrompt("mail *", "commentMailPrompt", "red");
return false;
}
if(!mail.match(/^[A-Za-z._\-0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/))
{
producePrompt("Wrong mail","commentMailPrompt","red");
return false;
}
producePrompt("accept", "commentMailPrompt", "green");
return true;
}
function validateComment(){
var comment = document.getElementById("comment").value;
var required = 30;
var left = required-comment.length;
if (left > 0){
producePrompt(left + " lettre" ,"commentPrompt","red" );
return false;
}
producePrompt("accept", "commentPrompt", "green");
return true;
}
function validateCaptcha(){
var captcha = document.getElementById("captcha").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1 + digit2;
if(captcha.length == 0){
producePrompt("captcha *", "captchaPrompt", "red");
return false;
}
if(!captcha.match(/^[0-9]{1,2}$/) || !captcha.match(sum)){
producePrompt("Captchas wrong","captchaPrompt","red");
return false;
}
producePrompt("Accept", "captchaPrompt", "green");
return true;
}
function submitForm(){
var server = 'http://localhost/test'; // Your PHP file
var commentName = $('#commentName').val(); // The values of your form
var commentMail = $('#commentMail').val(); // The values of your form
var commentPhone = $('#commentPhone').val(); // The values of your form
var comment = $('#comment').val(); // The values of your form
$.ajax({ // Here the magic starts
url: server+"/index.php", // Where this function will send the values
type:"get", // To get the status of your php file
data: "action=insertNews&commentName="+commentName+"&commentMail="+commentMail+"&commentPhone="+commentPhone+"&comment="+comment, // The values
success: function (data){ // After sending the values to your php file you will receive number 1 or 2, if you receives number 1 it means sucess, but if you receives number 2 it means fail.
if(data == 'Messange Send'){
//
}
else{
//
}
}
});
}
function validateCommentForm(){
if(!validateName() || !validateMail() || !validatePhone() || !validateComment()){
jsShow("commentFormPrompt");
producePrompt("Invalide form","commentFormPrompt","red");
setTimeout(function(){jsHide("commentFormPrompt")}, 2000);
}
else
submitForm();
}
function jsShow(id){
document.getElementById(id).style.display = "block";
}
function jsHide(id){
document.getElementById(id).style.display = "none";
}
function producePrompt(message, promptLocation, color){
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
that's is my code, the php code with HTML, And javascript with Ajax but when I click into submit button nothing happens, Any solution ?
function validateCommentForm(){
if(!validateName() || !validateMail() || !validatePhone() || !validateComment()){
jsShow("commentFormPrompt");
producePrompt("Invalide Form ","commentFormPrompt","red");
setTimeout(function(){jsHide("commentFormPrompt")}, 2000);
}
else
submitForm();
}
function submitForm(){
var server = 'url'; // Your PHP file
var commentName = $('#commentName').val(); // The values of your form
var commentMail = $('#commentMail').val(); // The values of your form
var commentPhone = $('#commentPhone').val(); // The values of your form
var comment = $('#comment').val(); // The values of your form
$.ajax({ // Here the magic starts
url: server+"/api.php", // Where this function will send the values
type:"get", // To get the status of your php file
data: "action=insertNews&commentName="+commentName+"&commentMail="+commentMail+"&commentPhone="+commentPhone+"&comment="+comment, // The values
success: function (data){ // After sending the values to your php file you will receive number 1 or 2, if you receives number 1 it means sucess, but if you receives number 2 it means fail.
if(data == 'Messange Send'){
// sucess code
}
else{
// fail code
}
}
});
}
Edit: You need to echo in your php echo a number 1 if sucess or a number 2 if fail.
PHP
$message = $_GET['comment'];
$email = $_GET['commentMail'];
$name = $_GET['commentName'];
$to = "$email";
$subject = 'New Message';
$message = " Le nom : ".$name."<br><br>".$message."<br><br> Email : ".$email;
$header = "$email";
if(mail($to, $subject, $message, $header)){
echo '<b style="color: green">Messange Send</b>';
}
else{
echo '<b style="color: red">Sommthing wrong</b>';
}
So AJAX is about creating more versatile and interactive web applications by enabling web pages to make asynchronous calls to the server transparently while the user is working. AJAX is a tool that web developers can use to create smarter web applications that behave better than traditional web applications when interacting with humans.
The technologies AJAX is made of are already implemented in all modern web browsers, such as Mozilla Firefox, Internet Explorer, or Opera, so the client doesn't need to install any extra modules to run an AJAX website. AJAX is made of the following:
JavaScript is the essential ingredient of AJAX, allowing you to
build the client-side functionality. In your JavaScript functions
you'll make heavy use of the Document Object Model (DOM) to
manipulate parts of the HTML page.
The XMLHttpRequest object enables JavaScript to access the server
asynchronously, so that the user can continue working, while
functionality is performed in the background. Accessing the server
simply means making a simple HTTP request for a file or script
located on the server. HTTP requests are easy to make and don't cause
any firewall-related problems.
A server-side technology is required to handle the requests that come
from the JavaScript client. In this book we'll use PHP to perform the
server-side part of the job.
For the client-server communication the parts need a way to pass data and understand that data. Passing the data is the simple part. The client script accessing the server (using the XMLHttpRequest object) can send name-value pairs using GET or POST. It's very simple to read these values with any server script.
The server script simply sends back the response via HTTP, but unlike a usual website, the response will be in a format that can be simply parsed by the JavaScript code on the client.
The suggested format is XML, which has the advantage of being widely supported, and there are many libraries that make it easy to manipulate XML documents. But you can choose another format if you want (you can even send plain text), a popular alternative to XML being JavaScript Object Notation (JSON).
Simple example with old school style:
The HTML
<html>
<head>
<title>AJAX with PHP: Quickstart</title>
</head>
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage"></div>
</body>
</html>
The Magician
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject() {
// will store the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else {
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
// make asynchronous HTTP request using the XMLHttpRequest object
function process() {
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
// retrieve the name typed by the user on the form
name = encodeURIComponent(document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "**yourPHPfiletoretrievedata**.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}
// executed automatically when a message is received from the server
function handleServerResponse() {
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4) {
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200) {
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
helloMessage = xmlDocumentElement.firstChild.data;
// update the client display using the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage + '</i>';
// restart sequence
setTimeout('process()', 1000);
}
// a HTTP status different than 200 signals an error
else {
alert("There was a problem accessing the server: " + xmlHttp.statusText);
}
}
}
I have an HTML page that takes a login from user and authenticates and redirects to the different page. Now i converted this web-page to an app using phonegap app build function. Now i am trying to call the php thats on my server. What is the proper way to do so? Below is the code.
HTML
<script>
function PostData() {
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var userid = document.getElementById("userid").value;
var pid = document.getElementById("pid").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'www.xyz.com/abc/login.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("userid=" + userid + "&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
</script>
</head>
<body>
<form>
<label for="userid">User ID :</label><br/>
<input type="text" name ="userid" id="userid" /><br/>
<label for="pid">Password :</label><br/>
<input type="password" name="password" id="pid" /><br><br/>
<div id="div1">
<input type="button" value ="Login" onClick="PostData()" />
</div>
</form>
Try this jQuery.
function PostData() {
$.ajax({
url: "/ajax/login_check.php",
type: "POST",
data: {userid : $("#userid").val(),pid : $("#pid").val()},
cache: false,
success: function (result) {
if(result.statu){
//Valide Div Screen Show
}
else{
//invalide Div Screen Show
}
}
});
}
check Valide Login use Check file
login_check.php
ur Mysql And Php COde Put in this file.
if { //if valide Use than
$responce['statu'] = "1";
$responce['msg'] = "Login success.";
}
else{
$responce['statu'] = "0";
$responce['msg'] = "Invalide Use name & Pass";
}
echo json_encode ($responce);
Exit;