I am trying to search for all properties in a database that are in one suburb. I have read that it has something to do with the HTML code 204 but I still do not undertand what to do or what it really means. I have not done any JS or PHP in a while so this may be a really silly error but I cannot for the life of me figure it out. Please Help!
Here is my JS code:
function basicSearch(){
//Connect Script to the PHP
var urlLink = "basicSearch.php";
//Get search parameters:
var searchAreaBar = document.getElementById("searchAreaBar").value;
//define the parameters to send to php
var strParameters = "searchAreaBar="+searchAreaBar + "&sid=" + Math.random();
// define the options for the AJAX request
var objOptions = {
// use method post
method: "post",
// use strParameters as the parameters
parameters: strParameters,
// if successfil call fuction(objXHR)
onSuccess: function(objXHR) {
// if objXHR. responseText = yes
if(objXHR.responseText=='Yes'){
alert("Success!");
}
else{
alert("Error! No Properties Found!");
}
}
}
// define the AJAX request object
var objRequest = new Ajax.Request(urlLink,objOptions);
}
Here is my PHP code:
<?php
//Link the username and password:
$connect = mysqli_connect("localhost", "admin", "12345", "realestate") or die ('Connection to database failed: ' . mysql_error());
//Extract variables for request parameters:
extract($_REQUEST);
//Define the query:
$BasicSearch = "SELECT * FROM properties WHERE Suberb='$searchAreaBar'";
//Run the query:
$resDasicSearch = mysqli_query($BasicSearch) or die(mysql_error());
//SET intCount to number of rows in result:
$intCount = mysqli_num_rows($resDasicSearch);
//If intCount is greater than 0:
if($intCount > 0){
//Echo Yes:
echo "Yes";
}
else{
//Echo no:
echo "No";
}
?>
Thanks in advance.
The error was that the browser's compiler was "commenting out" all the php and adding empty HTML tags. It was then getting confused as there was an "empty" document.
This was because the website (including JS, PHP and HTML files) were being stored and run from a local directory. For example:
the URL read:
file:///C:/xampp/htdocs/"Project Name"/Index.html
the correct URL is:
localhost/"Project Name"
IF you are using XAMPP, the folder containing all your project files need to be placed in the htdocs folder in the xampp directory.
As you seem to be using an Ajax function that is not shown it is hard to determine the root cause of the problem because nothing above, as far as I can tell, would yield the error you allude to in the title of the posting - namely "XML Parsing Error: no root element found" - I wonder therefore if there should be a configuration option in Ajax.Request that needs to be set to deal with a basic string response?
That aside you might be able to make use of the following - perhaps even for diagnosis purposes.
<?php
/*
---------------
basicSearch.php
---------------
*/
$dbhost = 'localhost';
$dbuser = 'admin';
$dbpwd = '12345';
$dbname = 'realestate';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql='select * from `properties` where `suberb`=?';
$stmt=$db->prepare( $sql );
if( $stmt ){
$searcharea = $_POST['searchAreaBar'];
$stmt->bind_param( 's', $searcharea );
$stmt->execute();
$stmt->store_result();
$stmt->bind_result( $suberbs );
$stmt->fetch();
echo $stmt->num_rows()==0 ? "No" : "Yes";
}
$stmt->close();
$db->close();
?>
<script>
/* reuseable utility ajax function */
function ajax( method, url, params, callback, options ){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )callback.call( this, xhr.response, options, xhr.getAllResponseHeaders() );
};
var async=params.hasOwnProperty('async') ? params.async : true;
var query=[];
for( var n in params )query.push(n+'='+params[n]);
switch( method.toLowerCase() ){
case 'post': query=query.join('&'); break;
case 'get': url+='?'+query.join('&'); params=null; break;
}
xhr.open( method.toUpperCase(), url, async );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( params );
}
/* function that does the search */
function function basicSearch(){
/* configure the parameters to be used in the ajax request */
var method='post';
var url='basicSearch.php';
var params={
searchAreaBar:document.getElementById('searchAreaBar').value,
sid:Math.random()
};
var callback=function(r,o,h){
alert( r ? 'Success' : 'Error! No Properties Found!' )
}
var options={};
/* call the ajax function */
ajax.call(this,method, url, params, callback, options);
}
</script>
Today I meet this error in Firefox's console, that is so simple, while all my API return JSON, one of my API return text/html and it causes Firefox show up that error!
I have changed my NodeJS Express code:
res.end('');
To
res.json({});
ANd it is okay now! Hope it can help someone!
Related
I'm creating an application in PHP for Wordpress and at this point, I'm trying to fetch a value from a database through AJAX every 2 seconds, and I've created a new file with the function that should be fired.
<?php
global $wpdb;
function conta(){
global $wpdb, $table_name;
$count = $wpdb->get_var("SELECT contatore FROM $table_name WHERE email = '$mail'");
echo "$count";
}
conta()
?>
An this function is called here with an XMLHttpRequest Object every 2 seconds
setInterval(function () {
var url = <?php echo json_encode($con); ?>;
var valuereq = new XMLHttpRequest();
valuereq.open("GET", url, true);
valuereq.send();
valuereq.status;
valuereq.onreadystatechange = function () {
if (valuereq.readyState == 4 && valuereq.status == 200) {
var return_data = valuereq.responseText;
document.getElementById("conta").innerHTML = "Executed: " + return_data;
}
else document.getElementById("conta").innerHTML = "Error";
}
}, 2000);
The Http request is executed correctly, but I receive this error:
Fatal error: Uncaught Error: Call to a member function get_var() on null in
C:\xampp\apps\wordpress\htdocs\wp-content\plugins\bittrex-
trader\admin\partials\conta.php:7 Stack trace: #0
C:\xampp\apps\wordpress\htdocs\wp-content\plugins\bittrex-
trader\admin\partials\conta.php(11): conta() #1 {main} thrown in
C:\xampp\apps\wordpress\htdocs\wp-content\plugins\bittrex-
trader\admin\partials\conta.php on line 7
The program is not able to find the global variable $wpdb, even though is declared. This happens only with the AJAX request because if i include directly the file $wpdb is found and working.
Is there a reason?
Thank you in advance.
Your $mail variable is not set inside the conta() function, yet you perform a query with it.
Use this to load basic wordpress (only loads wordpress core) so you can use $wpbd:
<?php
// use this flag to load only wordpress core
define( 'SHORTINIT', true );
// find the wp-load.php file and require it
require( '/path/to/wp-load.php' );
// now you can use $wpdb
function conta($wpdb, $table_name, $mail)
{
$count = $wpdb->get_var("SELECT `contatore` FROM `".$table_name."` WHERE `email` = '".$mail."'");
echo "$count";
}
// call the function and pass the parameters
conta($wpdb, $table_name, $mail);
// close connection
$wpdb->close();
?>
More on the flag for worpdress core here.
I have this (soon-to-be, hopefully) ABM application running on XAMPP.
I've already dealt with its validations and the query for the insert.
I have a file for registering subjects, in an html form, with a button type="submit".
So, when the options are selected and the input filled, when pressing the button a function is called (in a javascript file) --> it validates the data and sends a request to put the info in a database. Here's the js file:
function registerSubjects(){
var carreraMateria = "";
var nombreMateria = "";
var descripcionMateria = "";
var cargaHorariaMateria = "";
if(validacionFormularioAlta()){ //this is the main validating function
$.ajax({
url: 'http://localhost/path/registerSubjects.php',
type: "POST",
data: {"carreraMateria": carreraMateria,
"nombreMateria": nombreMateria,
"descripcionMateria": descripcionMateria,
"cargaHorariaMateria": cargaHorariaMateria,
},
dataType: "html",
beforeSend: function() {
console.log("I'm in before send part");
},
success: function(data) {
if( data == "OK"){
console.log("it saved the data");
location.href = "http://localhost/path/main.php";
return;
}
//Note: There are better ways, this is just because I'm learning, will try to improve on it later :)
if( data == "ERROR"){
console.log("not saved");
alert("error, please try again");
return;
}
alert("Server message: " + data);
}
});
}else{
alert("Incorrect inputs");
}
}
Data from the form is "caught" using these variables (javascript file):
carreraMateria = document.getElementById("carreraMateria").selectedIndex;
nombreMateria = document.getElementById("nombreMateria").value;
descripcionMateria = document.getElementById("descripcionMateria").value;
cargaHorariaMateriaElemento = document.getElementById("cargaHorariaMateria");
cargaHorariaMateriaSeleccion = document.getElementById("cargaHorariaMateria").selectedIndex;
cargaHorariaMateria = parseInt(document.getElementById("cargaHorariaMateria").value);
And..... this is the registerSubjects.php which deals with some server-side validations and the INSERT:
<?php
//Connection data
include("../extras/conexion.php");
//Inicialization of variables
$carreraMateria = "";
$nombreMateria = "";
$descripcionMateria = "";
$cargaHorariaMateria = "";
//Getting data
$carreraMateria = $_POST['carreraMateria'];
$nombreMateria = $_POST['nombreMateria'];
$descripcionMateria = $_POST['descripcionMateria'];
$cargaHorariaMateria = $_POST['cargaHorariaMateria'];
//CONNECTION
$CONN = new mysqli($serverName, $username, $password, $dataBase);
// Verifico la conexion
if ($CONN->connect_error) {
die("Problema al conectar con la base de datos" . $CONN->connect_error);
return;
}
//INSERT!
//Query para introducir los datos en la base
$SQL = "INSERT INTO subjects(career_id, name, description, hours) VALUES (?, ?, ?, ? )";
if($stmt = $CONN->prepare($SQL))
$stmt->bind_param('ssss', $carreraMateria, $nombreMateria, $descripcionMateria, $cargaHorariaMateria);
$stmt->execute();
$id = $stmt->affected_rows;
$stmt->close();
}
//Check for row modification
if($id>0 ){
echo "OK";
}else{
echo "ERROR";
}
return;
?>
And so it is... I had the connection part and its checking in a different file, but was causing some problems. I've written that in the files themeselves and now the ajax is working "fine"... well, at least is working :/
The thing is... I can't insert anything... I'm stuck in my own alert, in the part that says (in the AJAX part):
if( data == "ERROR"){
console.log("not saved");
alert("error, please try again");
return;
}
Can't seem to be realizing what's wrong. At first I wasn't "catching" the values in the JS file correctly, I've fixed that, but now I can't have the INSERT working right.
Apparently I'm getting the values right (from the form, from what was selected), and I'm referencing them well, so I'm pretty confused.
EDIT1:
I've tried getting the values received in the php file; I've done this:
$carreraMateria = $_POST['carreraMateria'];
var_dump($_POST["carreraMateria"]);
$nombreMateria = $_POST['nombreMateria'];
var_dump($_POST["nombreMateria"]);
$descripcionMateria = $_POST['descripcionMateria'];
var_dump($_POST["descripcionMateria"]);
$cargaHorariaMateria = $_POST['cargaHorariaMateria'];
var_dump($_POST["cargaHorariaMateria"]);
And the result was:
string(0) ""
string(0) ""
string(0) ""
string(0) ""
Then I GUESS I'm not getting the data correctly...? :/
EDIT2:
I've disabled the PHP and AJAX parts, and was just testing the JavaScript. I've "caught" the values and printed them into console log, and they show fine, so now the problem is with transferring them into the PHP file to insert them into the database.
if($stmt = $CONN->prepare($SQL)) {
$stmt->bind_param('ssss', $carreraMateria, $nombreMateria, $descripcionMateria, $cargaHorariaMateria);
$stmt->execute();
$stmt->execute();
$id = $stmt->affected_rows;
$stmt->close();
}
there was a missing open bracked
This is functioning now :)
In the javascript file, I had declared the variables meant for initialization inside the function registerSubjects(), and so they were empty when trying to pass them. They had to be declared as global variables, outside the function.
function showFeature(geojson, style){
currentFeature_or_Features = new GeoJSON(geojson, style || null);
if (currentFeature_or_Features.type && currentFeature_or_Features.type == "Error"){
document.getElementById("put_geojson_string_here").value = currentFeature_or_Features.message;
return;
}
if (currentFeature_or_Features.length){
for (var i = 0; i < currentFeature_or_Features.length; i++){
if(currentFeature_or_Features[i].length){
for(var j = 0; j < currentFeature_or_Features[i].length; j++){
currentFeature_or_Features[i][j].setMap(map);
if(currentFeature_or_Features[i][j].geojsonProperties) {
setInfoWindow(currentFeature_or_Features[i][j]);
}
}
}
else{
currentFeature_or_Features[i].setMap(map);
}
if (currentFeature_or_Features[i].geojsonProperties) {
setInfoWindow(currentFeature_or_Features[i]);
}
}
}else{
currentFeature_or_Features.setMap(map)
if (currentFeature_or_Features.geojsonProperties) {
setInfoWindow(currentFeature_or_Features);
}
}
document.getElementById("put_geojson_string_here").value = JSON.stringify(geojson);
}
I am developing a application that can show the point in the map using google maps api and php but i had a button if you clique for searching the page refreshed i would that if i search the point (var geojson_parce) the page show the result (showFeature(geojson_parce,adressStyle) but not be refreshed (tourned). please if you have a solution help me
<?php
$host = "localhost";
$user = "postgres";
$password = "20152016";
$db = "Projet";
$con = pg_connect("host=$host dbname=$db user=$user password=$password")
or die ("Could not connect to server\n");
?>
<h4>Afficher par nom:</h4>
<form>
<input type="text" name="term" /><br />
<input type="submit" Onclick="showFeature(geojson_parce,adressStyle);"></input>
</form>
<?php
if (!empty($_REQUEST['term'])) {
$term = pg_escape_string($_REQUEST['term']);
$sql = "SELECT row_to_json(fc)
FROM ( SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features
FROM (SELECT 'Feature' As type
, ST_AsGeoJSON(lg.geometry)::json As geometry
, row_to_json(lp) As properties
FROM poi As lg
INNER JOIN (SELECT id, description FROM poi WHERE nom LIKE '%".$term."%') As lp
ON lg.id = lp.id ) As f ) As fc;";
$result = pg_query($con, $sql);
while ($row = pg_fetch_assoc($result))
{
foreach($row as $rslt);
?>
var geojson_barrage=<?php
echo $rslt;
} }?>;
To achieve what you want to do ( get details from the db to show markers on the map without reloading the page ) you would need to restructure your code and utilise ajax.
Currently the submission of the form will set the variable $term which is then used in the sql query but obviously this has the negative side effect of reloading the page.
The best way to achieve what you want to do is to send a POST request via Ajax to your script that will send the json response back to your javascript function - and NOT reload the page as it is asynchronous.
The following code snippets are not tested but they should give you the idea of what I mean.
/*
At the top of your php page, this php code will get the data
from the database when it receives a POST request:
*/
<?php
$host = "localhost";
$user = "postgres";
$password = "20152016";
$db = "Projet";
$con = pg_connect("host=$host dbname=$db user=$user password=$password") or die ("Could not connect to server\n");
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/* get the POSTed variables from your ajax call and query the database */
#ob_clean();
$term = isset( $_POST['term'] ) && !empty( $_POST['term'] ) ? $_POST['term'] : false;
if( !$term ) exit( json_encode( array('error'=>'Search term was empty') ) );
$sql = "select row_to_json(fc)
from ( select 'featurecollection' as type, array_to_json(array_agg(f)) as features
from ( select 'feature' as type, st_asgeojson(lg.geometry)::json as geometry, row_to_json(lp) as properties
from poi as lg inner join ( select id, description from poi where nom like '%".$term."%') as lp
on lg.id = lp.id ) as f ) as fc;";
/* Query db */
$result = pg_query($con, $sql);
/* Process the recordset and construct your data response */
/*
send json data: it is this data that YOUR showFeature
function uses. It equates to "http.responseText"
in the ajax function
*/
header("Content-Type: application/json; charset=UTF-8",true);
echo $data;
exit();
}
/* Any other code below ... */
?>
In the HEAD section where your javascript is:
<script>
/* How / where is this set? */
var adressStyle;
function showFeature(geojson, style){
var node=document.getElementById("put_geojson_string_here");
var cff = new GeoJSON( geojson, style || null );
if (cff.type && cff.type == "Error"){
node.value = cff.message;
return;
}
if( cff.length ){
for( var i = 0; i < cff.length; i++ ){
if( cff[i].length ){
for( var j = 0; j < cff[i].length; j++ ){
cff[i][j].setMap(map);
if( cff[i][j].geojsonProperties ) setInfoWindow( cff[i][j] );
}
} else{
cff[i].setMap(map);
}
if( cff[i].geojsonProperties ) setInfoWindow( cff[i] );
}
} else {
cff.setMap(map)
if( cff.geojsonProperties ) setInfoWindow( cff );
}
node.value = JSON.stringify( geojson );
}
function getdata(){
/* ajax */
var http=new XMLHttpRequest();
var headers={
'Accept':"text/html, application/xml, application/json, text/javascript, "+"*"+"/"+"*"+"; charset=utf-8",
'Content-type':'application/x-www-form-urlencoded',
'X-Requested-With':'XMLHttpRequest'
};
/* Assign a callback listener for when the data is received */
http.onreadystatechange=function(){
if( http.readyState==4 && http.status==200 ) showFeature.call( this, http.responseText, adressStyle );
}
/* Open the POST request */
http.open( 'POST', document.location.href, true );
/* Send some headers - Content-Type is important */
for( header in headers ) http.setRequestHeader( header, headers[ header ] );
/* Actually send the request variables */
http.send( 'term='+document.getElementById('term').value );
}
</script>
And the html form
<form>
<input type="text" id='term' name="term" /><br />
<input type="button" onclick="getdata();" value='Submit query' />
</form>
So, the user clicks the button ( which does not now submit the form in the traditional sense ) which sends an AJAX POST request to the same page - the request is handled by the PHP code above ( it only gets executed if the request is a POST request though you might want to add other conditions to that ) and the PHP code queries the database, processes the recordset and echoes back the json data which is used to add the markers to the map. Your original javascript function showFeature is acting now as the callback to the ajax request but, as it wasn't shown in your question, I do not know how it works or what it does exactly.
Write the showFeature() function as this:
function showFeature(event,geojson_parce,adressStyle){
event.preventDefault();
//...do rest of function
}
and the call will be
onclick = "showFeature(event,geojson_parce,adressStyle)"
Calling preventDefault() on the event object will prevent the page from refreshing when clicking submit.
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
The page is getting refresh because of submit button in for. To prevent page load you need to unbind submit in form. You can achieve this by following ways,
<input type="button" onclick="showFeature(geojson_parce,adressStyle);">Search</input>
At the end of this function showFeature just add.
return false;
or like below as well
<input type="button" onclick="showFeature(geojson_parce,adressStyle); return false;">Search</input>
Hope this helps to you.
I am following this post:Can't get html5 Canvas signature pad to submit to database, and is a great signature script, but I already have a error when I tried to save it into DB...the console give me this error:
Error: Failed to construct 'XMLHttpRequest': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
Can you help me with this part of javascript to fix it:
$("#saveSig").click(function saveSig() {
//encode URI
var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
$("#imgData").html('Thank you! Your signature was saved');
var ajax = XMLHttpRequest();
ajax.open("POST", 'sign/signature.php');
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(sigData);
$('#debug').html(sigData);
});
The error message says what you should do: you should use the 'new' operator to construct 'XMLHttpRequest'.
Where you create your ajax object, change var ajax = XMLHttpRequest(); to var ajax = new XMLHttpRequest();
Since you are using jquery anyway, you can use jquerys ajax method to make the ajax request instead of dealing with the browser specifics of XMLHttpRequest.
$("#saveSig").click(function saveSig() {
//encode URI
var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
$.ajax({
type: "POST",
url: 'sign/signature.php',
contentType: 'application/upload',
data: sigData,
success: function () {
$("#imgData").html('Thank you! Your signature was saved');
}
});
$('#debug').html(sigData);
});
Update In response to you comments:
You must understand, that this javascript and the... click(function saveSig() {...} is executed in the browser. So you shouldn't put any php in there, because the php must be executed by the webserver. When you click on the "#saveSig" element, the browser executes this function and with the call of $.ajax(...) it sends a new HTTP POST request to the webserver in the background calling the url 'sign/signature.php'. The response data to that request is available to the success function. Here follows an example of how the webserver (php) and the browser (javascript) could work together.
sign/signature.php
<?php
// read the request data:
$sigData = (isset($_POST['data'])) ? $_POST['data'] : "";
$user_id = (isset($_POST['UserId'])) ? $_POST['userId'] : "";
// process your sigData here (e.g. save it in the database together with the user_id)
//generate the response:
echo "Successfully saved signature for user id: ".$user_id.".";
?>
javascript:
$("#saveSig").click(function saveSig() {
//encode URI
var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
$.ajax({
type: "POST",
url: 'sign/signature.php',
contentType: 'application/upload',
data: {
data: sigData,
user_id: $('#user_id').val() // this get's the value from the hidden user_id input
},
success: function (responseData) {
$("#imgData").html('Thank you!' + responseData);
}
});
$('#debug').html(sigData);
});
Maybe the AJAX Introduction by w3schools is interesting to you
I already found the answer!
this is the hidden input in the canvas:
<input type="hidden" value="<?php echo $user_id; ?>" name="user_id" id="user_id" />
here is the code which will run this script:
$("#saveSig").click(function saveSig() {
//encode URI
var sigData = canvas.toDataURL("image/png");
var user_id = $("#user_id").val(); //here the id is showed, like 1, 2, etc
$("#firm").html("Thank you! Your signature was saved with the id: "+user_id);
$("#debug").html(sigData);
var ajax = new XMLHttpRequest();
ajax.open("POST", "sign/signature.php",false);
ajax.onreadystatechange = function() {
console.log(ajax.responseText);
}
ajax.setRequestHeader("Content-Type", "application/upload");
ajax.send("imgData="+sigData);
// ajax.send("user_id"+user_id); //here give me this error: InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.
});
DB connection:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
$session_id = $_SERVER['REMOTE_ADDR'];
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
//$user_id = (isset($_POST['user_id'])) ? $_POST['user_id'] : ""; //not works
//$user_id = $_POST['userId']; //not works
$user_id = '1'; // when I put a number the id is saved
// process your sigData here (e.g. save it in the database together with the user_id)
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
$imageName = "sign_" . rand(5,1000) . rand(1, 10) . rand(10000, 150000) . rand(1500, 100000000) . ".png";
//Set the absolute path to your folder (i.e. /usr/home/your-domain/your-folder/
$filepath = "../signature/" . $imageName;
$fp = fopen("$filepath", 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
//Connect to a mySQL database and store the user's information so you can link to it later
include_once("CONN/configs.php");
try{
$statement = $conn->prepare("INSERT INTO SIGNATURE (`session`, `user_id`, `signature`) VALUES (?, ?, ?)");
if ($statement->execute(array($session_id, $user_id, $imageName)));
echo '<div class="alert alert-success">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Firma con id: '.$user_id.' guardada correctamente.</div>';
}
catch (Exception $e)
{
echo '<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Error al tratar de guardar la firma.</div>';
die;
}
}
?>
I hope someone will need this.
Best regards!
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;
}