Ajax function sends GET request but PHP never process it - javascript

I am trying to use Ajax to run a function in a PHP script. My two script files are as follows:
get.js:
$.ajax({
url: "testPhp.php",
data: { param1: "INITIALIZE"},
type: "GET",
context: document.body
}).done(function() {
alert("DONE!");
}).fail(function() {
console.log(arguments);
});
testPhp.php:
<?php
define("SERVER_NAME", "localhost");
define("USERNAME", "root");
define("PASSWORD", "");
define("DATABASE", "myDB");
//Print database info
echo nl2br("Server Name: " . SERVER_NAME . "\nUsername: " . USERNAME . "\nPassword: " . PASSWORD);
//Connecting to database
$mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD);
//Check database connection
if($mysqli === false) {
die ("\nCould not connect: " . mysqli_connect_error());
} else {
echo nl2br("\nConnected successfully! Host info: " . mysqli_get_host_info($mysqli));
}
//Function to execute database queries
function executeQuery($sql_query, $mysqli) {
if(mysqli_query($mysqli, $sql_query)){
echo nl2br("\n\nQuery executed successfully: $sql_query");
} else {
echo nl2br("\n\nERROR: Could not able to execute $sql_query. " . mysqli_error($mysqli));
}
}
function initializeDatabase() {
//Query to create flashcards database
$sql = "CREATE DATABASE IF NOT EXISTS " . DATABASE;
executeQuery($sql, $mysqli);
}
if(isset($_GET["param1"])) {
$arg = $_GET["param1"];
if($arg == "INITIALIZE") {
initializeDatabase();
}
}
testPhp.php contains other methods, but none are called yet. When I run the PHP script with the code of initializeDatabase() outside of the function, so it will automatically run, it works perfectly. The alert() also occurs a couple seconds after I load my webpage, when the script is run, so it seems like it is doing something during the run of the function before exiting. However, when I use the Ajax GET request, it seems as if PHP is not responding. Any ideas?

It could be failing because in the function initializeDatabase(), $mysqli is an undefined variable. Try passing $mysqli to initializeDatabase().

Related

Prevent Direct access to PHP file using AJAX

I want to prevent direct access to a certain PHP file called prevented.php
My logic is that I have a main file lets call it index.php and it generates a token and stores it in a $_SESSION variable. I also have a another file called def.php which is called using AJAX and it passes the token from the index.php to the def.php and if the $_SESSION['token'] is equal to the $_POST['token'] it defines a _DEFVAR and returns true otherwise it returns false. After I called the def.php and it returns true, I redirect to the prevented.php via javascript using location.href="prevented.php". In the top of the prevented.php file there is a code which checks if the _DEFVAR is defined or not. If not, its die with a message like invalid otherwise it displays the content of the prevented.php file. But somewhy I always get invalid message and I don't know why. Any idea how to reach the prevented.php without directly direct the page?
Here's my code:
index.php
<?php
$_SESSION["token"] = hash_hmac('sha256', "tokenString", "t2o0k0e0n3"); // Creates a hashed token
?>
<script>
$.ajax({
type: "POST",
url: "def.php",
data: {
token: '<?php echo $_SESSION["token"]; ?>'
},
cache: false,
success: function(data) {
console.log (data);
if (data) {
console.log (data + ' valid');
} else {
console.log (data + ' invalid');
}
location.href = "prevented.php";
},
error: function () {
console.log('error');
}
});
</script>
def.php
<?php
session_start();
if (!isset($_POST['token']) || $_POST['token'] != $_SESSION['token']) {
echo false;
die('invalid in def');
} else {
define('_DEFVAR', 1);
echo true;
die ('valid in def');
}
?>
prevented.php
<?php
include "def.php";
if (defined('_DEFVAR')) {
die ('valid in prevented'); // instead of this I would show the content of the page
} else {
die ('invalid in prevented');
}
?>
Your code is unnecessarily overcomplicated. If your intent is merely to ensure that visitors to protected.php have first visited index.php then all you need to do is create a session flag in one and check for its existence in the other. There is no need for any AJAX or any form POSTs. The innate behavior of PHP sessions already gives you this functionality.
index.php:
<?php
session_start();
$_SESSION['flag'] = true;
?>
click here for the protected page
protected.php:
<?php
session_start();
if ($_SESSION['flag'] ?? false) {
echo "you have previously visited index.php";
} else {
echo "you have not previously visited index.php";
}
?>

AJAX function for retrieving postgres data not working

I have a simple AJAX function bound to a button that should execute a PostgreSQL query. However, when I click the button that I bound the ajax query to, all I get is the confirmation that the database connection was successful. Nothing seems to happen withe the ajax result (should be printing to console in the handleAjax() function. What am I doing wrong?
This is the javascript code (with jquery):
$(document).ready(function() {
function sendAjax() {
$.ajax({
url: "db/database.php",
success: function (result) {
handleAjax(result);
}
});
}
function handleAjax(result) {
console.log(result);
}
$("#submit-button").on("click", sendAjax);
});
And this it the contents of database.php:
<?php
function dbconn(){
ini_set('display_errors', 1); // Displays errors
//database login info
$host = 'localhost';
$port = 5432;
$dbname = 'sms';
$user = 'postgres';
$password = 'postgres';
// establish connection
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
}
}
$conn = dbconn();
$sql = "SELECT * FROM numbers;";
$result = pg_query( $sql ) or die('Query Failed: ' .pg_last_error());
$count = 0;
$text = 'error';
while( $row = pg_fetch_array( $result, null, PGSQL_ASSOC ) ) {
$text = $row['message'];
//echo $text;
}
pg_free_result( $result );
?>
The problem is in the database.php file, all you get is "Connected." because you don't print your result at the end. Ajax only receive the output of the php file.
So at the end of your php file you should add :
echo $text;
And you also should remove the echo "Connected.";
AJAX is not a magic wand that in magic way reads PHP code. Let's say AJAX is a user. So what does user do.
Open web page
Wait until PHP execute code and display data
Tells you what he sees
If you don't display anything, ajax can't tell you what he saw.
In thi's place is worth to say that the best way to communicate between PHP and AJAX is using JSON format.
Your code generally is good. All you have to do is to display your data. All your data is in your $text var. So let's convert your array ($text) to JSON.
header('Content-Type: application/json');
echo json_encode($text);
First you set content-type to json, so ajax knows that he reads json. Then you encode (convert) your PHP array to js-friendly format (JSON). Also delete unnecessary echoes like 'Conntected' because as I said, AJAX reads everything what he sees.
You should return $conn from dbconn()
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
return $conn;
}

Parsing JSON data with a local AJAX request

I've got a php file on a webserver that executes queries to a MySQL database.
I'm testing a site on my pc (locally) that uses a js file with an AJAX request to get JSON data from that php file.
Is it possible to do it like this, or the js file must be put on the same domain server of the php file?
Because the console.log of the parsed data gives me this error:
Uncaught SyntaxError: Unexpected token I
This is the ajax call
$.ajax({
method:"POST",
crossDomain:true,
url:"url for the php file",
data:{
query: "SELECT * FROM course_categories;"
},
success: function(response){
var course_categories=JSON.parse(response);
console.log(course_categories);
var el="";
console.log(course_categories.length);
for(var i=0;i<(course_categories.length);i++)
{
}
},
error: function(request,error){
console.log("ERROR: Request " + request + "\nSpecific Error: " + error);
}
While this is the PHP call
<?php
//get all the courses from the database and reply using the JSON structure
//$mysqli=new msqli("localhost","username","password","dbname");
$mysqli=new mysqli("localhost","hey","","db_name");
if(mysqli_connect_errno()) //returns a number of the error if there is any, if not
{
echo json_encode("Error to connect to DBMS".mysqli_connect_error());
exit(); //closes the connection
}
else
{
$query=$_POST["query"];
//$query="SELECT * FROM course_categories";
$result=$mysqli->query($query); //do a query (->query) setted by $query, using the $mysqli variable, and store the data in $result
if($result->num_rows >0) //if there is at least one row...
{
$myArray= array(); //...create an array...
while($row = $result->fetch_array(MYSQL_ASSOC))
{
//...and fetch it. Everytime this operation returns a row,
$myArray[]=$row; //...and added to myArray ([] means autoincrement).
}
}
echo json_encode(utf8ize($myArray));
//free result
$result->close();
//close connection
$mysqli->close();
}
I did it. All I had to do, was to remove the crossDomain:true line so that the JSON could actually parse the data.

Secure AJAX POST/GET jquery

So basically my question is simple.
Imagine situation when you a making a login or register form. With jquery.post i make ajax call
$.post( "pages/form_handle.php", name: $.(".username").val(), pass: $.(".pass").val() , function( data ) {
$( ".result" ).html( data );
});
it's simple call(i belive so)...
How to make it secure?
So if user look in my source code he or she know where i send my data in example pages/form_handle.php also he or she know what data i send to this page.
One of idea what i have simple send all ajax calls to one page ajax.php adding extra variables who will call right php function for ajax call...
But does it is the right way? Or maybe there is some better way to make it secure?
Stick to basics, and keep salting your passwords.
AJAX is not server side language, its a javascript plugin that does the same thing as forms, actions, etc... just in background as a new request.
Your ajax is not in danger, but your php files are, you can use jquery-validate.js to check on users input, but also you should make validation check in your ajax.php.
Here is a simple ajax login request:
function loginUser() {
var process = "loginUser";
var data = $("form").serializeArray();
data[1].value = data[1].value; // data to ajax.php page
data = JSON.stringify(data);
$("#loginButton").html('Login');
$.ajax({
type: "POST",
url: "ajax.php",
data: {"process": process, "data": data},
success: function(data) {
if (data.response.state == "success") {
// if ajax.php returns success, redirect to homepage or whatever
} else {
// if ajax.php returns failure, display error
}
},
error: function(jqXHR, textStatus, errorThrown, data) {
// error handling
},
dataType: "json"
});
}
And the simple ajax.php login:
<?php // ajax.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
if (isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW'])){
$un_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_USER']);
$pw_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_PW']);
$query = "SELECT * FROM users WHERE username='$un_temp'";
$result = mysql_query($query);
if (!$result) die("Database access failed: " . mysql_error());
elseif (mysql_num_rows($result)){
$row = mysql_fetch_row($result);
$salt1 = "qm&h*";
$salt2 = "pg!#";
$token = md5("$salt1$pw_temp$salt2");
if ($token == $row[3]) echo "$row[0] $row[1] :
Hi $row[0], you are now logged in as '$row[2]'";
else die("Invalid username/password combination");
} else die("Invalid username/password combination");
}else{
header('WWW-Authenticate: Basic realm="Restricted Section"');
header('HTTP/1.0 401 Unauthorized');
die ("Please enter your username and password");
}
function mysql_entities_fix_string($string){
return htmlentities(mysql_fix_string($string));
}
function mysql_fix_string($string){
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return mysql_real_escape_string($string);
}
?>

Javascript to Microsoft SQL Server (AJAX request)

I have a problem, how can i select data from my database (Microsoft SQL Server) from my javascript by an AJAX request.
I know I need a "server language", but it seems that PHP cannot do this !
How can I do ?
Thank you !
PHP is a server side language. Drivers are created for thee PHP package that allow them to interface with several different types of database architecture systems. In this case, the SQL Server would be connected to through the sqlsrv drivers for PHP.
A simple query to the database looks like the following:
-- query.php --
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM Person";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
$name = sqlsrv_get_field( $stmt, 0);
echo $name; //maybe the name is "George"
This establishes the connection, and then attempts to query the database. As we're just retrieving one row, we use sqlsrv_fetch() to attempt to populate the $stmt variable. If it works, then we'll get $name as a return from the row at column with index 0. This will return the value of $name to the success function of our ajax call (as illustrated below)
The $.ajax() is simple. Figure out what element is going to fire the ajax call, then just do it..
$('element').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'query.php',
type: 'GET',
success: function(data){
console.log(data); //will show George in the console
//otherwise it will show sql_srv errors.
}
});
});
Resources
sqlsrv_connect()
sqlsrv_query()
$.ajax()
For connecting to SQL Server... You can use this code...
public function connect() {
$dsn = "Driver={SQL Server};Server=xxxxx;Port=1433;Database=yyyy";
$data_source='zzzz';
$user='dbadmin';
$password='password';
// Connect to the data source and get a handle for that connection.
$conn=odbc_connect($dsn,$user,$password);
if (!$conn) {
if (phpversion() < '4.0')
{
exit("Connection Failed: . $php_errormsg" );
}
else
{
exit("Connection Failed:" . odbc_errormsg() );
}
}
return $conn;
}
Please note, here I have created a data source. This code is using ODBC as you can see. ;)
And this connection is using Sql Authentication.
Hope this helps...
Asp.net
Client Side Code
$.ajax({
url: "ViewData.aspx/GetTransitNameById",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"Transitid":"' + id + '"}',
success: function (result) {
// You got the required data in result.d
var finalresult = result.d;
}
});
Server Side Code
[WebMethod]
public static string GetTransitNameById(int Transitid)
{
string name = "";
try
{
oohMonitoringManager om = new oohMonitoringManager();
name = om.GetTransitNameByTransitId(Transitid);
// here you got what you needed.
// name contains the data that you have to return back to the javascript ajax function
}
catch (Exception a1)
{ }
return name;
}

Categories

Resources