How do I POST multiple form data to PHP - javascript

I am trying to send data from a form into a php for it then to write it into a html, without loading into onto php file page. The var_dump shows the data is ready, it somehow just doesn't want to pass over to the php...
<!DOCTYPE html>
<html lang="en">
<head>
<title>TEST</title>
<meta charset="UTF-8" content="bla bla bla">
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript" language="javascript">$(function(){$('body').on('click', 'input.sumbit', function(){gogosend();});});</script>
</head>
<body>
<form method="post">
<ul class="form">
<li class="short">
<label>First Name<span class="required"></span></label>
<input type="text" name="first" id="first"/>
</li>
<li class="short">
<label>Last Name<span class="required"></span></label>
<input type="text" name="last" id="last" />
</li>
<li class="long">
<label>Email Address<span class="required"></span></label>
<input type="text" name="email" id="email"/>
</li>
<li class="short">
<label>Company Name</label>
<input type="text" name="company" id="company"/>
</li>
<li class="short">
<label>Telephone Number</label>
<input type="text" name="phone" id="phone" />
</li>
<li class="textarea">
<label>Message<span class="required"></span></label>
<textarea name="message" id="message" rows="20" cols="30"></textarea>
</li>
<li class="button">
<input class="sumbit" name="sumbit" id="sumbit" value="Submit" type="submit" />
</li>
</form>
<script>
function gogosend()
{
var dfirs = document.getElementById("first").value;
var dlast = document.getElementById("last").value;
var demai = document.getElementById("email").value;
var dcomp = document.getElementById("company").value;
var dphon = document.getElementById("phone").value;
var dmess = document.getElementById("message").value;
alert(dfirs);
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data_first = "first=" +dfirs ;
var data_last = "last=" +dlast ;
var data_email = "email=" +demai ;
var data_company = "company=" +dcomp ;
var data_phone = "phone=" +dphon ;
var data_message = "message=" +dmess ;
alert(data_first);
xhr.open("POST", "mailer.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data_first);
xhr.send(data_last);
xhr.send(data_email);
xhr.send(data_company);
xhr.send(data_phone);
xhr.send(data_message);
}
</script>
<?php
var_dump($_POST);
echo "</br>";
?>
</body>
</html>
And here is the php file code :
<?php
$first = $_POST["first"];
$last = $_POST["last"];
$email = $_POST["email"];
$company = $_POST["company"];
$phone = $_POST["phone"];
$message = $_POST["message"];
$text = "NAME: $first $last <br>
EMAIL: $email<br>
COMPANY: $company<br>
TELEPHONE NUMBER: $phone<br>
MESSAGE: $message<br><hr><br><br><br>";
$file = fopen("contactrequests.html","a+");
fwrite($file, $text);
fclose($file);
?>
How do I rewrite the above for it to work ? For example now it gives me the var_dump for random data that I entered :
array (size=7)
'first' => string '24' (length=2)
'last' => string '225' (length=3)
'email' => string '25g2' (length=4)
'company' => string '2d5' (length=3)
'phone' => string '2d5' (length=3)
'message' => string '2d5' (length=3)
'sumbit' => string 'Submit' (length=6)
I tried How to pass multiple values from ajax to php file But that did not help.

I would suggest sending a JSON object extracted from your form to be accessed by the PHP script... In the PHP script create a PHP class instance or an indexed array from this JSON using this function http://php.net/manual/en/function.json-decode.php
To serialize form to a JSON in javascript client side you can use this http://api.jquery.com/serializearray/
And if I might give an advice, skip using xhr directly... use the jQuery ajax wrapper... it will ensure running on all major browsers the same way without hassle

You just need to format those data according to application/x-www-form-urlencoded.
function gogosend()
{
var dfirs = document.getElementById("first").value;
var dlast = document.getElementById("last").value;
var demai = document.getElementById("email").value;
var dcomp = document.getElementById("company").value;
var dphon = document.getElementById("phone").value;
var dmess = document.getElementById("message").value;
alert(dfirs);
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data_first = "first=" +dfirs ;
var data_last = "last=" +dlast ;
var data_email = "email=" +demai ;
var data_company = "company=" +dcomp ;
var data_phone = "phone=" +dphon ;
var data_message = "message=" +dmess ;
var data = ([data_first, data_last, data_email, data_company, data_phone, data_message]).join('&');
alert(data_first);
xhr.open("POST", "mailer.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.send(data);
}

As easy as add a return false; to your gogosend function
( the form submission requires a return false; at the end to stay on the page, btw the data is allready submitted to mailer.php )
VoilĂ  :)

Related

Javascript dynamicly change DOM using PHP

PHP code
<?php
...
//Extract the data that was sent to the server
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$findemail = [
"email" => $email,
"password" => $password,
];
$cursor = $collection->findOne($findemail);
if($cursor){
if($cursor['email'] == $email and $cursor['password'] == $password){
// I Know these two lines don't work but I want to show what I want to do
echo "success";
header('location: cms-view-products.html');
}
else {
echo "failed";
header('location: login.php');
}
}
?>
AND this is my HTML code
<?php include('demo2.php') ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="demo2.php" onsubmit="return false"; method="post">
Email: <input type="email" name="email" required >
name: <input type="password" name="password" required >
<button type='submit' onclick="loadContent()">Load</button>
</form>
<div id="ServerContent">
<p>Dynamically loaded content goes here</p>
</div>
<script>
function loadContent(){
var url = "demo2.php";
var email = document.getElementsByName('email').value;
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById("ServerContent").innerHTML = this.responseData;
}
else
alert("Error communicating with server");
}
var data = `JSON.stringify({
"email": "document.getElementsByName('email').value",
"name": "document.getElementsByName('name').value"
})`;
xhr.send(data);
}
</script>
</body>
</html>
I've currently tried to echo the message via JS, the specific element <p id=" feedback"></p>, nevertheless it doesn't work. With PHP the process works, nevertheless, I can't redirect users using headers. I've found $_SESSION could resolve this issue. However, my question is to use JS to open a pop-up and then redirect the user to x page?
I edited the post since comments advised me about using Ajax and so this is my first attempt. I can always achieve one of the two either redirect the user to x page or show an error massage. but I can't do both.
Also, I don't want to alert the massage, but to change HTML element dynamically.
Thanks guys for your time and comments.

XMLHttpRequest responding with undesired response

I ran into trouble that i have failed to understand at all. I have a sign up form,ajax script and php script.My goal is that,i want to submit data to the php from the sign up form using ajax. My problem is that i can send but do not get the results that i desire as the response.
This is my sign-up form
<form method="post" action="../../includes/seller.inc.php" id="form">
<label for="names">First name and last name: </label><input type="text" name="names" id="names"> <br><br>
<label for="phone">phone number: </label><input type="text" name="phone" id="phone"> <br><br>
<label for="shopName">shop name: </label><input type="text" name="shopName" id="shopName"> <br><br>
<label for="email">Email: </label><input type="text" name="email" id="email"> <br><br>
<label for="pwd">Password: </label><input type="password" name="pwd" id="pwd"> <br><br>
<label for="pwd2">Retype Password: </label><input type="password" name="pwd2" id="pwd2"> <br><br>
<label for="description">Provide a brief Description</label><textarea name="description" id="description" cols="30" rows="5"></textarea> <br><br>
<button type="submit" name="submit">submit</button><br>
</form>
And this is my PHP script(action specified by the form):
$names = mysqli_real_escape_string($conn, $_POST["names"]);
$phone = mysqli_real_escape_string($conn, $_POST["phone"]);
$shopName = mysqli_real_escape_string($conn, $_POST["shopName"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$pwd = mysqli_real_escape_string($conn, $_POST["pwd"]);
$pwd2 = mysqli_real_escape_string($conn, $_POST["pwd2"]);
$description = mysqli_real_escape_string($conn, $_POST["description"]);
//validating the user input data
if(!empty($names && $phone && $shopName && $email && $pwd && $pwd2)){
if (preg_match("/^[a-zA-Z\s]+$/",$names)) {
if (preg_match("/^[0-9+](\d)+$/",$phone)) {
if(preg_match("/^[a-zA-Z\s]+$/",$shopName)) {
if(filter_var($email,FILTER_VALIDATE_EMAIL)) {
if ($pwd !== $pwd2) {
header("Location: ../sell/auth/sell.signup.php?passwordsdoNotMatch");
} else {
$hashed_pwd = password_hash($pwd, PASSWORD_DEFAULT);
$sql = "INSERT INTO seller(name,phone,shopName,email,password,description,approval_status) VALUES ('$names','$phone','$shopName','$email','$hashed_pwd','$description','0');";
if(!mysqli_query($conn, $sql)) {
echo "sorry not added".mysqli_error($conn);
} else {
header("Location: ../index.php");
$_SESSION['actionmsg-success'] = "successfully Added .Wait for approval!! so that you may post your products.";
}
}
And this is the ajax
function loadFunc() {
const names = document.getElementById('names');
const phone = document.getElementById('phone');
const shopName = document.getElementById('shopName');
const email = document.getElementById('email');
const pwd = document.getElementById('pwd');
const pwd2 = document.getElementById('pwd2');
const description = document.getElementById('description');
var form = document.getElementById('form');
form.addEventListener('submit', function (e) {
e.preventDefault();
var params = `names=${names}&phone=${phone},shopName=${shopName},email=${email}&pwd=${pwd}&pwd2=${pwd2}&description=${description}`;
var xhr = new XMLHttpRequest();
xhr.open('post', '../../includes/seller.inc.php');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
if (this.readyState == 4) {
console.log(this.responseText);
}
}
xhr.send(params);
});
}
When running them i dont get an error but i get a response of my own html code printed to the browser.

can't parse JSON data from php when using parse() function

I have trouble converting json data from PHP into javascript JSON format. When I use the responseText() function, I can see the that data was parsed successfully from PHP. But when I convert the ajax response to JSON, for example, var json = JSON.parse(ajax.responseText), I don't see any information outputted to the screen. I don't mind jquery answers, but I would like to see at least an example in pure javascript.
header('Content-Type: application/json');
if (isset($_POST["height"])) {
$height = preg_replace('/[^0-9]/', '.', $_POST['height']);
$width = preg_replace('/[^0-9]/', '.', $_POST['width']);
$areaInches = $height * $width;
$areaCM = $areaInches * 0.00064516;
$result = array(
'area_inches' => $areaInches,
'area_cm' => $areaCM
);
echo json_encode($result);
}
function sendData() {
var height, width;
height = parseFloat(document.getElementById('input_height').value);
width = parseFloat(document.getElementById('input_width').value);
console.log(height);
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var json = JSON.parse(ajax.responseText);
document.getElementById('jsondata1').innerHTML = json.area_inches + "ft^2";
document.getElementById('jsondata2').innerHTML = json.area_cm + "cm^2";
console.log(ajax.responseText);
} else {
console.log('error');
}
};
ajax.open("POST", "calculate_area.php", true);
ajax.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
ajax.send('height=' + height +
'&width=' + width
);
}
<h1>Calculate Area of Rectangle</h1>
<div class="wrapper">
<label>Height</label>
<input id="input_height" class="clear" type="text">
</div>
<div class="wrapper">
<label>Width</label>
<input id="input_width" class="clear" type="text">
</div>
<br>
<div class="wrapper">
<button onclick="sendData();">Calc. Area</button>
<input id="jsondata1" class="mt" type="text" readonly>
<input id="jsondata2" class="mt" type="text" readonly>
<div></div>
</div>

How to retain the values displayed in the HTML after it is fetch from the PHP?

I have an HTML page that takes the user input and displays the output based on the database. I have a hyperlink to the other pages. I want when I navigate from first page to other HTML page, I add a back button and it shoud return to the first page but it should show the fetched values. Here is the code below.
1st HTML:
<script>
function PostData() {
var online = navigator.onLine;
if(online){
// 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;
// var image = document.getElementById("image").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'login3.php');
//xhr.open('POST', 'config.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("userid=" + userid + "&pid=" + pid);
//xhr.send("&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
else{
alert("You are offline");
}
}
</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>
</body>
PHP:
<?php
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM demo WHERE username = '$userid' and password = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo $row['week'].'<br/>'.'<br/>';
echo '<a href="2ndHTML.html"/>'.$row['day1'].'</a>'.'<br/>';
?>
2nd HTML:
<body>
<form enctype="multipart/form-data" id="form" action="" method="post">
<input type="file" id="imageid" name="image" onchange="readURL();" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type="button" value="upload" onclick="javascript:uploadInage();" />
BACK
</form>
</body>
I want to retain the values fetched on the 1stHTML.html
It's best to use session. Once the user has completed the first form set a session to signal that, so when they return to the first page it will read the session and automatically redirect them to the necessary page.
You'll need to put this at the top of your 1sthtml.php and 2ndhtml.php page to signal that you want to use sessions:
<?php
session_start();
On your 1sthtml.php page you'll need to set the session information:
<?php
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM demo WHERE username = '$userid' and password = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo $row['week'].'<br/>'.'<br/>';
echo '<a href="2ndHTML.html"/>'.$row['day1'].'</a>'.'<br/>';
// ---- SET SESSION HERE ---
$_SESSION['stage'] = 1;
}
?>
And then, on the 1sthtml.php again you'll need to check to see if that session variable exists, if it does then forward onto the page you want. So, at the top of your 1sthtml.php, next to your previous session_start():
<?php
session_start();
if (isset($_SESSION['stage'])) {
header('Location: 2ndhtml.php');
exit();
}

Trying to add form data to a database using an Ajax request with PHP

I cant quite get my form to add its data to a local database I have setup.
I have a addproducts.php page:
<?php
$title = "Products";
include("Header.php");
include("PHPvalidate.php");
?>
<script src="AjaxProduct.js"></script>
<article>
<section>
<fieldset><legend><span> Add a product to the database </span> </legend>
<form id ="productsform" method="post" onsubmit="return false;">
<input type="hidden" name="submitted" value="true">
<label> Enter a product name: <input type="text" id="name" name="name"/> </label>
<label> Enter a product quantity: <input type="number" id="quantity" name="quantity"/> </label>
<label> Enter a product description: <input type="text" id="description" name="description"/> </label>
<label> Enter a product price: <input type="text" id="price" name="price"/> </label>
<label> Upload a image of the product: <input name="image" accept="image/jpeg" type="file"></label>
<input id="submit" name="submit" type="button" class="reg" value="Add Product">
<div id="check"></div>
</form>
</fieldset>
</section>
</article>
I then have a ajax fetch request to gather up the data to get ready to be posted to the database:
fetch = function () {
var xhr, name, quantity, description, price, target;
xhr = new XMLHttpRequest();
target = document.getElementById("check");
name = document.getElementById("name").value;
quantity = document.getElementById("quantity").value;
description = document.getElementById("description").value;
price = document.getElementById("price").value;
var vars = "name="+name+"&quantity="+quantity+"&description="+description+"&price="+price;
changeListener = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
target.innerHTML = xhr.responseText;
} else {
target.innerHTML = "<p>Something went wrong.</p>";
}
};
xhr.open("POST", "addSQL.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = changeListener;
xhr.send(vars);
}
pageLoaded = function() {
var fetchbutton = document.getElementById("submit");
if(fetchbutton) {
fetchbutton.addEventListener("click", fetch);
}
}
window.onload = pageLoaded;
And finally an addSQL.php
That send the data to the database:
//Stores all information passed through AJAX into the query
$name = $_POST['name'];
$quantity = $_POST['quantity'];
$description = $_POST['description'];
$price = $_POST['price'];
//Adds information to database
$query = "INSERT INTO products (name, quantity, description, price) VALUES ('$name','$quantity','$description','$price')";
//Runs the query
$result = $mysqli->query($query) OR die("Failed query $query");
echo $mysqli->error."<p>";
//
?>
When i try to add dummy data into the form and submit nothing happens with no errors or anything so Im not sure where the point of failure is.
Any help would be appreciated.
I think you're missing this:
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Edit: also now that I look at it, you're vulnerable to SQL injection and an apostrophe in your data will break the query:
$name = $mysqli->real_escape_string($_POST['name']);
$quantity = $mysqli->real_escape_string($_POST['quantity']);
$description = $mysqli->real_escape_string($_POST['description']);
$price = $mysqli->real_escape_string($_POST['price']);
You add some alert() in your code to find the error.
add alert in the every line when you get a value in variable like alert(vars); after the assign value in vars variable

Categories

Resources