Running a JS script in a PHP file not working - javascript

I am attempting to send a webhook to my discord server when data is inserted into the table, however the function is not being called... Currently it just echos "sendlog()" as shown here: http://prntscr.com/cxqgk5
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
$token = $_POST["token"];
$type = $_POST["type"];
$pid = $_POST["pid"];
$sid = $_POST["sid"];
$gid = $_POST["gid"];
$name = $_POST["name"];
$players = $_POST["players"];
$max = $_POST["max"];
$cdesc = $_POST["cdesc"];
$sus = $_POST["sus"];
if($token == 'DS_443'){
$con = mysqli_connect("localhost","**","**","**");
if(mysqli_connect_errno()){
echo(mysqli_connect_error());
}
if($type == 'edit' and $players !=NULL and $sid !=NULL){
$con->query("UPDATE OnlineServers SET ServerCurrent='$players' WHERE ServerID='$sid'");
} elseif($type == 'remove' and $sid !=NULL){
$con->query("DELETE FROM OnlineServers WHERE ServerID='$sid'");
} elseif($type == 'add' and $sid !=NULL and $gid !=NULL and $name!=NULL and $players !=NULL){
$con->query("INSERT INTO OnlineServers (GameId,GameName,GameMax,ServerCurrent,ServerID,Command) VALUES ('$gid','$name','$max','$players','$sid','TEST')");
?>
sendLog();
<?php
} elseif($type == 'call'){
$con->query("INSERT INTO Calls (Caller,CallerID,CallID,CallDesc,Suspect,SuspectID,ServerID,GameID) VALUES ('$pid','$name','$cdesc','$sus')");
}
} else {
?>
sendLog();
<?php
}
?>
<script>
function sendLog(){
var hookurl = "webhookurl"
let tosend = {
'Server added;',
'Game Name: ',
'Game ID: ',
'Server ID: ',
},
var msgJson = {
"attachments": [
{
"color": "#CC09EF",
"text": tosend,
"footer": "Infius Game Logs",
"footer_icon": "http://deersystems.net/assets/images/nfius.png",
}
]
}
post(hookurl, msgJson);
}
</script>
<script>
function post(url, jsonmsg){
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
var data = JSON.stringify(jsonmsg);
xhr.send(data);
xhr.onreadystatechange = function() {
if(this.status != 200){
alert("ttt");
}
}
}
</script>
</body>

java script function should be wrapped inside script tags
<script type="text/javascript">
sendLog();
</script>
OR
<?php
echo '<script type="text/javascript">',
'sendLog();',
'</script>'
;
?>

You have output sendLog(); whithout script tag so, it will be consider normal text. If you want to call that function then you need it between script tag.
Also, you should have clean formatting of code. And avoid multiple script tag on same pages. add all js code in single script tag.

Related

Firefox blocking ajax post request

I am using ajax to resend the verification email to my user who registered on-site. The code is working fine on my chrome browser but not on firefox. In the Firefox networking tab, I can see it blocked my post request. How can I solve this issue, I am not getting any kind of errors, it's just not working.
Firefox networking tab screenshot.
And this is how I am using ajax, I can't use jQuery that's why I am using vanilla js method.
<!DOCTYPE html>
<head>
<title>Verification</title>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("email_send").addEventListener("click", function() {
function postAjax(url, data, success) {
var params = typeof data == 'string' ? data : Object.keys(data).map(
function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }
).join('&');
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', url);
xhr.onreadystatechange = function() {
if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); }
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
return xhr;
}
postAjax('send_verification.php', { }, function(data){
if (data === "verified"){
window.location ="login.php";
} else if (data === "sent"){
document.getElementById('mydiv').innerHTML = '<span class="prego">Sent Again...</span>';
}else if (data === "error"){
document.getElementById('mydiv').innerHTML = '<span class="prego">Unable Sent Again...</span>';
}
document.getElementById('mydiv').innerHTML = '<span class="prego">Just checking</span>';
console.log(data+" getting something");
});
});
</script>
</head>
<body>
<div class="text-center">
<img src="images/sucess.gif" alt="sucess">
<h4>A verification link have been sent to your email, Please flow instructions to activate your account.</h4>
<br>
<h4 class="text-center">Didn't get one? <a id="email_send" action="send_mail" href=""> click to resend.</a> </h4>
<div id="mydiv">
</div>
</div>
</body>
</html>
Also, I tried fetch() method for this, but fetch is also getting blocked for some reason.
This is the request I am making using ajax.
<?php
session_start();
include 'connection.php';
if(isset($_SESSION['email'])){
$email = $_SESSION['email'];
$email_check = $con->prepare("SELECT * FROM `user_reg` WHERE email =?");
$email_check->bind_param("s",$email_i);
$email_i = $email;
$email_check->execute();
$result = mysqli_stmt_get_result($email_check);
$email_count = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
$token = bin2hex(random_bytes(25));
if ($email_count>0){
if($row['status']==="inactive"){
$insert_query = $con->prepare("UPDATE `user_reg` SET `token`=? WHERE `email`=?");
$insert_query->bind_param("ss", $token_i, $email_i);
$token_i = $token;
$email_i = $email;
$query = $insert_query->execute();
if ($query){
$username = $row['username'];
$url = "";
$subject = "Email verification";
include 'templates/email_con.php';
include 'templates/email_verifiy_tempate.php';
if (mail($email, $subject, $body, $headers)){
$_SESSION['msg']="Check your email for activation of your account";
echo "Email Sent...";
header('location:login.php');
}else{
echo "Email not sent, please check your email";
}
$insert_query->close();
}else{
echo "error";
}
}else{
$_SESSION['msg']="You are alredy verified, login to continue";
echo "verified";
}
}else{
echo "Email dosen't exists, please sign up";
}
}else {
header('location:login.php');
}

How to read a json file which contains an array from javascript

Please guys help me because i can't find out what i can do in order to read my javascript a json file which contains an array with one element.
My php file is working fine and the output is a .json file which contains this line: {"posts":[["30"]]}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
$sql= "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$response = array();
$posts = array();
$result=mysqli_query($link, $sql);
while($row=mysqli_fetch_assoc($result)) {
$site_id=$row['site_id'];
$posts[] = array($site_id);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
// Close connection
mysqli_close($link);
?>
Can anybody help me what i have to do (without using ajax) in order my javascript function reads that value? I want to rerad this value cause i want to manipulate this number.
function load3() {
var flag1 = true;
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}
while(flag1!=false);
$("#user_id").val(selection)
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}
while(flag2!=false);
$("#book_id").val(selection2)
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}
while(flag3!=false);
$("#game_id").val(selection3)
//i do not want to do with ajax!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/PHP/loo.php',
data: $('#LoadGame').serialize(),
success: function (html) {
//do something on success?
$('#outPut').html(html);
var bingoValue=4;
if( $('#outPut').text().indexOf(''+bingoValue) > 0){
//alert('bingo!');
window.location.href='https://support.wwf.org.uk/';
//document.location.replace('https://developer.mozilla.org/en-US/docs/Web/API/Location.reload');
}
else {
alert('No!');
}
}
});
}
Thank you for your help!
Assuming this PHP code runs during your doc request,
You can read that json if you put it in a script tag
<script type="text/javascript">
window.myJson = <?php echo(json_encode($response)); ?>
</script
and it will be accessible as window.myJson in frontend

update php page using ajax using post requests reload the page?

I am trying to change the content of my php web page using ajax as below
the index.php page has input filed that call a function to executed on the button click but my problem is that the page is reload it
so i want to know what I am doing wrong??
Note that i am using the post requests to keep my data secure as w3schools.com recommended
inexd.php file code below
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Site Title</title>
</head>
<body align="left">
<div>
<h4 align="left">Balance Enquiry</h4>
</div>
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNumInput">
<button type="button" onclick="SendForm()">Search</button>
</div>
</form>
<script>
function SendForm()
{
alert("Hello! SendForm start");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
alert("Hello! going to send ajax");
var x = xmlhttp.open("POST","AccData.php", true);
xmlhttp.send(document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
alert(document.getElementById("AccNum").value);
alert("Hello! SendForm end");
}
</script>
</body>
</html>
The data.php file code below
<?php
alert("Hello! php start processing");
$AccountNumber = $_POST['AccNum'];
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
alert("Hello! connected to oracle");
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:AccNum';
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':AccNum', $AccountNumber); // binds the parameter
oci_execute($stid); // executes the query
echo $AccountNumber;
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>
With the <input type="submit" value="Search"> your sending the form the "old" way to the server not with Ajax!
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNuminput">
<button type="button" onclick="sendForm()">Search</button>
</div>
</form>
<script>
function sendForm(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//Execudted when finished and everything its Okay
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST", "acc_data.php", true);
xmlhttp.send("accNum="+document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
}
</script>
Then in your data.php you do not need any html you just need to process the the data that you received by the ajax post request(Session is also not needed for that) . In the xmlhttp.responseText you are receiving your answer from the server when the request is finished.
<?php
$accountNumber = $_POST['accNum'];// set a good variable name
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8'); //setup connection
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR); // throws an error on connection error
}
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:ACCNUM'; // sql stirng
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':ACCNUM', $accountNumber); // binds the parameter
oci_execute($stid); // executes the query
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>

Live Search Using Ajax and PHP mysql

I created a Live Search using AJAX,PHP and mysql.here when I click on search result ,redirecting me to a particular page it works perfectly. Now I need a small change.
All I need is:
When I click on the search result, that particular result should be display in the input field.
Here is my AJAX code:
<script type="text/javascript">
END OF AJAX CODE
PHP CODE
<?php
ob_start();
session_start();
include("Base.php");
$dbase=new Base();
#$userID=$_SESSION['userID'];
$createdDate=date("Y-m-d");
$createdTime=date("h:i:s A");
$partialStates=mysql_escape_string($_REQUEST['q']);
$qryy="SELECT * from `gon_pro` WHERE `pro_name` LIKE
'%$partialStates%' ";
$pser=$dbase->execute($qryy);
$ser_nums=mysqli_num_rows($pser);
while($co[]=mysqli_fetch_array($pser)){
}
?>
<?php
foreach ($co as $key => $namo) {
$cv=$namo['pro_name'];
$cv_id=$namo['id'];
$cv_p=$namo['price'];
?>
<a href="pro_det.php?prolod=<?php echo $cv_id; ?>"><p class="res
col-md-6"><?php echo $cv; ?></p></a>
<?php
}
?>
END OF PHP CODE
function getStates(str) {
if (str.length == 0) {
document.getElementById("row").innerHTML = "";
document.getElementById("results").innerHTML =""
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML =
xmlhttp.responseText;
}
};
xmlhttp.open("GET", "support/getStates.php?q=" + str, true);
xmlhttp.send();
}
}
</script>

PHP Ajax error, get 404 when type first char

I see an error in my console it says: showHint() is not defined, while I defined it already, also this live search doesn't return anything when I type it. It assume should work like this.
gethint.php file:
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
//Further names removed for Post
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
index.php
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","/gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
Your error is coming from the __DIR__ which is not defined in your showHint function. Remove this or update it to the correct path in which you're storing your autocomplete dictionary and you should be good.
To echo __DIR__ as the path to your gethint.php file, do the following:
xmlhttp.open("GET","<?php echo __DIR__; ?>/gethint.php?q=" + str, true);
However, i'm going to assume that you're not wanting to do __DIR__ as your path. Ultimately it's up to you to figure out how to set the path to your gethint.php file. We do not know the directory structure of your application or how where you have files stored.

Categories