what can i do to access only a specific table - javascript

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....

Related

XMLHttpRequest randomly returning Error 500, can't figure out a pattern

I building a website, which must get data both from a MySQL database on the same server, and from an external API.
I have a javascript function which calls 5 other functions, and each of them creates an XMLHttpRequest to get different kinds of data:
function getData(){
getGi(); //Function which calls an external API (Curl request) via a local php file
getPQ(); //Gets data from a MySQL DB, also via a local php file, same as next 3 functions:
getBS();
getCV();
getTP();
}
All 5 functions call a php file via XMLHttpRequest. The first php file's call is a simple curl request to an external API. The other 4 access a DB on the same server. Example (they are all similar):
function getCV(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "../php/getDB.php?t=CV", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
dados = JSON.parse(this.responseText.slice(0, -1));
initCV(dados);
}
}
}
However, upon loading the website, a few Error 500 are thrown:
CV.js:14 GET https://<url>/php/getDB.php?t=CV 500 (Internal Server Error)
The number of errors or which of the requests throw errors seem random. Sometimes I get just one error, sometimes 3 or 4, and they are never the same files. Right now I've "solved" the issue by forcing the request to try again if it fails the first time:
xmlhttp.addEventListener("load", function() {
if (xmlhttp.status == 500) {
getCV();
return
}
});
But obviously this is not a proper solution. Any ideas on how I can debug/fix this? Or is this a server issue and I should contact my webhost?
Edit: here's the php code:
<?php
//Settings
$dbhost ="localhost";
$dbuser = "user";
$dbpass = "hunter2";
$dbname ="database";
//Read parameter
$tipo = $_GET['t'];
if (is_null($tipo)) {
exit("Sem parĂ¢metro.");
}
//connect to database
$conn = #mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
//query options
mysqli_query($conn,"SET character_set_results = 'utf8mb4', character_set_client = 'utf8mb4', character_set_connection = 'utf8mb4', character_set_database = 'utf8mb4', character_set_server = 'utf8mb4'");
switch($tipo) {
case "CV":
$query = "SELECT * FROM table1";
break;
case "PI":
$query = "SELECT * FROM table2";
break;
case "PQ":
$query = "SELECT * FROM table3";
break;
case "TP":
$query = "SELECT * FROM table4";
break;
case "BS":
$query = "SELECT * FROM table5";
break;
default:
exit("Parametro invalido.");
}
//Execute query
$result = mysqli_query($conn, $query);
if (!$result){
echo "Couldn't execute the query";
die();
}
else{
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data[]=$row;
}
}
mysqli_close($conn);
echo json_encode($data, JSON_PRETTY_PRINT);
?>

Why is this function always getting called

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 :)?

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;.

Cannot pass data from my JavaScript to my PHP file

When I click on "subcribeButton" I want it to save the value and pass that value to my PHP file. I want that PHP file to then make a post to the SQL database.
This is my js:
$(".subscribeButton").on( "click", function() {
var email = $(".subscribeInput").val();
var isValid = isEmailValid(email);
if(isValid){
$(".errorMsg").css( "display", "none" );
modal.style.display = "block";
$.post( "save.php", { email: email });
$(".subscribeInput").val("");
} else {
$(".errorMsg").css( "display", "initial" );
};
});
$(".subscribeInput").on( "click", function() {
$(".subscribeInput").val("");
});
This is my php code, I would like my php code to accept data from my js file and then post the data to my sql database:
<?php
$servername = "localhost";
$username = "user";
$password = "pw";
$dbname = "db_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = $_POST['email'];
echo $text
$sql = "INSERT INTO MyGuests (email)
VALUES ($text)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The result is I'm getting the following error:
POST http://flockto.it/home/save.php 500 (Internal Server Error)
send # jquery.js:4
ajax # jquery.js:4
m.(anonymous function) # jquery.js:4
(anonymous function) # email.js:13
dispatch # jquery.js:3
r.handle # jquery.js:3
so why not adding a callback in your ajax request so you can debug it in console or with an alert see this it may help you
$.post( "save.php", { "email" : email } , function(result){
console.log(result);//here the result will display what you will echo after getting the post in your php file
});
so in your php file you can add this
if (isset($_POST['email'])){
$text = $_POST['email'];
echo $text;
}
//so if you check the console you will get the email
//value from your php file so then you can insert it at the DB as you want
You have a syntax error.
Your code is missing the ; at the end of this line:
echo $text
It should be:
echo $text;
The solution:
In the js file url was wrong and quotation marks around email were missing
$(".subscribeButton").on( "click", function() {
var email = $(".subscribeInput").val();
var isValid = isEmailValid(email);
if(isValid){
$(".errorMsg").css( "display", "none" );
modal.style.display = "block";
$.post( "data/save.php", { "email": email });
$(".subscribeInput").val("");
} else {
$(".errorMsg").css( "display", "initial" );
};
});
$(".subscribeInput").on( "click", function() {
$(".subscribeInput").val("");
});
In the php file used the wrong variable
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = $_POST['email'];
if (isset($_POST['email'])){
$text = $_POST['email'];
echo $text;
}
$sql = "INSERT INTO MyGuests (email)
VALUES ('$text')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
A million thanks to everyone who replied to this thread and helped me solve the issue.

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();
?>

Categories