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;
}
Related
I'm running a script which is supposed to send a user ID number to a database. The database grabs a bunch of image IDs from whichever row has the matching user ID, then goes to a different table and grabs the image URLs which match the image IDs. Then it returns the URLs.
The PHP script runs fine on its own, it returns the correct URL in either straight text or JSON, as requested.
As for the jQuery, the AJAX call does indeed get to the success function, because I can ask it to document.write something there and it will do it. When I ask it to print out the data, however, the AJAX call runs forever (I think it is repeatedly calling the success function? Based on the browser telling me that it is either waiting or transferring data repeatedly). Regardless, nothing is printed to the screen despite the repeating script.
Oh, also, no errors are returned to the console.
I am not sure why it is doing this and so here I am. I've browsed through the other posts here and randomly on the internet, with no luck. Any help is appreciated!
Here is the PHP:
<?php
header('Content-type: text/plain; charset=utf-8');
// define variables and set to empty values
$servername = "localhost";
$username = "root";
$password = "Wolf*6262";
$dbname = "Game";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$id = $_GET["id"];
}
$query1 = mysqli_query($conn, "SELECT imageids FROM users WHERE id = $id");
// Start user session
if ($imageIds = mysqli_fetch_array($query1)) {
fetchUrls($imageIds, $conn);
} else {
echo "Fail";
}
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = '1'");
$array = mysqli_fetch_assoc($query2);
$url = $array["url"];
exit($url);
}
$conn->close();
The jQuery:
function getUrls (userId) {
$.ajax({
type: 'GET',
data: {id:userId},
URL: 'fetchChar.php',
async: false,
dataType: 'text',
success: function (data) {
document.write(data);
document.write(userId);
}
});
}
Aaand here's where I define userId and call getUrls, it's in a separate HTML file:
var userId = <?php echo $_SESSION["id"]; ?>;
$(document).ready(getUrls(userId));
Can you please modify your script: as standard way what prefer from jQuery:
1. Change URL to url
2. Please avoid async defining
Like this
$.ajax({
type: 'GET',
data:{ id: userId },
url: 'fetchChar.php',
// async: false,
dataType: 'text',
success: function (data) {
console.log(data);
//document.write(data);
//document.write(userId);
}
});
I added console log to show the return data, so that you can make sure that your data is returning correctly from fetchChar.php file using console log.
Ended up doing the following, question solved:
Javascript file:
$.ajax({
type: "POST",
dataType: "json",
url: "fetchChar.php",
data: {id:userId},
success: function(data) {
document.write(JSON.stringify(data));
}
});
PHP file, near the end:
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = 1");
$array = mysqli_fetch_assoc($query2);
$url = $array['url'];
$url = json_encode($url);
echo $url;
exit();
}
I'm submitting a form using MySQL command inside a PHP file. I'm able to insert the data without any problem.
However, I also, at the same time, want to display the user a "Thank you message" on the same page so that he/she knows that the data has been successfully registered. On the other hand I could also display a sorry message in case of any error.
Therein lies my problem. I've written some lines in Javascript to display the message in the same page. However, I'm stuck on what (and how) should I check for success and failure.
I'm attaching my code below.
Can you please help me on this with your ideas?
Thanks
AB
HTML Form tag:
<form id="info-form" method="POST" action="form-submit.php">
form-submit.php:
<?php
require("database-connect.php");
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$sql = "INSERT INTO tbl_details ".
"(name,email_id,mobile_number) ".
"VALUES ".
"('$name','$email','$mobile')";
mysql_select_db('db_info');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
return false;
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
submit-logic.js:
$(function ()
{
$('form').submit(function (e)
{
e.preventDefault();
if(e.target === document.getElementById("info-form"))
{
$.ajax(
{
type:this.method,
url:this.action,
data: $('#info-form').serialize(),
dataType: 'json',
success: function(response)
{
console.log(response);
if(response.result == 'true')
{
document.getElementById("thankyou_info").style.display = "inline";
$('#please_wait_info').hide();
document.getElementById("info-form").reset();
}
else
{
document.getElementById("thankyou_info").style.display = "none";
document.getElementById("sorry_info").style.display = "inline";
$('#please_wait_info').hide();
}
}
}
)};
});
}
Per documentation: http://api.jquery.com/jquery.ajax/
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server.
You are explicitly setting this to json but then returning a string. You should be returning json like you are telling the ajax script to expect.
<?php
require("database-connect.php");
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$mobile = mysql_real_escape_string($_POST['mobile']);
$sql = "INSERT INTO tbl_details ".
"(name,email_id,mobile_number) ".
"VALUES ".
"('$name','$email','$mobile')";
mysql_select_db('db_info');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die(json_encode(array('result' => false, 'message' => 'Could not enter data: ' . mysql_error()));
}
echo json_encode(array('result' => true, 'message' => 'Entered data successfully'));
mysql_close($conn);
?>
I also added code to sanitize your strings, although mysql_* is deprecated and it would be better to upgrade to mysqli or PDO. Without sanitization, users can hack your database..
Nevertheless, returning json properly will ensure that your response in success: function(response) is an object, and response.result will be returned as expected, and you can use response.message to display the message where you want.
I'm developing a small script of js to edit a profile in the way facebook used to be (click a button, edit and save without reloading the page). The problem is that when I run it, the ajax function returns sucess but akes no changes on the database. The function os js is this:
$('.savebtn').click(function(){
var editdata = $(".editbox").val();
var parameter = $(this).closest("td").find("#parameter").text();
var datastring = "data="+editdata+"¶meter="+parameter;
var $t = $(this);
console.log(datastring);
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function()
{
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
});
});
(Ignore the $t thing, somehow this works like this, but not if I use $(this))
Ajax executes the code for sucess but doesn't update anything on the database.
The PHP code for the database is:
<?php
include_once("../../config/connect_db.php");
include_once("../../database/cliente.php");
$parameter = $_POST['parameter'];
$data = $_POST['data'];
$id = $_SESSION['id'];
var_dump($_POST);
try {
updateProfile($parameter, $data, $id);
}
catch (PDOException $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users
SET ? = ?
WHERE id = ?");
$stmt->execute(array($parameter, $data. $id));
}
EDIT: As pointed out, this could be a problem with trying to pass a column name as a parameter. Changed the code to the following, but with no sucess:
function updateProfile($parameter, $data, $id)
{
global $conn;
$query = "UPDATE biofood.users
SET $parameter = $data
WHERE id = $id";
$stmt = $conn->prepare($query);
$stmt->execute();
}
This line:
$stmt->execute(array($parameter, $data. $id));
I think should be
$stmt->execute(array($parameter, $data, $id));
(notice the comma after $data)
This might not solve your problem, but it might give you a better indication on where your problem is.
First, you are not checking whether it works or not as your updateProfile function returns nothing.
Modify your updateProfile function, so that it returns the number of rows affected. (BTW this is a safer way to write your function. If you can check or limit the value of $parameter prior to calling this function, it will be less prone to SQL injection.)
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users SET $parameter = ? WHERE id = ?");
$stmt->execute(array($data, $id));
return $stmt->rowCount(); // # of rows affected
}
In the script that calls this function, get the value and send it back as a response. We'll send back a JSON.
$response = array();
try {
$response['success'] = updateProfile($parameter, $data, $id);
} catch (PDOException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
header('Content-Type: application/json');
echo json_encode($response);
In your JavaScript file, make the following change:
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function (data) {
if (data.success) {
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
},
dataType: 'json'
});
I came across weird problem with my site only after uploaded it to the live server. In localhost I've no issue with these.
The problem is for login and register function. Let me talk about login first.
I keyed in the credentials and found that the page is called in the f12 network tab.However that page doesn't retrieve any data! So I put aside this jquery/ajax for a while and manually checked the php pages if they return any data but still they don't.
Now the flow like this:
login form filled up by user-> ajax request from php script-> php request from class file and return to ajax -> ajax give access to admin dashboard.
Now as I told you, I excluded ajax request and only checked with php and class file. Again it doesn't return anything from the class file to the php script though I only echoed "something"! Its not even go through any function!
Then I omitted, class file, checked the php script with ajax file.I only echo "wexckdsewndxw" and changed tha datatype in ajax to 'text'..still it doesn't get any value!
So in conclusion, data between pages are not passed at all! SO I suspect its something to do with crossDomain issue as mentioned here:
How does Access-Control-Allow-Origin header work?
But not sure how this works and how I should alter my code.
My code for reference:
login-user.js
/*login user*/
<!--login form submission starts-->
$("document").ready(function(){
$("#login-user").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "login-this-user.php",
data: data,
success: function(data) {
alert(data);
console.log(data);
var i;
for (i = 0; i < data.length; i++)
{
console.log(data[i].email);
console.log(data[i].activate);
console.log(data[i].status);
if($.trim(data[i].status)=='0')
{
//alert("not verified");
$('.invalid-popup-link').trigger('click');
}else
{
//alert("verified");
location.replace("admin/dashboard.php");
}
}//end for
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
return false;
});
});
<!--login form submission ends-->
login-this-user.php
<?php
session_start();
include('config.php');
include('class.login.php');
$return = $_POST;
//$return ='{"email":"admin#gmail.com","pass":"admin","action":"test"}';
//$return['json']= json_encode($return);
//
//below code to store in database
$data = json_decode($return, true);
$login = new checkLogin();
$status = $login->checkLogin2($data["email"],$data["pass"]);
$_SESSION['user_id']=$status;
$login = new checkLogin();
$profile = $login->check_profile($data["email"]);
$activated_id=array();
foreach($profile as $k=>$v){
array_push($activated_id,array("email"=>$v['email'],"activate"=>$v['activate'],"status"=>'0'));
$_SESSION['email'] = $v['email'];
$_SESSION['activated_id'] = $v['activate'];
}
//header('Content-Type: application/json');
echo json_encode($activated_id);
?>
class
<?php
session_start();
?>
<?php
class checkLogin
{
public $email;
public $password;
public $userId;
public $salt;
public $hpass;
public function __construct()
{
}
public function checkLogin2($param1, $param2)
{
$this->email=$param1;
$this->password=$param2;
$sql = "SELECT * FROM authsessions WHERE email='{$this->email}'";
$statement = connection::$pdo->prepare($sql);
$statement->execute();
while( $row = $statement->fetch()) {
$salt=$row['salt'];
$hashAndSalt=$row['hashpword'];
$user_id=$row['UUID'];
}
if (password_verify($this->password, $hashAndSalt)==true) {
$status = "verified";
$_SESSION['user_id'] =$user_id;
$_SESSION['logged_in']=1;
}else
{
$status = "not verified";
$_SESSION['user_id'] =0;
$_SESSION['logged_in']=0;
}
return $_SESSION['user_id'] = 1;
}
public function check_profile($param)
{
$this->email = $param;
$sql="SELECT * FROM authsessions WHERE email = '{$this->email}'";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$profile=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$profile[] = $row;
}
return $profile;
}
}
?>
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);
}
?>