I'm struggling to get this to work as part of a larger exercise.
It's pretty simple - a user fills in a form which is sent using an XMLHttpRequest to a processing page. This should return a response below the form.
I had it almost working, but one field wouldn't show... and now nothing. Could this be a cache problem or is a problem with the code.
Here's the form:
<div id="miniContact">
<label for="yourName">Your Name</label>
<input type="text" name="yourName" id="yourName"><br>
<label for="phone">Your Phone</label>
<input type="text" name="phone" id="phone"><br>
<input type="text" name="reqd" id="reqd"><br>
<label for="email">Your Email</label>
<input type="email" name="email" id="email"><br>
<label for="type">Your vehicle type</label>
<input type="text" name="type" id="type">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
Javascript:
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var yourName = document.getElementById("yourName").value;
var phone = document.getElementById("phone").value;
var reg = document.getElementById("reg").value;
var srv = document.getElementById("reqd").value;
var email = document.getElementById("email").value;
var type = document.getElementById("type").value;
var vars = "yourName="+yourName+"&phone="+phone+"®="+reg+"srv="+service+"email="+email+"&type="+type;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
...and the php file (my_parse_file.php):
<?php
echo 'Thank you '. $_POST['yourName'] . ' ' . $_POST['service'] . ', says the PHP file';
$user_name = $_POST['yourName'];
$reg = $_POST['reg'];
$email = $_POST['email'];
$srv = $_POST['srv'];
$phone_number = $_POST['phone'];
$vehicle = $_POST['type'];
?>
Related
I have a form that is to be used to input information and register an account. The information is entered on the website and when the button 'register' is pressed it is validated by an external JavaScript method and afterwards, a PHP method is called using ajax which should take the information from the text boxes and enter it into the database. I can't seem to get the PHP getting the information working.
<?php
$mysqli = new mysqli('localhost:8080', 'root', null, 'salmonhouse');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO clients (name, surname, email, address, password)
VALUES (?,?,?,?,?)";
$name = $_POST['name'];
$surname = $_POST['surname'];
$email= $_POST['email'];
$address= $_POST['Address'];
$pass= $_POST['Password'];
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sssss", $name, $surname, $email, $address, $pass);
$stmt->execute();
?>
HTML textboxes
<form class="quote">
<div class = inliner>
<label>Name</label>
<input id="name" type="text" placeholder="Name">
</div>
<div class = inliner>
<label>Surname</label>
<input id="surname" type="text" placeholder="Surname">
</div>
<div>
<label>Email</label><br>
<input id="email" type="email" placeholder="Email Address"><br>
</div>
<div>
<label>Address</label><br>
<input id="Address" type="email" placeholder="Home Address"><br>
</div>
<div class = inliner>
<label>Password</label>
<input id="Password" type="text" placeholder="Password">
</div>
<div class = inliner>
<label>Verify Password</label>
<input id="vPassword" type="text" placeholder="Password">
</div>
<br><button class="button_1" type="button" onclick="Validate()">Register</button>
</form>
Calling javascript file from html page
<script type= "text/javascript">
var name = document.getElementById("name").value;
var surname =document.getElementById("surname").value;
var email =document.getElementById("email").value;
var pass=document.getElementById("Password").value;
var passV =document.getElementById("vPassword").value;
var address=document.getElementById("Address").value;
</script>
<script type= "text/javascript" src="asset/js/my_javascript.js"></script>
Actual javascript file
/* eslint-env browser */
/*jslint devel: true */
/* eslint-disable */
function Validate(){
name = document.getElementById("name").value;
surname =document.getElementById("surname").value;
email =document.getElementById("email").value;
pass=document.getElementById("Password").value;
passV =document.getElementById("vPassword").value;
var error = "";
document.getElementById("name").style.borderColor = "white";
document.getElementById("surname").style.borderColor = "white";
document.getElementById("email").style.borderColor = "white";
document.getElementById("Password").style.borderColor = "white";
document.getElementById("vPassword").style.borderColor = "white";
var count= 0;
if(name.length == 0){
document.getElementById("name").style.borderColor = "red";
count =1;
error = error + "Name cannot be empty\n"
}
if(surname.length == 0 ){
document.getElementById("surname").style.borderColor = "red";
count =1;
error = error + "Surname cannot be empty\n"
}
if(email.length == 0 ){
document.getElementById("email").style.borderColor = "red";
count =1;
error = error + "Email cannot be empty\n"
}
if(!(email.includes("#"))){
document.getElementById("email").style.borderColor = "red";
count =1;
error = error + "Email needs to contain an # symbol\n"
}
if(!(email.includes("."))){
document.getElementById("email").style.borderColor = "red";
count =1;
error = error + "Email needs to comtain a .com or similar\n"
}
if(pass!==passV){
document.getElementById("Password").style.borderColor = "red";
document.getElementById("vPassword").style.borderColor = "red";
count =1;
error = error + "Passwords do not match\n"
}
if(!(pass.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%&*()])[0-9a-zA-Z!##$%&*()]{8,}$/))){
document.getElementById("Password").style.borderColor = "red";
document.getElementById("vPassword").style.borderColor = "red";
count =1;
error = error + "Password must be atleat 8 long and contain a LowerCase, UpperCase, Number and a symbol."
}
if(false){
alert("Please correct the following errors highlighted in red\n"+error);
}
else{
alert("Name: " + name + "\nSurname: "+ surname + "\nEmail: "+ email+"\nPassword: "+pass+"\n Succesful Registration");
xmlhttp = new XMLHttpRequest();
var url = "asset/php/inserting.php";
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
/* eslint-enable */
This PHP file is a separate file with just this code. I have tested and if I manually set the variables instead of trying to retrieve them the data is successfully inserted into the database. So from my testing it is simply the retrieval not working. I also tried $_REQUEST['name']
This is the ajax/xmlhttprequest code.
xmlhttp = new XMLHttpRequest();
var url = "asset/php/inserting.php";
xmlhttp.open("POST",url,true);
xmlhttp.send();
My advice would be to use the jQuery library rather than XMLHttpRequest. You will need to include in the <head> section of your HTML a <script> tag to load the jQuery library from some CDN (Content Delivery Network). Also add id="f" to your <form> tag. Then your Ajax call can be as simple as:
$.ajax({
type: "POST",
url: 'asset/php/inserting.php',
data: $('#f').serialize(), // serializes the form's elements.
success: function(msg)
{
alert(msg); // show response from the php script.
}
});
You can attached the variable in ajax call, which you need to get in your php page using & for separating variable and = for assigning value .i,e :
//attaching values to pass
var data = "name=" + name + "&email=" + email + "&surname=" + surname + "&Address=" + Address + "&Password=" + Password;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//if success do something here
alert("save");
}
};
var url = "asset/php/inserting.php";
request.open("POST", url, true);
//send data to php page
request.send(data);
i am trying to make a subscriber form that submit the form using ajax post method not jQuery. I wrote a code but it is not working properly i think i am doing wrong in sending POST data. here is my code what i have tried so far.
<div id="form" style="max-width:477px">
<div class="imgContainer" id="myImageContainer">
<span onclick="document.getElementById('myLogin').style.display='none'" class="close" title="Close">×</span>
</div>
<div class="loginInfo" id="myLoginInfo">
<label for="Full Name">
<b>Full Name</b>
</label>
<spam class="error" style="color:red">
<i id="nameErr"></i>
</spam>
<input type="text" placeholder="Enter full name" name="name" id="name">
<label for="Email"><b>Email</b></label>
<spam class="error" style="color:red">
<i id="emailErr"> </i>
</spam>
<input type="text" placeholder="Enter your Email" name="email" id="email">
<button onclick="verify()">Subscribe</button>
</div>
</div>
</div>
<script>
function verify(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
document.getElementById("email").innerHTML = myObj.email;
document.getElementById("emailErr").innerHTML = myObj.emailErr;
document.getElementById("name").innerHTML = myObj.name;
document.getElementById("nameErr").innerHTML = myObj.nameErr;
}
};
xmlhttp.open("GET", "subs.php", true);
var data="email=" + document.getElementById("email").value + "&name="+document.getElementById("name").value;
xmlhttp.send(data);
}
</script>
and the PHP page looks like this(it works fine when using HTML <Form method="post">
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $name = $emailErr = $nameErr="";
function test($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($_POST["email"])) {
$emailErr=" *This Field is Required";
}else{
$email=test($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){$emailErr = " *Invalid email format";}
if (strlen($email)>60){$emailErr=" *Email cannot be larger than 60 character";}
}
if (empty($_POST["name"])) {
$nameErr=" *This Field is Required";
}else{
$name = test($_POST["name"]);
$name = preg_replace('/\s\s+/', ' ', $name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = " *Only letters and white space allowed";
}
if (strlen($name)>60)
{$nameErr=" *Name cannot be larger than 60 character";}
}
$json['email'] = $email;
$json['emailErr'] = $emailErr;
$json['name'] = $name;
$json['nameErr'] = $nameErr;
$myJSON = json_encode($json);
echo $myJSON;
}
when I hit the subscribe button it gives me null value rather than showing Error message.
xmlhttp.open("GET", "subs.php", true);
Should be
xmlhttp.open("POST", "subs.php", true);
If the PHP code expects a POST request.
Suggest you send ajax with Axios is more clearly and easy than Jquery and pure javascript
I'm trying to upload a file in an iFrame, so far everything seems to work fine, but I can't process the image in the PHP end as it doesn't seem to receive it...
It does seem to upload though as my progress bar does work and show progress and completes. The responseText says: No image selected?
Here is my aJax:
function submitFile() {
//The file location
var theFile = document.getElementById("image").files[0];
var xhr = new XMLHttpRequest();
//Disable submit button whilst upload is active
doc("submit").disabled = true;
//Completed
xhr.onload = function(e) {
if (this.status == 200) {
document.getElementById("imageUpload").innerHTML = xhr.responseText;
doc("submit").disabled = false; //Unlock submit button
}
};
//Progress
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var currentPercentage = Math.round(e.loaded / e.total * 100);
document.getElementById("imageUpload").innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
document.getElementById("imageUpload").style.backgroundSize = currentPercentage + "% 100%";
}
};
//Send data
xhr.open("POST", "php/uploadImage.php", true);
xhr.send(theFile);
}
This is the form where I am submitting the image from, it uploads when I select the file however and not when I click submit see the onchange function.
<form action="php/submitMessage.php" onsubmit="validation(this)" method="post" id="submitMessage" enctype="multipart/form-data">
<div class="left half">
<input class="text" type="text" name="name" placeholder="First and Second Name"
rules="[A-Za-z]*\s[A-Za-z]*" />
<input class="text" type="text" name="email" placeholder="Email Address"
rules="^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" />
<textarea name="message" placeholder="Enter your message here..." rows="5"></textarea>
</div>
<div class="right half">
<input class="text" type="text" name="reg" placeholder="Car Registration"/>
<input type="file" onchange="submitFile();" name="image" id="image" style="display:none;" />
<input type="hidden" name="image_location" id="image_location"/>
<label for="image" id="imageUpload" class="uploadBtn">Upload Image</label>
<p>Message will be regarded as a quote request if you provide an image.</p>
</div>
<input type="submit" id="submit" style="background-color:#fff;color:#000;" value="Submit Message/Quote" />
</form>
This is my PHP, I want to receive the file, resize it, and then set a session variable to its location which will be used when the rest of the form is submitted as the file location will need to be added to the database row.
<?php
session_start();
//Image was selected
if($_FILES['image']['tmp_name']) {
//any errors?
if(!$_FILES['image']['error']) {
//validate the file and setup future filename
$new_file = date("Ymdhisa");
//Can't be larger than 5MB
if ($_FILES['image']['size'] > 5000000) {
//Resize the file
$width = 500;
//Keep aspect ratio
$size = getimagesize($_FILES['image']['tmp_name']);
$height = round($width*$size[1]/$size[0]);
//Create object
if ($size[2] == 1) {
$images_orig = imagecreatefromgif($_FILES['image']['tmp_name']);
} else if ($size[2] == 2) {
$images_orig = imagecreatefromjpeg($_FILES['image']['tmp_name']);
} else if ($size[2] == 3) {
$images_orig = imagecreatefrompng($_FILES['image']['tmp_name']);
}
//Get image size to create object
$photoX = imagesx($images_orig);
$photoY = imagesy($images_orig);
//Create resized object
$images_fin = imagecreatetruecolor($width, $height);
imagecopyresampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY); //Resize the image
imagejpeg($images_fin,"images/".$new_images); //Save image to file
//Remove image from memory
imagedestroy($images_orig);
imagedestroy($images_fin);
//Set session key for file location
$_SESSION['tmp_image'] = "uploads/".$new_file; //Should be unset when message has been sent
$message = "File successfully uploaded!";
echo $message;
}
}
else
{
$message = "There was an error: ".$_FILES['image']['error'];
echo $message;
}
} else {
echo "No image selected?";
}
?>
This is my code and its work fine too me , Hope work for you too
function submitVisualMedia()
{
$(document).ready(function (e) {
var fd = new FormData($("#fileinfo")[0]);
$.ajax({
url:, //YOUR DESTINATION PAGE
type: "POST",
data: fd,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function ()
{
//some code if you want
}
});
});
return false;
}
<form method="post" id="fileinfo" onsubmit='return submitVisualMedia()' >
<input class="form-control" type="text" id="title" >
<input class="form-control" type="file" name="visualMedia" id="visualMedia" accept="image/*">
<button class="btn btn-success" type="submit">Upload</button>
</form>
and php side
public function uploadVisualMedia() {
ini_set('upload_max_filesize', '25M');
ini_set('post_max_size', '25M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
$fname = date('l-j-m-Y').'-'.rand(1,1000000);
$size = $_FILES['visualMedia']['size'];
$ftype = $_FILES['visualMedia']['type'];
$temp = $_FILES['visualMedia']['tmp_name'];
$type = array();
$type = explode("/", $ftype);
$filename = "galleries/" . $type[0] . "_gallery/" . $fname . "." . $type[1];
$index = 0;
while (file_exists($filename)) {
$filename = "galleries/" . $type[0] . "_gallery/" . $fname . "($index)" . "." . $type[1];
$index++;
}
move_uploaded_file($temp, $filename);
}
You most change little in this code and it should work for you fine . with this you can upload video an audio too.
change $filename to some folder name you want..
Hi please I'm new to javascript and ajax and i read that to convert javascript ( client-side)variable to php(server side) variable we have to pass by AJAX.
Please can someone give the the same code using AJAX. Here I'm using bad method but i just post this code to show what is my goal which is : when the user select an id from select tag HTML i want that others information appears in inputs tags (type text) so that he can modify the information
here is my source code:
<script type="text/javascript">
document.getElementById('id').onchange = function(){
var identifiant = document.getElementById('id').value;
<?php
$phpvar='"+identifiant+"';
$sql="select * from inscrits where id=".$phpvar;
$res=mysql_query($sql) or die ('Unable to run query:'.mysql_error());
$ligne=mysql_fetch_array($res);
?>
//document.getElementById('nom').value ="<?php echo $phpvar;?>";
document.getElementById('nom').value = "<?php echo $ligne['nom'] ?>";
document.getElementById('prenom').value = "<?php echo $ligne['prenom'] ?>";
document.getElementById('profession').value = "<?php echo $ligne['profession'] ?>";
document.getElementById('etablissement').value = "<?php echo $ligne['etablissement'] ?>";
document.getElementById('telephone').value = "<?php echo $ligne['telephone'] ?>";
document.getElementById('email').value = "<?php echo $ligne['email'] ?>";
document.getElementById('acceptation').value = "<?php echo $ligne['acceptation'] ?>";
}
</script>
Please appreciate my situation i'm new to javascript programming i just get started
if it is possible to post me the code that i can use in same page.php thank you
There are many ways of doing this, but here is a simple code that can help. I got the code from an old book called Ajax in a Nutshell but modified it for you example,
create a php file lookupCustomer.php and add your php code in it with an additional change to i,
<?php
$phpvar = 'id';
$sql="select * from inscrits where id=".$phpvar;
$res=mysql_query($sql) or die ('Unable to run query:'.mysql_error());
$ligne=mysql_fetch_array($res);
print_r(json_encode($ligne));
?>
Here is how you call the php script and update your form, again this is just a simplified way of doing this logic,
<html>
<head>
<title>EXAMPLE</title>
<script language="javascript" type="text/javascript">
var xmlObj = (typeof window.ActiveXObject != 'undefined')
? new ActiveXObject("Microsoft.XMLHTTP")
: new XMLHttpRequest();
if (xmlObj == null)
alert("Error creating request object!");
function getCustomerInfo()
{
var id = document.getElementById("id").value;
var url = "lookupCustomer.php?id="+ escape(id);
xmlObj.open("GET", url, true);
xmlObj.onreadystatechange = updatePage;
xmlObj.send(null);
//* using POST instead of GET, use this code
//var url = "lookupCustomer.php";
//var req = "id="+ escape(id);
//req = req + "?dummy=" + new Date().getTime();
//document.getElementById("order").value = url;
//xmlObj.open("POST", url, true);
//xmlObj.onreadystatechange = updatePage;
//xmlObj.send(null);
}
function updatePage()
{
alert(xmlObj.readyState+" "+xmlObj.status);
if (xmlObj.readyState == 4)
{
if (xmlObj.status == 200)
{
/* Get the response from the server */
var customerAddress = xmlObj.responseText;
/* Update the HTML web form */
var linqne = JSON.parse(this.responseText);
document.getElementById('nom').value = linqne.nom;
document.getElementById('prenom').value = linqne.prenom;
document.getElementById('profession').value = linqne.profession;
document.getElementById('etablissement').value = linqne.etablissement;
document.getElementById('telephone').value = linqne.telephone;
document.getElementById('email').value = linqne.email;
document.getElementById('acceptation').value = linqne.acceptation;
}
else
{
var customerAddress = xmlObj.responseText;
alert("Server return status error = "+xmlObj.status);
}
}
}
</script>
</head>
<body onLoad="document.forms[0].reset();">
<p><img src="breakneck-logo.gif" alt="Break Neck Pizza" /></p>
<form method="POST" action="lookupCustomer.php">
<p>Enter your id number:
<input type="text" size="14" name="id" id="id" onBlur="getCustomerInfo()" />
<input type="text" size="20" name="nom" id="nom" />
<input type="text" size="20" name="prenom" id="prenom" />
<input type="text" size="20" name="profession" id="profession" />
<input type="text" size="20" name="etablissement" id="etablissement" />
<input type="text" size="20" name="telephone" id="telephone" />
<input type="text" size="20" name="email" id="email" />
<input type="text" size="20" name="acceptation" id="acceptation" />
</p>
</form>
</body>
</html>
Im building simple login system using Ajax XMLhttpRequest. PHP File and Javascript all working fine.. but when i use response test in IF Else Condition its not working as i expect.
Here My HTML
<div class="login-form">
<input type="username" name="username" id="username" class="text-input--underbar" placeholder="Username" value="">
<input type="password" name="password" id="password" class="text-input--underbar" placeholder="Password" value="">
<br><br>
<ons-button modifier="large" onClick="javascript:ajax_post();" class="login-button">Log In</ons-button>
<br><br>
<ons-button modifier="quiet" class="forgot-password">Forgot password?</ons-button>
</div>
<div id="status"></div>
Here my Javascript Code.
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "http://boost.meximas.com/mobile/login.php";
var fn = document.getElementById("username").value;
var ln = document.getElementById("password").value;
var vars = "username="+fn+"&password="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
if(return_data=="true"){
alert("Yes Login True");
}else{
alert("No Login False");
}
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
Here my PHP Code
if(isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
}
$sql = "SELECT * FROM member WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($con,$sql);
if(!$result){
echo "failed";
}else{
echo "true";
}
For the Wrong input also im getting Yes Login True and status inner HTML True that mean PHP file always returning True. but when i check php file alone it works fine.. there is no errors.
i meant using this.
while($row = mysqli_fetch_array($result)) {
echo "Hello" .$row['email']. "Thanks";
}
it gives correct output.
Im sorry if its unclear.. please let me know.
The function mysqli_query() will only return FALSE if your query produces an error in the database. Otherwise, it will always return TRUE. Giving that, you should check your results in another way, like using mysqli_num_rows().
Besides, it is very advisable that you sanitize user's inputs before running queries with them. Always remember Booby Tables(and how to prevent it in PHP).