I write php inside JavaScript in the following way. even though the delete function is working that alert doesn't come.
Here is my code:
Delete.php
<script type="text/javascript">
function delete_id(id) {
if (confirm('Are you sure To Remove This Record ?')) {
<?php
include('database_connect.php');
if (isset($_GET['variable'])) {
$sql_query = "DELETE FROM register WHERE id=".$_GET['variable'];
mysqli_query($con, $sql_query);
header("Location: newusers.php");
}
mysqli_close($con);
?>
}
}
</script>
You can't do it like this. The correct way would be to make an ajax request to backend, and then have php delete the row.
Edit
here is some sample code for you
<script>
function delete_id() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert("deleted");
}
};
xhttp.open("GET", "/delete.php", true);
xhttp.send();
}
</script>
and the delete.php goes like
<?php
//write code for delete here
?>
Another point is that header("Location...") would redirect but in ajax, hence it is better to not use php redirect, but check in javascript and then use document.location for the redirect.
Related
So I have a code, where a number is retrieved from a text file and is displayed through HTML.
The thing is that it only retrieves the number when I refresh the page. If I change the number on other page, it doesn't change on the other page.
I've seen similar questions before, most of them said to use AJAX, but I don't understand much about AJAX and I only need it for this bit of code, it's not like I'm going to constantly use it. I would like to know if there is any other besides AJAX and if there is only AJAX, please present examples of code.
PHP code:
<?php
$file = "num.txt"; //Path to your *.txt file
$contents = file($file);
$num = implode($contents);
?>
JavaScript code. Basically it gets the PHP value and outputs to the html.
document.getElementById("num").innerHTML = '<?php echo $num; ?>';
Keep in mind, I don't want to refresh the page. Just the variable.
EDIT: PHP code - Getting an error - Notice: Undefined index: keynum in C:\xampp\htdocs\num.php on line 3
Here is the code of the PHP
<?php
$keynum = $_POST['keynum'];
$post = "INSERT INTO post (keynum) VALUES ($keynum)";
$fileLocation = getenv("DOCUMENT_ROOT") . "/num.txt";
$file = fopen($fileLocation,"w");
$content = $keynum;
fwrite($file,$content);
fclose($file);
echo 'Response';
die();
?>
You can achieve what you want using XMLHttpRequest, like this:
function updateData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('num').innerHTML = this.responseText;
}
};
xhttp.open('GET', '/num.php', true);
xhttp.send();
}
setInterval(updateData, 2000);
If you want to refresh the variable without refreshing the page, then you need to use an asynchronous request. It doesn't need to be AJAX, you can use the native XMLHttpRequest() function.
If you want more info: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
or with jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
setInterval(function(){
$.ajax({url:"num.php", success:function(result){
$("#num").html(result);
}});
}, 3000);
</script>
<textarea id="num"></textarea>
get_nbr.php
<?php
$file = "num.txt"; //Path to your *.txt file
$contents = file($file);
$num = implode($contents);
echo $num;
?>
index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!---trigger get_nbr() on page load on an infinite loop every two seconds -->
<body onload="setInterval(get_nbr, 2000)">
<script>
function get_nbr() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("num").innerHTML = this.responseText;
}
};
xhttp.open("GET", "get_nbr.php", true);
xhttp.send();
}
</script>
<p id="num"></p>
like this.
let url = ""; //whatever url your requesting.
setInterval(function(){
var x = new XMLHttpRequest();
x.open("GET" , url , true);
x.onreadystatechange = function(){
if(x.readyState == 4 && x.status == 200)
{
document.getElementById("num").innerHTML = x.responseText;
}
}
x.send();
} , 2000);
-- UPDATE , added post --
setInterval(function(){
var x = new XMLHttpRequest();
x.open("POST" , url , true);
x.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
x.onreadystatechange = function(){
if(x.readyState == 4 && x.status == 200)
{
document.getElementById("num").innerHTML = x.responseText;
}
}
x.send("postVar1=123");
} , 2000);
So basically I want to have a Javascript function that posts data to a table in my database. i know that I need to call a php page to do this. But the code I have written doesn't work. The js fucntion is triggered by a button press in html. I need to do this in js ajax and not jquery ajax
The Javascript
function comment_sub(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
}
};
xhttp.open("POST", "static/setcomments.php", true);
xhttp.send(encodeURIComponent(document.getElementById('comment-textbox').value));
}
The PHP
<?php
echo "Hello";
$mydb = mysqli_connect("localhost", "root","", "website");
if (!$mydb){
die("Connection failed".mysqli_connect_error());
}
$sql = "INSERT INTO 'comments'('comment_text') VALUES ('{$_GET['comment-textbox']}')";
$query = mysqli_query($mydb, $sql);
if (!$query)
{
die('Error: ' . mysql_error());
}
echo "1 record added"
?>
Checked the network and console log. The JS function is being called fine but the network logs gives me a 404 error for the post request
You are only sending the value itself, not the name comment-textbox.
Try this:
xhttp.send(JSON.stringify({
'comment-textbox': document.getElementById('comment-textbox').value
}));
On the PHP page, you are doing a HTTP POST and not a HTTP GET. So rewrite it as this:
$sql = "INSERT INTO 'comments'('comment_text') VALUES ('{$_POST['comment-textbox']}')";
So I have a main page which have buttons, each buttons contain names, when I click that button I want to pop up div which shows information of that person, I used ajax to retrieve info from php,
var strURL="searchSender.php?ID="+ID;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
outMsg=req.responseText;
var prevWin = document.getElementById("senderInfo");
prevWin.innerHTML = outMsg;
prevWin.style.top = 50+"px";
prevWin.style.right = 80+"px";
prevWin.style.visibility = "visible";
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
searchSender.php basically redeem info of that specific person from the database, that returns these codes (i didn't include here the code that retrieves data from database)
<label>Name: <?php echo $row['Name'];?> </label></br>
<label>Address: <?php echo $row['Address'];?></label></br>
<label>Contact: <?php echo $row['ContactNumber'];?></label></br>
<div id="divSenderMap">
<?php
$url = "mapSender.html";
$_SESSION['SenderID'] = $row['ID'];
include $url ?>
</div>
<input type="button" id="btnSendReply" value="SEND"/>
<input type="button" id="btnCloseDiv" value="X" onclick="closeDiv()"/>
mapSender.html is supposed to return a map where the person is, the code is working on any other file/page, but it does not do it here. It is returning php and html codes but not javascript codes. What could be wrong?
As #MichaelLonghurst told it seems your file is named mapSender.html. So the server does not call PHP before return the HTML.
You should rename mapSender.html into mapSender.php.
I create a session in my php script.
I want to destroy my php session in javascript.
when I click on Destroy Session then javascript function destroy() call and destroy SESSION['user'].
<?php
ob_start();
session_start();
SESSION['user'] = "test 123";
echo "<a onClick = 'destroy()'>Destroy Session</a>";
?>
<script>
Function destroy(){
session_destroy(); // Like `PHP` I want destroy Session in `javascript`
}
</script>
I think you should use AJAX to destroy function from Javascript. Like :
.js code :
function destroy_session(){
var xmlhttp = getXmlHttp();
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET','./destroy_session.php', true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
alert(xmlhttp.responseText);
}
}
};
xmlhttp.send(null);
}
destroy_session.php code:
<?php
session_start();
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
echo 'Session was destroyed';
?>
you cant directly destroy the session of php within javascript, since javascript is running on the client and php is running on the server.
but you can erase the session cookie from php within php - when its used!
but this detaches only the client from the session, no destroying the session.
What you can do is use AJAX to load a PHP page that executes a session_destroy(). jQuery has very easy ajax functions, documented here.
This is a follow up of another question I asked last night. My problem now is not that the script doesn't works, but that I'm getting some very strange repeat of an HTML input element when my xmlhttprequest object returns the response text. Here's the code:
<!DOCTYPE HTML>
<?php
if(!empty($_GET['uName']))
{
$r = mysql_connect("localhost", "root", "pass") or die("Couldn't connect to db");
mysql_select_db("db", $r) or die ("Couldn't select db");
$q = mysql_query("select * from users where uName = '{$_GET['uName']}'") or die("Couldn't query table");
$data = mysql_fetch_assoc($q);
mysql_close($r);
}
?>
<html>
<head>
</head>
<body>
<form>
<input type="text" name="fUName" onchange="ShowUser(fUName.value);" value="name" style="width:125px;">
</form>
<div id="display"><?php print "ID = {$data['id']}"; ?></div>
</body>
</html>
<script type='text/javascript'>
function ShowUser(name)
{
if(name.length == 0)
{
document.getElementById("display").innerHTML = "Please enter a username to check";
return;
}
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("display").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "index.php?uName=" + name, true);
xmlhttp.send();
}
</script>
Here's the strange problem:
There should only be one input field, and is orginally, however when I enter text into it and it loses focus, the JS is triggered and also prints out another input field.
Please ignore the bad practice of PHP, JS and HTML/CSS in one script, this was supposed to be a quick test that has turned for the worse :)
I'm baffled!
Thanks for any help.
The problem lies in the fact that all of your code is in one page. Consider this: you load up index.php. After it's all displaying then you call this same page again (for your AJAX request) so you're essentially saying "Hey, I want you to try and load this page again," hence why you're ending up with duplicate fields.
Try separating out your files in to something like index.php and getuser.php or something of the sort.