I was able to link to the database to add data via AJAX "GET", but now I must send another AJAX "POST" request to delete the data from the SQL database. Given the fact that I have no prior knowledge of PHP or SQL, I am struggling mightily with this task. I have tried to send the request using many different parameters, but am finding these attempts to be futile. I have found many tutorials on this using jQuery, but unfortunately I must use plain JavaScript.
PHP:
<?php
$userName = "root";
$password = "";
$dbName = "ToDo";
$server = "localhost";
$db = new mysqli($server, $userName, $password, $dbName);
$sql = "DELETE FROM tasks WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i", $_REQUEST["id"]);
$stmt->execute();
$returnVal = $stmt->affected_rows;
$stmt->close();
$db->close();
echo $returnVal;
JavaScript: (userWaste represents text input added to database via client side js)
const del = (userWaste) => {
let xhr = new XMLHttpRequest();
let url = "ToDo/deleteTask.php";
let params = "?id=" + userWaste;
xhr.open("POST", url, true);
xhr.onreadystatechange = () => {
if(xhr.readyState == 4 && xhr.status == 200){
let deletedTask = xhr.responseText;
}
}
xhr.send(params);
PHP:
<?php
header("Access-Control-Allow-Origin: *");
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "todo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$taskId = $_POST['taskId'];
$sql = "DELETE FROM tasks WHERE id=$taskId";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
$conn->close();
return true;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
$conn->close();
return false;
}
JS:
const del = (userWaste) => {
let xhr = new XMLHttpRequest();
xhr.open("POST", "test.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
let params = "taskId=" + 1;
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
const x = xhr.responseText;
console.log(x);
}
}
xhr.send(params);
}
I believe 'userWaste' contains id of record that you want to delete.
Also change "test.php" in xhr.open to your php script url
Related
I am sending echoing some data to be received in Javascript however when i debug it, it seems that a new line has been added.
PHP
<?php
header("Content-Type: application/json; charset=UTF-8");
require './connection.php';
$obj = json_decode($_POST["x"], false);
$usernamequery = "SELECT * FROM User WHERE username='$obj->newUser'";
$result = mysqli_query($db, $usernamequery);
$row = mysqli_fetch_assoc($result);
if($row["Username"] == null){
$updatequery = "UPDATE User SET User='$obj->newUser' WHERE username ='$obj->username'";
$result = mysqli_query($db, $updatequery);
echo "valid";
} else{
echo "invalid";
}
?>
JS
///// USERNAME
$(document).ready(function () {
$("#userSubmitForm").on("click", function(e) {
$username = document.getElementById("user").value;
$newUser = document.getElementById("newUser").value;
user = $newUser;
obj = { "username":$username, "newUser":$newUser};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
validity = this.responseText;
if (validity === "valid"){
$('#usernameModal .modal-header .modal-title').html("Result");
$('#usernameModal .modal-body').html("Your Username Has Been Changed to '$newUser'");
$("#passSubmitForm").remove();
$("#userCloseForm").remove();
window.setTimeout(redirect,3000);
} else{
$('#error').html("This Username Already Exists"); ;
}
}
};
What is happening is responseText will be receive "valid"/"Invalid" as "valid[newline]"/"invalid[newline]"
As stated at http://php.net/manual/en/function.echo.php that can't be a "problem" of the echo. There must be some newline-character after your -tags
A simple solution would be to just trim your response text like this: var validity = this.responseText.trim(); in order to strip it from unwanted space/tab/newline characters.
I'm trying to create a JSON callback. I got two files, json.html and json.php. Also, I've a database with like this:
Type: MySQL
DB Name: user_table
Table name: customers
Fields: id, name, product, supplier
Codes of my json.html is:
<html>
<head>
</head>
<body>
<div id="demo" style="font-size: 20px;"></div>
<script>
obj = { "table":"customers", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
for (x in myObj) {
txt += myObj[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("POST", "json.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
</script>
</body>
</html>
And here is the codes of json.php:
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_POST["x"], false);
$conn = new mysqli($servername, $username, $password, $dbname);
$result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
Here is the error log reports:
PHP Notice: Undefined variable: table in /home/user/public_html/json/json.php on line 7
PHP Fatal error: Cannot access empty property in /home/user/public_html/json/json.php on line 7
PHP Notice: Undefined index: x in /home/user/public_html/json/json.php on line 4
PHP Notice: Undefined variable: table in /home/user/public_html/json/json.php on line 7
PHP Notice: Trying to get property of non-object in /home/user/public_html/json/json.php on line 7
PHP Notice: Undefined variable: limit in /home/user/public_html/json/json.php on line 7
PHP Notice: Trying to get property of non-object in /home/user/public_html/json/json.php on line 7
PHP Fatal error: Call to a member function fetch_all() on a non-object in /home/user/public_html/json/json.php on line 9
How can I make it work?
As mentioned in a comment to David, the problem was with fetch_all(). I guess what was making the problem is the server resources because the page returned 500 on call.
In any case I retrieved the required array using this method instead:
$conn = new mysqli($servername, $username, $password, $dbname);
$result = $conn->query("SELECT * FROM customers LIMIT 10");
$outp = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$outp[] = $result->fetch_array(MYSQLI_ASSOC);
}
echo json_encode($outp);
And it worked.
Now, I'm going to make it work with my JSON callback.
Try replacing
$result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit);
with
$result = $conn->query("SELECT name FROM ".$obj->{'table'}." LIMIT ".$obj->{'limit'});
Try like this...
In your javascript send object..
xmlhttp.send(obj);
In PHP:
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
header("Content-Type: application/json; charset=UTF-8");
extract($_POST); //Extracting
$conn = new mysqli($servername, $username, $password, $dbname);
$result = $conn->query("SELECT name FROM ".$table." LIMIT ".$limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
print_r($outp);
echo json_encode($outp);
?>
Looks like the JSON you are trying to send is not making it to the PHP script.
Some things I would do are:
Change the request header content type to application/json (see this https://stackoverflow.com/a/9880122/2315558)
Check that x has a value before trying to use it
function create(x) {
var field=document.createElement('fieldset');
var t=document.createElement('table');
t.setAttribute("id","myTable");
document.body.appendChild(t);
field.appendChild(t);
document.body.appendChild(field);
var row=document.createElement('th');
newHeader = document.createElement("th");
newHeader.innerText = x;
row.appendChild(newHeader);
var row1=document.createElement('tr');
var col1=document.createElement('td');
var col2=document.createElement('td');
var row2=document.createElement('tr');
var col3=document.createElement('td');
var col4=document.createElement('td');
var row3=document.createElement('tr');
var col5=document.createElement('td');
var col6=document.createElement('td');
col1.innerHTML="Name";
col2.innerHTML="<input type='text' name='stateactivityname' size='40' required>";
row1.appendChild(col1);
row1.appendChild(col2);
col3.innerHTML="Registration Applicable";
col4.innerHTML="<select name='regapp' required><option></option><option>Yes</option><option>No</option></select>";
row2.appendChild(col3);
row2.appendChild(col4);
col5.innerHTML="Registers Applicable";
col6.innerHTML="<select name='registers' required><option></option><option>Yes</option><option>No</option></select>";
row3.appendChild(col5);
row3.appendChild(col6);
t.appendChild(row);
t.appendChild(row1);
t.appendChild(row2);
t.appendChild(row3);
addrow('myTable');
}
PHP code for storing data to database is:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$conn=new mysqli("localhost","root","","newcomplyindia");
if($conn->connect_errno){
echo("connection error");
}
$actname=$_POST["actname"];
$industry=$_POST['industrytype'];
$centralorstate=$_POST["cors"];
$sql="insert into acts (actname,centralorstate) value ('".$actname."','".$centralorstate."')";
$regapp=$_POST["regapp"];
if($regapp=='Yes'){
$regapp=true;
}
else{
$regapp=false;
}
$registers=$_POST["registers"];
if($registers=='Yes'){
$registers=true;
}
else{
$registers=false;
}
$sub=$_POST["sub"];
if($sub=='Yes'){
$sub=true;
}
else{
$sub=false;
}
if($conn->query($sql)==true){
echo 'act name added ';
}
$lastid=$conn->insert_id;
$sql1="insert into actsstate (actid,registrationrequired,registersapplicable,sublocation)"
. "values('$lastid','$regapp','$registers','$sub')";
if($conn->query($sql1)==true){
echo '<br>name and central/state added';
}
$stateactivity=$_POST["stateactivityname"];
$activityname=$_POST["activityname"];
$activitymonth=$_POST["month"];
$activitydate=$_POST["date"];
$sql2="insert into activity (name,actid,activityname,activitymonth,activitydate)"
. "values('$stateactivity','$lastid','$activityname','$activitymonth','$activitydate')";
if($conn->query($sql2)){
echo 'activity added';
}
else{
echo 'no record';
}
$conn->close();
?>
i have a javascript like this. The table is created dynamically. And i want to store the data inside this table to database. am using mysqli for database connection
Am new to javascript. Can anyone help me to do this
Here's a way using Vanilla JS (pure js)
var xhttp = new XMLHttpRequest();
var url = "save.php";
xhttp.open("POST", url, true);
// uncomment this if you're sending JSON
// xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() { // Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
// the 4 & 200 are the responses that you will get when the call is successful
alert(xhttp.responseText);
}
}
xhttp.send('the data you want to send');
And here's a way to save to the database (mysql in my case) with Flat PHP (pure php)
$servername = "localhost";
$username = "db_username";
$password = "db_password";
$dbname = "db_name";
// connect to the DB
$conn = new mysqli($servername, $username, $password, $dbname);
// check if you're connected
if ($conn->connect_error) {
echo "Connection failed: " . $conn->connect_error;
}
else {
// echo "connecting to DB succeeded <br> ";
}
// uncomment the following if you're recieving json
// header("Content-Type: application/json");
// $array = json_decode(file_get_contents("php://input"), true);
$sql = "INSERT INTO table_name (columns,names) VALUES (columns,values)";
if ($conn->query($sql) === TRUE) {
echo "Data was saved successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
to learn more about the sql commands I suggest the w3schools tutorials
Of course you can by using AJAX:
$.post("php_script.php",{javascript variables}, function(result) {
alert(result);
});
I am using this code right here:
HTML code (jsonexamplecss.html):
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "adomaniname/phpselectdatawhere.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var s = 256;
var hr = new XMLHttpRequest();
hr.open("POST", "adomainname/phpselectdatawhere.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send("limit="+s);
var arr = JSON.parse(response);
var i;
var i = 0;
for(i = 0; i < arr.length; i++) {
out = arr[i].name
if (out = "0 results") {
alert("0 results");
}
}
document.getElementById("id01").innerHTML = out;
alert(out);
}
</script>
</body>
</html>
PHP code(phpselectdatawhere.php):
<?php
if(isset($_POST['limit'])){
$limit = preg_replace('#[^0-9]#', '', $_POST['limit']);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM testget WHERE id='$limit'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"];
}
} else {
echo "0 results";
}
$conn->close();
?>
I have a table named testget with id, name fields both VARCHAR. I wrote a script in order to do these things:
The HTML script sends data to the php script via http request and in this example it sends limit=256.
The PHP script gets the limit=256, puts away the number from the limit and stores $limit =256.
After that the PHP script searches if there is a name in the table whose id='$limit' and prints the name if it exists, else it echoes 0 results. The table testget has a row where id=256 and name=JohnDoe so it can't echo 0 results.
After all this procedure the HTML scripts gets the echoed stuff and alerts them with JavaScript.
So in this case I want to have JohnDoe alerted in my HTML page but unfortunately nothing shows up. Could you please help me?
Note that the url and the database connection info are correct but as you can understand I don't want to show them.
So following my last question I want to use the value that is submitted in the input tag to get the matching id in my database. I have created two files for it but I can't figure out how to link them. Also note I made a database with a few values(id, firstname, etc.) and when the user fills in 1 I want it to display id 1 & the firstname.
This code is from the last question & I've added xmlhttp:
Input code
Choose a number between 1 and 5
Your info shall be shown here
Click me!
var myButton = document.getElementById('btn');
myButton.onclick = function(){
alert(document.getElementById('myid').value);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var dbText = xmlhttp.responseText;
document.getElementById('dbinfo').innerHTML = dbText;
}
}
xmlhttp.open("POST", "LinkToDataFile", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
That is what the user sees and the number is displayed correctly however I now need to link it to my file data.php which I have tried but it cannot get the value.
Data Code
<?php
require_once('input_code');
//Get the data from the database and echo them here
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "db_name";
try
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("SELECT `id`, `firstname`, FROM `db_name` WHERE `id` = :myid"); //Here it needs to grab the value but it does not work.
$statement->bindParam(':id', $id);
$id = $_POST['id'];
$statement->execute();
$result = $statement->setFetchMode(PDO::FETCH_ASSOC);
$data = "";
foreach($statement->fetchAll() as $key => $value)
{
$data .= $value['id']." | ".$value['firstname'];
}
}
catch(PDOException $e)
{
echo "The following error occurred : ".$e->getMessage();
}
echo $data;
?>
So what am I doing wrong? am I missing something obvious like the $id again or is it a series of errors, the only thing it does now is giving me an alert with the number.
By adding a line and moving $id before $statement it is all fix thanks to Dante Javier
Input code
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //Under this add the following lines:
var id = document.getElementById('myid').value;
xmlhttp.send("id="+id);
Data Code
$id = $_POST['id']; //Move this above the $statement = $connection->prepare.