Why is this function always getting called - javascript

Tried to do ajax function which calls a php function to do some mysql stuff, however you can see in the log file that the php function updateInfo() is always getting called with every submit button is pressed, despite I never do updateInfo(); in the php.
ajax function (which calls updateInfo();):
function showUser(str, name) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
<?php updateInfo(); ?>
}
};
xmlhttp.open("GET","part.php?q="+str+"&d="+name,true);
xmlhttp.send();
}
php updateInfo function:
function updateInfo(){
error_reporting(0);
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'defekt';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
$q = intval($_GET['q']);
$d = $_GET['d'];
$m = preg_replace('/[0-9]+/', '', $d);
$s = intval($_GET['d']);
$sql = "UPDATE form SET " . $m . "=" . $q . " WHERE id =" . $s;
$result = $conn->query($sql);
$conn->close();
}
for some reasons I am also not able to echo anything in the updateInfo function.
what would be the best solution to do a specific part in php if you can use functions :)?

Related

what can i do to access only a specific table

I 'm working at with XAMPP server at my home pc.My files are in xampp/htdocs/marfo I am trying to fetch some records in a booking database lying on xampp\mysql\data\marfo. Althought i can read all others tables of the same database (using different files at the same directory) this specific table gives me this error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/xampp/htdocs/marfo/booking.php. (Reason: CORS request not http)."
the code in js is:
function readres() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responceText != "NoResults") {
reservarray = JSON.parse(this.responseText);
// function to set whole site for this language
} else { return "Bad thing !!! Something went wrong .........." }
} else { return "Didn't found anything malaka.........." }
}
xmlhttp.open("GET", "booking.php", true);
xmlhttp.send();
}
and the code at PHP file:
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'marfo';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed:" . $conn->connect_error);
}
$sql = "SELECT * FROM bookings";
$result = $conn->query($sql);
$counter = 0;
if ($result->num_rows > 0) {
// output reservations
while ($row = $result->fetch_assoc()) {
$reservarray = array(
"datefrom" . $counter => $row["datefrom"], "dateto" . $counter => $row["dateto"], "name" . $counter => $row["name"]
);
$counter = $counter + 1;
}
echo json_encode($reservarray);
} else {
echo 'No results';
}
$conn->close();```
any help appreciated....

AJAX call to php not returning value when using post method

PHP Code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ngram";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$uid =$_REQUEST["username"];
$sql = 'select * from user_db where username like '.'"'.$uid.'"';
$result = $conn->query($sql);
//echo $sql;
if ($result->num_rows > 0)
{
$conn->close();
echo (0);
}
else
{
$conn->query("insert into user_db values('".$_REQUEST["name"]."','".$_REQUEST["username"]."','".$_REQUEST["email"]."','".$_REQUEST["pass"]."')");
$conn->close();
echo (1);
}
?>
function connectDb(formElement)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","signup.php",true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
myFunction(xmlhttp.responseText);
}
}
xmlhttp.send(new FormData (formElement));
}
function myFunction(response)
{
if(response != 1)
{
window.open("error.html","_self");
}
else
{
window.open("login.html","_self");
}
}
Here javascript is able to send request but php is not returning any value. The values gets added to the database but the page does not changes. Only returned value gets displayed in screen.
you write return $r but not write a function for access it.write a function or either write echo $r;.

JavaScript PHP $_Get issue

so I have a JavaScript function which calls to a PHP file using an asyncronous method. This is my code
JavaScript
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback (xmlHttp.responseText);
}
xmlHttp.open("GET", "http://127.0.0.1/formulario/insertReporte.php?"+'nombreAlumno='+nombreAlumno+'&noCta='+noCta+'&semestre='+semestre, true);
xmlHttp.send(null);
And here is my PHP File
<?php
$servername = "myServerName";
$username = "myUserName";
$password = "myPassWord";
$dbname = "myDb";
$nombreAlumno = $_GET['nombreAlumno'];
$noCta = intval($_GET['noCta']);
$semestre = intval($_GET['semestre']);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO infoalumno (nombreAlumno,noCta,noSemestre)
VALUES ($nombreAlumno,$noCta,$semestre)";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
My issue comes on this line $nombreAlumno = $_GET['nombreAlumno']; as I get this error
On my database my nombreAlumno field is declared as a varchar.
I know my connection works because if I change that line into $nombreAlumno = intval($_GET['nombreAlumno']); it inserts 0 into my database.
Any ideas what am I doing wrong?
You need to add quotes around your values. Also use mysqli_real_escape_string before insert into database to prevent sql injection
$nombreAlumno=mysqli_real_escape_string($conn, $nombreAlumno);
$noCta=mysqli_real_escape_string($conn, $noCta);
$semestre=mysqli_real_escape_string($conn, $semestre);
$sql = "INSERT INTO infoalumno (nombreAlumno,noCta,noSemestre)
VALUES ('".$nombreAlumno."','".$noCta."','".$semestre."')";
Try this
<?php
$servername = "myServerName";
$username = "myUserName";
$password = "myPassWord";
$dbname = "myDb";
$nombreAlumno = $_GET['nombreAlumno'];
$noCta = intval($_GET['noCta']);
$semestre = intval($_GET['semestre']);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO infoalumno (nombreAlumno,noCta,noSemestre)
VALUES ('".$nombreAlumno."','".$noCta."','".$semestre."')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Can't get ajax working with PHP to load a table of info from MySQL

So basically I have a drop down list that displays data from a MySQL table(accounts) that would display user accounts. When the user selects one of the accounts I want it to display all facilities(facility table) that are owned by that account.
I have the drop down displaying the accounts, but it will not run the onChange() function to load my table. Here is everything I have, can someone tell me why my function is not getting triggered at all?
Index.php
<?php
require_once('sessionstart');
require_once('header.php');
require_once('dbconn.php');
//Accounts
require_once('getaccounts.php');
//Facility
echo "<div id='facilities'>";
require_once('getfacility.php');
echo "</div>";
?>
<?php
require_once 'footer.php';
?>
getaccounts.php
<?php
//require files
require_once('sessionstart.php');
require_once('dbconn.php');
//clear options variable
$options = "";
//connect to db and test connection.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT account_id, account_name FROM accounts";
$data = mysqli_query($dbc, $sql);
//loop through data and display all accounts
while ($row = mysqli_fetch_array($data)) {
$options .="<option>" . $row['account_name'] . "</option>";
}
//account drop down form
$accountDropDown="<form id='account' name='account' method='post' action='getaccounts.php'>
<label>Accounts: </label>
<select name='account' id='account' onchange='showFacilities(this.value)'>
<option selected='selected' disabled='disabled' value=''>Select account</option>
" . $options . "
</select>
</form>";
//echo out account form
echo $accountDropDown;
?>
This works how I need it to and displays all accounts within the drop down. However I can't seem to get the showFacilities() function to work.
getfacility.php
<?php
require_once('dbconn.php');
$q = intval($_GET['q']);
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM facility "
. "INNER JOIN accounts ON accounts.account_id = facility.account_id "
. "WHERE facility.account_id = '".$q."'";
$data = mysqli_query($dbc, $sql);
echo "<table>
<tr>
<th>Facility Number</th>
<th>Facility Name</th>
<th>Facility Address</th>
<th>Facility City</th>
</tr>";
//loop through data and display all accounts
while ($row = mysqli_fetch_array($data)) {
echo "<tr>";
echo "<td>" . $row['facility_number'] . "</td>";
echo "<td>" . $row['facility_name'] . "</td>";
echo "<td>" . $row['facility_address'] . "</td>";
echo "<td>" . $row['facility_city'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
footer.php (includes showFacilities())
<script>
function showFacilities(account){
//I wrote this to test and see if this function was even being triggered.
document.alert("test");
if(account == ""){
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("facilities").innerHTML = xmlhttp.responseText;
}
}
else{
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
}
</script>
<footer>
<p>Copyright &copy</p>
</footer>
</body>
</html>
Please tell me if I am doing this all wrong, am I laying everything out properly? Why is this function not being hit?
I have tried to a bunch of different things, and I just can't seem to get this to work, any help or advice or even a push in the proper direction will be very appreciated, thanks.
Your if else clauses don't add up (so your script is generating a script error, most likely a syntax error).
else{
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
This piece doesn't have an IF to accompany it.
This would be correct:
if(account == ""){
return;
}
else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("facilities").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
On a sidenote: Why create a form wrapper around your select (the one that where you can load accounts) when you use an onchange event to fire an XmlHTTPRequest?

document.getElementById("elementname").innerHTML = selectText puts EVERY option value in my page

So I am using this code:
function updateSelect(a) {
$type = a;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest(); }
else {
xmlhttp=new ActiveXObject
("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","selectbox.php?type=".$type,false);
xmlhttp.send();
selectText=xmlhttp.responseText;
document.getElementById("cultpicklist").options.length=0;
document.getElementById("cultpicklist").innerHTML = selectText;
And for some reason it gives me EVERY option value on the entire page (I have several DISTINCT select boxes)! selectText only pulls from a small subset of the database (i.e. an entirely different table from where this data is coming from) - why would it be doing this?
Here's what is generated on selectbox.php:
<?php
include "mysql_config.php";
$con = mysql_connect($host, $user, $pass);
if (!$con)
{
die('Could not connect to the database, please contact administrator');
}
mysql_select_db($db);
while ($cultrow = mysql_fetch_array($rescult)) {
ECHO '<option name="culture[]" value="'. stripslashes($cultrow['cult_id']) .'">'. stripslashes($cultrow['cult_desc']) .'</option>';
}
?>

Categories