Sending data from JavaScript to PHP via XMLHttpRequest - javascript

Good day.
I'm trying to send a simple piece of data from one php file (manage.php) to another (view.php).
I cannot send the data via a form, I want to send it via a JS script. Here's my attempt:
var read = function(id) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("id=" + id);
}
In view.php, using $_POST["id"] causes an error stating that the index "id" is undefined.
What's the correct way to send the data? Thank you.

Your input is not complete. So I did the full example below that you can follow. I made a function, named readid(id), doing the same thing as you want. Then I call that function from html, when needed.
<!doctype html>
<html lang="fr">
<head>
<meta charset="iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript" charset="iso-8859-1">
function readid(id){
"use strict";
console.log("id=", id)
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/cgi-bin/view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 || this.status === 200){
console.log(this.responseText); // echo from php
}
};
xmlhttp.send("id=" + id);
}
</script>
</head>
<body>
<p>This is a test</p>
<input type="button" name="Submit" value="Submit" id="formsubmit" onClick="readid(id)">
</body>
</html>
view.php
<?php
$logFile = "view.log";
$id = $_POST['id'];
file_put_contents($logFile, $id);
echo $id;
?>

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
$.ajax({
type: 'POST',
data: id,
url: 'PATH_TO_VIEW.PHP',
success: function(data) {
//do something
},
error: function(data){
console.log('Something went wrong.');
}
});
});
</script>
</body>
</html>
Now the data in ajax can be collected numerous e.g. serialized and new FormData(form) to quickly name two.

Related

XHR based ajax unable to upload files

I've a pretty simple javascript function which tries to send formdata along with an attached file to a php script. Below is my html and javascript code:
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery AJAX Submit Form</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<form id="form" enctype="multipart/form-data">
<input type="text" name="name" id="name">
<input type="file" name="file" id="file">
<input type="button" onclick="upload()" value="Upload">
</form><span id="msg"></span>
<div id="result"></div>
<script type="text/javascript">
function upload(){
var formData = new FormData();
formData.append("file", document.getElementById("file").files[0]);
var xhttp = new XMLHttpRequest();
document.getElementById("msg").innerHTML = document.getElementById('file').files[0];
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
document.getElementById("msg").innerHTML = this.responseText;
}
};
xhttp.open("POST", "https://localhost/2.php");
xhttp.setRequestHeader("Content-type", "multipart/form-data");
xhttp.send(formData);
}
</script>
</body>
</html>
And below is my php script "2.php":
<?php
error_reporting(E_ALL);
$myfile = fopen("newfile.txt", "w");
fwrite($myfile, $_POST['name'].$_FILES['file']['name']);
fclose($myfile);
echo 'file written';
move_uploaded_file($_FILES['file']['tmp_name'],$_FILES['file']['name']);
echo "success";
?>
The above php script doesn't has any problem because it is able to retrieve the input text as $_POST['name'] and save it in the text file created. Also the script is successfully able to retrieve the file submitted and save it, only when I submit the html form normally without any javascript.
I want to submit both the input field data and selected file via XHR api only and not through fetch api.

XMLHttpRequest does not fire for POST if both required fields are entered

Hello I am trying to sent user id and password to PHP file and echo it back in json. If I have "required" in the input form tags when I enter only one value it returns the json with that value and other one as empty string. But if I enter both it does not go into the XMLHttpRequest at all.
If I remove "required" tho it does not work with only entering one value either. Thank you!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>first assignment</title>
<link rel="stylesheet" href="style.css">
<script>
function curlcheck() {
var user_id = document.getElementById("user_id").value;
var pass = document.getElementById("password").value;
var body = "ucid=" + user_id + "&password=" + pass;
xhr = new XMLHttpRequest();
xhr.open("POST", "front_curl.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.status === 200 && xhr.readyState === 4) {
var response_json = JSON.parse(xhr.responseText);
//checks for json and "success" value from it
console.log("in successfull responce");
console.log(response_json.success);
console.log(response_json);
} else {
//checks when status did not come back successful
console.log("status NOT success");
console.log(xhr.responseText);
}
};
xhr.send(body);
}
</script>
</head>
<body>
<div class="somebox"></div>
<ul>
<h3>Team 1 Online Exam System</h3>
</ul>
<form action="" method="POST">
<div name="form header" class="formhead">
<h1>Welcome</h1>
<p><span id="loginerr" class="err_alert"></span></p>
</div>
<div class="login_box">
<lable for="user_id">User ID</lable>
<input type="text" placeholder="Enter User ID" id="user_id" required>
<label for="password">Password</label>
<input type="password" placeholder="Enter Password" id="password" required>
<button id="but" type="submit" onclick="curlcheck()">Login</button>
</div>
</form>
<div class="footer">
</div>
</body>
</html>
your form is sent by default post method without js if your required conditions are met.
else your form isn't sent as you don't fill required fields, but this doesn't matter for js, so form is sent by js (your xhr)
you can:
1) onclick="curlcheck(); return false"
OR
2) onclick="curlcheck" and make curlcheck return false
OR
3) onclick="curlcheck", function curlcheck(event) { and put event.preventDefault(); inside the function
So you'll prevent default form sending and leave only your xhr working

having trouble using JavaScript or Ajax and text display the same page

I'm having mistakes do not know where error
Having trouble using JavaScript or Ajax and text display the same page
Please help me in the wrong reform
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pop up example</title>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
document.getElementById('myform').addEventListener("submit",upload);
function upload()
{
var xhr = new XMLHttpRequest();
xhr.open("POST","/upload.php",true);
{
var formdata = new formData(myform);
xhr.send(formdata);
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200)
{
//some code to check if submission succeeded
url = xhr.responseText();
if(url == 'failed')
Console.log('upload failed'); // do something for failure
else
document.getElementById('urlBox').innerHTML = url;
}
}; return false;
}
</script>
</head>
<body>
<form id="myform" method="POST" action=<?php ($_SERVER["PHP_SELF"]); ?>>
<p>chose url:
<select size="1" name="D1">
<option value="google_drive">google drive</option>
<option value="clody">clody</option>
</select>
<input type="text" name="T1" size="40">
<input type="submit" value="go" name="B1">
<input type="reset" value="reset" name="B2">
</p>
</form>
</body>
</html>
and this upload.php file
<?php
if(!empty($_POST['D1']) && !empty($_POST['T1'])){
$providers = array(
'google_drive' => 'Goole drive^https://drive.google.com/file/d/{replace}/view',
'clody' => 'Cloudy^https://www.cloudy.ec/embed.php?id={replace}'
);
if(isset($providers[$_POST['D1']])){
$url = str_replace('{replace}', $_POST['T1'], $providers[$_POST['D1']]);
echo "$url";
}
}
else{
echo "failed";
}
?>
and thank you all
Add following line in your html page
<div id='urlBox'></div>
It is normal your semicolon after xhr.open("POST","/upload.php",true) ?
You can try replace this line:
<form id="myform" method="POST" action=<?php ($_SERVER["PHP_SELF"]); ?>>
For this:
<form id="myform" method="POST" action="<?php ($_SERVER["PHP_SELF"]); ?>">
The differece is in your action. You're not using ""

send information to database without having page reload

I have a site where you type into a text box and it will send what I wrote to my database.
I have been stuck with my page having to reload which is very troubling in my case. i am not familiar with ajax but i have heard it can be used to complete this task. i have 2 files one is called demo.php this sends the information to the server and at this time has a header that redirects me back to that page which i don't want.
I want to be able to keep sending things data to the sever without the page reloading. the other page is the index.php this is were i right into the text box and send the text to my database both files are listed below.
this is the demo.php
<?php
header("Location: http://mywebsite.com");
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['firstname'];
$sql = "INSERT INTO MyGuests (firstname) VALUES ('$value')";
if ($conn->query($sql) === TRUE) {
echo "working";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
this is the forum on index.php were i enter the information and send it. i need it to stay on that page and not reload in any way.
<form action="demo.php" method="post" />
<p> <input id="textbox" type="text" name="firstname" placeholder="Enter What You Want Your Message To Be" /></p>
<input id="textbox1" type="submit" value="Submit" />
</form>
my second attempt at index.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="navigation.css href="navigation/navigation.css">
<link rel="stylesheet" href="navigation/navigation.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
</head>
<body>
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="button" name ="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " >
</form>
</body>
<script>
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
});
</script>
</html>
You can have two files/pages for your purpose:
1. Form page
2. Ajax processing page where you request values will be inserted into your database.
Add this to your head tag
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
Steps to utilize ajax:
1. Include jquery library in form page
2. Include html form
3. Save values from ajax, that means process that ajax
HTML form suppose to be like this:
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="submit" name="send" value="send" >
</form>
Ajax call:
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
return false;
});
ajax_target.php handles formData, its validation and insertion to database.
your html/index form consists
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
</head>
<body>
<form action="demo.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="submit" name="send" value="send" >
</form>
</body>
<script>
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
return false;
});
</script>
</html>
your demo.php includes
<?php
//your db insertion goes here.
echo "inserted successfully";
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="navigation.css href="navigation/navigation.css">
<link rel="stylesheet" href="navigation/navigation.css">
</head>
<body>
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="submit" name ="send" value="send" >
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<script>
$(document).ready(function(){
var options = {
beforeSend: function () {
if (!confirm('Are you sure to submit ?')) {
return false;
}
},
success: function (response) {
alert(response);
},
error: function (response) {
alert(response);
};
}
$('#ajax-form').ajaxForm(options);
});
</script>
</body>
</html>
updated your index.php

jQuery/AJAX execution of PHP not working

I am trying to use jQuery/AJAX to run a PHP file on a server. This PHP simply adds a row with some constants to a database. Here is my code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Submit Application</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("http://.../submitApp.php");
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="javascript:doSomething()">
<p>
<label for="programName"></label>
<input type="text" name="programName" id="programName" />
</p>
<p>
<label for="greQuant"></label>
<input type="text" name="greQuant" id="greQuant" />
</p>
<p>
<label for="greVerbal"></label>
<input type="text" name="greVerbal" id="greVerbal" />
</p>
<p>
<input type="submit" name="submitApp" id="submitApp" value="Submit" />
</p>
</form>
</body>
</html>
Upon pressing the submit button on the above form, nothing seems to happen. I should mention I am running this locally via DreamWeaver. I know for a fact that the code is reaching the JavaScript method and that the PHP code is functional. Anyone know what's wrong?
Use POST instead of GET to do this work.
function doSomething() {
var programName = $('#programName').val();
var greQuant = $('#greQuant').val();
var greVerbal = $('#greVerbal').val();
$.ajax({
type: "POST",
url: "submitApp.php", //URL that you call
data: { programName: programName, greQuant:greQuant, greVerbal:greVerbal } //var in post: var from js
}).done(function(msg) {
alert(msg);//change to something to indicate action
}
});
and with your php, handle like this
<?php
$programName = $_POST['programName'];
$greQuant = $_POST['greQuant'];
$greVerbal = $_POST['greVerbal'];
//do something important
?>
this is just a simple example, you need apply some security to this php code

Categories

Resources