insert browsers geoposition into mysql table with php? - javascript

I'm trying to store browser's geoposition obtained with javascript and posted via $.ajax into mysql table with php. I receive the posted data and converted in a recursive array so I can get only the latitude and longitude data but I'm getting two warnings(I will comment on code):
1->Warning: mysqli_real_escape_string() expects parameter 2 to be string, object given in.
2->Warning: mysqli_error() expects exactly 1 parameter, 0 given in
Here is my code:
geolocation and send data:
if (window.navigator.geolocation) {
var failure, success;
success = function (position) {
console.log(position);
var stringData = JSON.stringify(position, null);
$.ajax({
type: "POST",
url: "GL_.php",
data: {
data: stringData
}
});
};
failure = function (message) {
alert('Cannot retrieve location!');
};
navigator.geolocation.getCurrentPosition(success, failure, {
maximumAge: Infinity,
timeout: 5000
});
}
...Receive data - > ...
<? php
$hostname_connection = "p:localhost";
$database_connection = "s_c"
$username_connection = "root";$password_connection = "";
$cs_connection = mysqli_connect($hostname_connection, $username_connection, $password_connection, $database_connection) or trigger_error(mysqli_error(), E_USER_ERROR); mysqli_set_charset($cs_connection, 'utf8');
function mysqli_result($res, $row, $field = 0) {
$res - > data_seek($row);
$datarow = $res - > fetch_array();
return $datarow[$field];
}
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}
global $cs_connection;
$theValue = > function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string($cs_connection, $theValue) : mysqli_escape_string($theValue); //FIRST WARNING
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'".$theValue."'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'".$theValue."'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
if (isset($_POST['data'])) {
$dataString = $_POST['data'];
}
function geoCodeUser($dataString) {
global $database_connection;
global $cs_connection;
$position = json_decode($dataString, true);
$lat = $position['coords']['latitude'];
$lng = $position['coords']['longitude'];
if ($dataString !== NULL) {
$insertLatLng = sprintf("INSERT INTO usergeoloc (lat,long) VALUES (%s, %s)", GetSQLValueString($cs_connection, $lat, "text"), GetSQLValueString($cs_connection, $lng, "text"));
$Result1 = mysqli_query($cs_connection, $insertLatLng) or die(mysqli_error($cs_connection)); //SECOND WARNING
} else {
echo "NO CONTENT";
}
}
geoCodeUser($dataString);
?>
The variables $lat and $lng are populated each one with the corresponding value but as I've mentioned previously the error came up. Can anyone explain what's wrong here?

For the first error your problem is you are calling your GetSQLValueString method wrong, you have it defined as
GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
but are calling it with these arguments
GetSQLValueString($cs_connection, $lat, "text"),
GetSQLValueString($cs_connection, $lng, "text")
so $theValue gets set to an object (the mysqli link)
As for the mysqli_error error you are not passing it the required argument
http://php.net/manual/en/mysqli.error.php
Procedural style
string mysqli_error ( mysqli $link )
you have:
die(mysqli_error())
it should be
die(mysqli_error($cs_connection))

Catch like this:
if($cs_connection){
$theValue = mysqli_real_escape_string($cs_connection, $theValue);
} else {
// No DB Connection, so no way reason to escape
}

Related

what can I do to prevent xss code?

I have escaped my fields, but when I make an xss code like <script>alert(one frame);</script> then the table which is specially for display the date the xss code is sent it to my database. I want when I make my own xss code dont send the JS script to my database.
$code = trim(stripslashes(htmlspecialchars($_POST['code'])));
$product = trim(stripslashes(htmlspecialchars($_POST['product'])));
$result = new sale();
$sale_type = $result->getTypeSaleById($_POST['sale_type']);
$purchase_price = trim(stripslashes(htmlspecialchars($_POST['purchase_price'])));
$sale_price = trim(stripslashes(htmlspecialchars($_POST['sale_price'])));
$min_stock = trim(stripslashes(htmlspecialchars($_POST['min_stock'])));
$stock = trim(stripslashes(htmlspecialchars($_POST['max_stock'])));
my controller
case 'add_product':
if(isset($_POST['code']) && $_POST['code']!= '' && isset($_POST['product']) && $_POST['product']!= '' && isset($_POST['sale_type']) && $_POST['sale_type']!= '' && isset($_POST['purchase_price']) && $_POST['purchase_price']!= 0 && isset($_POST['sale_price']) && $_POST['sale_price']!= 0 && isset($_POST['min_stock']) && $_POST['min_stock']!= '' && isset($_POST['max_stock']) && $_POST['max_stock']!= '' ){
$code = trim(stripslashes(htmlspecialchars($_POST['code'])));
$product = trim(stripslashes(htmlspecialchars($_POST['product'])));
$result = new sale();
$sale_type = $result->getTypeSaleById($_POST['sale_type']);
$purchase_price = trim(stripslashes(htmlspecialchars($_POST['purchase_price'])));
$sale_price = trim(stripslashes(htmlspecialchars($_POST['sale_price'])));
$min_stock = trim(stripslashes(htmlspecialchars($_POST['min_stock'])));
$stock = trim(stripslashes(htmlspecialchars($_POST['max_stock'])));
$newProduct = new product();
if($newProduct->add($code,$product,$sale_type,$purchase_price,$sale_price,$min_stock,$stock)){
echo "success";
}else{
echo "it cannot be added";
}
}
else{
echo "something went wrong";
}
break;
my javascript function
function addProduct(){
var code = $('#code').val();
var product = $('#product').val();
var sale_type = $('#sale_type').val();
var purchase_price = $('#purchase_price').val();
var sale_price = $('#sale_price').val();
var min_stock = $('#min_stock').val();
var max_stock = $('#max_stock').val();
var valCheck = verificar();
if(valCheck == true){
$.ajax({
url: '../controller/product_controller.php',
type: 'POST',
data: 'code='+code+'&product='+product+'&sale_type='+sale_type+'&purchase_price='+purchase_price+'&sale_price='+sale_price+'&min_stock='+min_stock+'&max_stock='+max_stock+'&boton=add_product',
}).done(function(ans){
if(ans == 'success'){
$('#code,#product,#purchase_price,#sale_price').val("");
$('#sale_type').val('0');
$('#min_stock,#max_stock').val('0');
$('#success').show().delay(2000).fadeOut();
searchProduct('','1');
}else{
alert(ans);
}
})
}
else {
}
}
XSS code in database
datable
While displaying data from database, use htmlspecialchars() function.

Parse JSON array with AJAX from PHP

I am having trouble making an PHP API to get data from MYSQL and parse JSON. I have a demo app (hiApp) and comes with some JSON files inside a folder.
The demo JSON file is like this:
{ "err_code": 0, "err_msg": "success", "data": [{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]}
This what my contacts.php is returning:
[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]
My contacts.php api looks like this:
…
…
$result = mysql_query("select * from sellers", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['nickname'] = $row['first_name'];
$row_array['location'] = $row['territory'];
array_push($json_response,$row_array);
}
echo json_encode($json_response);
?>
The js file to parse JSON, looks like this:
define(['utils/appFunc',
'i18n!nls/lang',
'components/networkStatus'],function(appFunc,i18n,networkStatus) {
//var apiServerHost = window.location.href;
var xhr = {
search: function(code, array){
for (var i=0;i< array.length; i++){
if (array[i].code === code) {
return array[i];
}
}
return false;
},
getRequestURL: function(options){
//var host = apiServerHost || window.location.host;
//var port = options.port || window.location.port;
var query = options.query || {};
var func = options.func || '';
var apiServer = 'api/' + func + '.php' +
(appFunc.isEmpty(query) ? '' : '?');
var name;
for (name in query) {
apiServer += name + '=' + query[name] + '&';
}
return apiServer.replace(/&$/gi, '');
},
simpleCall: function(options,callback){
options = options || {};
options.data = options.data ? options.data : '';
//If you access your server api ,please user `post` method.
//options.method = options.method || 'GET';
options.method = options.method || 'POST';
if(appFunc.isPhonegap()){
//Check network connection
var network = networkStatus.checkConnection();
if(network === 'NoNetwork'){
hiApp.alert(i18n.error.no_network,function(){
hiApp.hideIndicator();
hiApp.hidePreloader();
});
return false;
}
}
$$.ajax({
url: xhr.getRequestURL(options) ,
method: options.method,
data: options.data,
success:function(data){
data = data ? JSON.parse(data) : '';
var codes = [
{code:10000, message:'Your session is invalid, please login again',path:'/'},
{code:10001, message:'Unknown error,please login again',path:'tpl/login.html'},
{code:20001, message:'User name or password does not match',path:'/'}
];
var codeLevel = xhr.search(data.err_code,codes);
if(!codeLevel){
(typeof(callback) === 'function') ? callback(data) : '';
}else{
hiApp.alert(codeLevel.message,function(){
if(codeLevel.path !== '/')
mainView.loadPage(codeLevel.path);
hiApp.hideIndicator();
hiApp.hidePreloader();
});
}
}
});
}
};
return xhr;
});
I know the error is in the way contacts.php is displaying the JSON results or I need to change something in the js file.
Thanks for the help.
Based on your comments above I've tried to rewrite a solution keeping the same structure, but removing the unnecessary things; this is what the code may look like. Note that there are no references to err_code and err_msg peoperties, and the callback is called directly on data variable.
define(['utils/appFunc',
'i18n!nls/lang',
'components/networkStatus'],function(appFunc,i18n,networkStatus) {
//var apiServerHost = window.location.href;
var xhr = {
getRequestURL: function(options){
//var host = apiServerHost || window.location.host;
//var port = options.port || window.location.port;
var query = options.query || {};
var func = options.func || '';
var apiServer = 'api/' + func + '.php' +
(appFunc.isEmpty(query) ? '' : '?');
var name;
for (name in query) {
apiServer += name + '=' + query[name] + '&';
}
return apiServer.replace(/&$/gi, '');
},
simpleCall: function(options,callback){
options = options || {};
options.data = options.data ? options.data : '';
//If you access your server api ,please user `post` method.
//options.method = options.method || 'GET';
options.method = options.method || 'POST';
if(appFunc.isPhonegap()){
//Check network connection
var network = networkStatus.checkConnection();
if(network === 'NoNetwork'){
hiApp.alert(i18n.error.no_network,function(){
hiApp.hideIndicator();
hiApp.hidePreloader();
});
return false;
}
}
$$.ajax({
url: xhr.getRequestURL(options) ,
method: options.method,
data: options.data,
success:function(data){
data = data.length > 0 ? JSON.parse(data) : [];
if (typeof(callback) === 'function' && data !== undefined)
callback(data);
}
});
}
};
return xhr;
});
Then you may call it this way, using directly response var, which now contains the parsed data array:
loadContacts: function() {
if(VM.module('contactView').beforeLoadContacts()) {
xhr.simpleCall({
query: { callback: '?' },
func: 'contacts'
}, function (response) {
if (response !== undefined) {
VM.module('contactView').render({
contacts: response
});
}
});
}
}
Also, you would have to add
header('Content-Type: application/json');
before your PHP echo line in order to be able to parse it in JS.
Ok, many thanks Andrea, looks like there is something else that I'm missing because the results from the contacts.php and the initial contacts.php file is the same in my browser:
[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]
It works just fine if I use the initial contacts.php that only has pure json data like above, but if I switch to my api it stops working.
Also it stops working if I use this in the initial contacts.php:
<?php
$myString = '[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]';
echo $myString;
?>
I'll keep looking, but thanks to you I'm one step ahead.

PHP json_encode() function not properly read by jquery [duplicate]

This question already has answers here:
How to parse JSON data with jQuery / JavaScript?
(11 answers)
Closed 8 years ago.
I have the following problem,
I'm sending a json_encoded data array from PHP to javascript. The actual JSON I'm receiving from PHP is shown below,
{
"route": "1(M)A",
"startSignal": "AN1",
"startX": 100,
"startY": 320,
"direction": "down",
"endSignal": "AN3",
"endX": 1100,
"endY": 320,
"1AT": {
"length": "100",
"xStart": 100,
"yStart": 320,
"xFinish": 133.33333333333,
"yFinish": 320
},
"1BT": {
"length": "100",
"xStart": 133.33333333333,
"yStart": 320,
"xFinish": 166.66666666667,
"yFinish": 320
},
"1CT": {
"length": "100",
"xStart": 166.66666666667,
"yStart": 320,
"xFinish": 200,
"yFinish": 320
},
"1DT": {
"length": "100",
"xStart": 200,
"yStart": 320,
"xFinish": 233.33333333333,
"yFinish": 320
}
}
In my .JS file, I'm getting the "echo json_encode($dataArray)" as follows,
$.ajax({
url: "visualiser/visualiser_RouteList.php",
data: "JSON",
async: false,
success: function(data){
console.log(data);
}
});
The problem is that for some reason ajax reads the json in the following manner..(every character in JSON is stored as an array element.. so I can't retrieve a particular value of an associated name for example, getting "1(M)A" String value from associated name "route"..
data[0] = "{"
data[1] = " \" "
data[2] = "r"
data[3] = "o"
where am I going wrong?
============================================================================
further edit after receiving the comments,
Thanks everyone, I did change the data to 'dataType = "json"' but it still doesn't work..I really wanted to see [object, object....] when I do 'console.log(data) but nothing is printing out so there must be something wrong with my $array in the PHP source, not sure if anyone's willing do have look but I'm posting my php source here..(Sorry for being a total noob at PHP..I can't seem to be doing anything but pulling my hair out)
=============================================================================
<?php
// Route registration form processing php
// accepts a serialized data from myRoute.js
//header('Content-Type: application/json');
include_once ("dbConnect.php");
//$sql="SELECT * FROM route";
$routeStarts = "SELECT id, idSignal, km, line_name, direction, route.type
FROM route
JOIN signals
ON startSignal = idSignal";
$routeEnds = "SELECT id, idSignal, km, line_name, direction, route.type
FROM route
JOIN signals
ON endSignal = idSignal";
$routeTracks = "SELECT idRoute, signalName, routeTrack.idTrack, length, firstTrack, pointTrack, prevTrack
FROM routeTrack
JOIN track
ON routeTrack.idTrack = track.idTrack";
/*ORDER BY idRoute";*/
$pointTracks = "SELECT idRoute, routeTrack.idTrack, aLocation, bLocation, aLine, bLine, aTrack, bTrack, type
FROM routeTrack
JOIN points
ON routeTrack.idTrack = aTrack";
$sqlMax = "SELECT MAX(km) FROM signals";
$sqlMin = "SELECT MIN(km) FROM signals";
$max = mysqli_query($con, $sqlMax);
$min = mysqli_query($con, $sqlMin);
$start = mysqli_query($con, $routeStarts);
$rowMax = mysqli_fetch_array($max);
$rowMin = mysqli_fetch_array($min);
$range = $rowMax[0] - $rowMin[0];
// For each route picks up the start signal
while($row1 = mysqli_fetch_array($start)){
$resultArray = array();
$routeName = $row1['id'];
$startSig = $row1['idSignal'];
$startX = ((($row1['km'] - $rowMin[0]) / $range)*1000)+100;
$startY = getYcoordinate($row1['line_name']);
$direction = $row1['direction'];
$resultArray['route'] = $routeName;
$resultArray['startSignal'] = $startSig;
$resultArray['startX'] = $startX;
$resultArray['startY'] = $startY;
$resultArray['direction'] = $direction;
//picking up the end signal for the same route
$end = mysqli_query($con, $routeEnds);
while($row2 = mysqli_fetch_array($end)){
if ($row2['id'] == $routeName){
$endSignal = $row2['idSignal'];
$endX = ((($row2['km'] - $rowMin[0]) / $range)*1000)+100;
$endY = getYcoordinate($row2['line_name']);
$resultArray['endSignal'] = $endSignal;
$resultArray['endX'] = $endX;
$resultArray['endY'] = $endY;
}
}
//now filtering out the track for the particular route , non-point
if ($resultArray['startY'] == $resultArray['endY']){
$tracks = mysqli_query($con, $routeTracks);
while($row3 = mysqli_fetch_array($tracks)){
if ($row3['idRoute'] == $routeName && $row3['firstTrack'] == 1 ){
$xFinish = getXfinish($range, $row3['length']);
$resultArray[$row3['idTrack']] = ['length'=>$row3['length'],
'xStart'=>$startX,
'yStart'=>$startY,
'xFinish'=>$startX + $xFinish,
'yFinish'=>$startY ];
} else if ($row3['idRoute'] == $routeName && $row3['firstTrack'] != 1 ){
foreach ($resultArray as $key => $value) {
if ($row3['prevTrack'] == $key){
$prevXstart = $resultArray[$key]['xFinish'];
$prevYstart = $resultArray[$key]['yFinish'];
}
}
$xFinish = getXfinish($range, $row3['length']);
$resultArray[$row3['idTrack']] = ['length'=>$row3['length'],
'xStart'=>$prevXstart,
'yStart'=>$prevYstart,
'xFinish'=>$prevXstart + $xFinish,
'yFinish'=>$prevYstart
];
}
}
//now filtering out the track for plotting point tracks
} else {
$tracks = mysqli_query($con, $routeTracks);
while($row3 = mysqli_fetch_array($tracks)){
if ($row3['idRoute'] == $routeName && $row3['firstTrack'] == 1 && $row3['pointTrack'] != 1){
$xFinish = getXfinish($range, $row3['length']);
$resultArray[$row3['idTrack']] = ['length'=>$row3['length'],
'xStart'=>$startX,
'yStart'=>$startY,
'xFinish'=>$startX + $xFinish,
'yFinish'=>$startY ];
} else if ($row3['idRoute'] == $routeName && $row3['firstTrack'] != 1 && $row3['pointTrack'] != 1){
foreach ($resultArray as $key => $value) {
if ($row3['prevTrack'] == $key){
$prevXstart = $resultArray[$key]['xFinish'];
$prevYstart = $resultArray[$key]['yFinish'];
}
}
$xFinish = getXfinish($range, $row3['length']);
$resultArray[$row3['idTrack']] = ['length'=>$row3['length'],
'xStart'=>$prevXstart,
'yStart'=>$prevYstart,
'xFinish'=>$prevXstart + $xFinish,
'yFinish'=>$prevYstart
];
// first track and point track
} else if ($row3['idRoute'] == $routeName && $row3['firstTrack'] == 1 && $row3['pointTrack'] == 1){
$pointTrack = mysqli_query($con, $pointTracks);
// not first track and point track
} else if ($row3['idRoute'] == $routeName && $row3['firstTrack'] != 1 && $row3['pointTrack'] == 1){
foreach ($resultArray as $key => $value) {
if ($row3['prevTrack'] == $key){
$prevXstart = $resultArray[$key]['xFinish'];
$prevYstart = $resultArray[$key]['yFinish'];
}
}
$turnPoint = getXfinish($range, ($row3['length']/2));
$pointTrack = mysqli_query($con, $pointTracks);
while($row4 = mysqli_fetch_array($pointTrack)){
if ($row4['idTrack'] == $row3['idTrack']){
$yTurnEnd = getYcoordinate($row4['bLine']);
}
}
if ($row1['direction'] == 'down'){
$resultArray[$row3['idTrack']] = ['xStart'=>$prevXstart,
'yStart'=>$prevYstart,
'xTurnStart'=> $prevXstart + $turnPoint,
'yTurnStart'=> $prevYstart,
'xFinish' => $prevXstart + $turnPoint + 50,
'yFinish' => $yTurnEnd
];
} else {
$resultArray[$row3['idTrack']] = ['xStart'=>$prevXstart,
'yStart'=>$prevYstart,
'xTurnStart'=> $prevXstart - $turnPoint,
'yTurnStart'=> $prevYstart,
'xFinish' => $prevXstart - $turnPoint -50,
'yFinish' => $yTurnEnd
];
}
}
}
}
//print_r($resultArray);
//header('Content-Type: application/json');
echo json_encode($resultArray);
unset($resultArray);
}
function getYcoordinate($line_name){
if ($line_name == 'downSuburban'){
$y= (800/20) * 8; // down Suburban
} else if ($line_name == 'upSuburban'){
$y= (800/20) * 10; // up Suburban
} else if ($line_name =='downMain'){
$y= (800/20) * 12; // down Main
} else if ($line_name == 'upMain'){
$y= (800/20) * 14; // up Main
}
return $y;
}
function getXfinish($trackRange, $trackLength){
return ($trackLength/($trackRange*1000))*1000;
}
// $dataArray = array();
// $dataArray[] = array('idRoute'=>$row['id'], 'startSignal'=>$row['startSignal']);
mysqli_close($con);
?>
You need the dataType rather the data.
$.ajax({
url: "visualiser/visualiser_RouteList.php",
dataType: "JSON",
async: false,
success: function(data){
console.log(data);
}
});
Your response is not being recognised as JSON, so it is not being deserialised. Presently it is being received as a string, hence why accessing by index is giving you the character of the string at that position.
You either need to set the headers in the response in PHP to JSON, or force the jQuery to deserialise it for you using dataType: 'json':
$.ajax({
url: "visualiser/visualiser_RouteList.php",
dataType: 'json',
async: false,
success: function(data){
console.log(data);
}
});
Also, when the response is correctly deserialised to an object, you cannot access it using indexes. You need to use the keys, like this:
data.route; // = '1(M)A'
$.ajax({
url: "Url",
dataType: 'JSON',//'datatype the ajax function expects',
type: "post or get",//action type
data:data to be posted,
async: false,
success: function(data){
console.log(data);
}
});,
refer this for more http://api.jquery.com/jquery.ajax/
As explained in this question & answer thread here, instead of data use dataType and instead of uppercase JSON try using lowercase json:
$.ajax({
url: "visualiser/visualiser_RouteList.php",
dataType: "json",
async: false,
success: function(data){
console.log(data);
}
});

SyntaxError: Unexpected token l in ajax call

I am trying to fetch a data from the server data base and pass it to the ajax to create a database table and its data in the local android database. But when an ajax call is make it give following error.
LogCat:
01-30 10:58:45.888: D/CordovaLog(31914): Server is not responding... Please try again: SyntaxError: Unexpected token l
01-30 10:58:45.888: I/Web Console(31914): Server is not responding... Please try again: SyntaxError: Unexpected token l at file:///android_asset/www/home.html:513
here is the ajax code:
$.ajax({
url : urlServer + 'getTableData.php',
// type: 'POST',
contentType : 'application/json',
beforeSend : function() {
$.mobile.loading('show')
},
complete : function() {
console.log("ajax complete");
createTable();
},
dataType : 'json',
data : {userId: user_id},
success : function(data) {
if (data != null)
{
dynamic_tabledetails = data.Table_details;
dynamic_selectQuery = data.SelectTableQuery;
table_data = data;
getTabledetails(dynamic_tabledetails);
}
else
{
alert("Error Message");
}
},
error : function(xhr, ajaxOptions, thrownError) {
console.log("Server is not responding... Please try again: "+thrownError);
}
});
Here is the php code:
<?php
require_once ('connect.php');
$userID= $_REQUEST['userId'];
$data = array ();
$listtables = array();
$Tabledetails = array();
$select_table = '';
$tab_name = array();
$getlistTables = 'SHOW TABLES FROM sacpl_crm_dev ';
$resultsListTables = mysql_query($getlistTables);
echo 'length of the tables name: '.$resultsListTables.' ';
while ($row = mysql_fetch_array($resultsListTables))
{
if(strpos($row[0],'_trail') == false)
{
$temporarydata = array();
$TableName = new ArrayObject();
$getTabledetails = 'show columns from '.$row[0].'';
$resultdetails = mysql_query($getTabledetails);
$TableName['tablename'] = $row[0];
$tab_name[] =$row[0];
$column = array();
$delete_field = '';
$comp_codeField = '';
while($rows = mysql_fetch_array($resultdetails))
{
$column_list =new ArrayObject();
$column_list['FieldName'] = $rows['Field'];
$column_list['Default'] = $rows['Default'];
if(strpos($rows['Type'],'(') == false)
{
$column_list['dataType'] = $rows['Type'];
$column_list['dataType_limit'] ='';
}
else
{
$type = explode('(',$rows['Type']);
$column_list['dataType'] = $type[0];
$column_list['dataType_limit'] = '('.$type[1];
}
if($rows['Field'] == 'deleted')
{
$delete_field = 'deleted = 0';
}
if($rows['Field'] == 'userId')
{
$userIdField = $rows['Field'].'="'.$userId.'"';
}
$column_list['Extra'] = $rows['Extra'];
$column_list['Null_value'] = $rows['Null'];
$column_list['Key_value'] = $rows['Key'];
$column[] = $column_list;
}
$TableName['column_details'] = $column;
$Tabledetails[]=$TableName;
if($userIdField == '' && $delete_field !='')
{
$select_table = 'select * from '.$row[0].' where '.$delete_field.'';
}
else if($userIdField != '' && $delete_field =='')
{
$select_table = 'select * from '.$row[0].' where '.$userIdField.'';
}
else if($userIdField != '' && $delete_field !='')
{
$select_table = 'select * from '.$row[0].' where '.$userIdField.' and '.$delete_field.'';
}
else{
$select_table = 'select * from '.$row[0].'';
}
$select_query[] = $select_table;
$resultTableData = mysql_query($select_table);
while ($row1 = mysql_fetch_array($resultTableData))
{
$temporarydata[] = $row1;
}
$data[$row[0]] = $temporarydata;
}
}
$data['Table_details'] = $Tabledetails;
$data['SelectTableQuery'] = $select_query;
mysql_close($con);
require_once('JSON.php');
$json = new Services_JSON();
echo ($json->encode($data));
?>
Comment out the line:
echo 'length of the tables name: '.$resultsListTables.' ';
Also, when outputting JSON for an AJAX call, it's important to set the Content-type header using:
header('Content-type: application/json; charset=utf-8',true);
This php code doesn't seem to have syntax error. the problem probably lies on the included php's: "connect.php" and "JSON.php". could you please post them too so we can find the error.
Link this into the beginning of your PHP-file:
header("Content-Type: text/javascript; charset=utf-8");

Ajax it does nothing when sending parameters to a php page

I am a beginner using ajax and am trying to change the status of reading a book by clicking an image.
I had the code working but without ajax. Now I have no php error but not a change in mysql.
The code:
<script type="text/javascript">
function sendState(state_id){
var hd_haveread = $("#hd_haveread").val();
var hd_toread = $("#hd_toread").val();
var hd_reading = $("#hd_reading").val();
var val = 0;
var baseurl = "img/";
switch(state_id){
case 1:
if (hd_haveread == "0"){
document.getElementById('hd_haveread').value = "1";
document.getElementById('hd_toread').value = "0";
document.getElementById('hd_reading').value = "0";
val = 1;
}
else{
document.getElementById('hd_haveread').value = "0";
val = 0;
}
break;
case 3:
if (hd_toread == "0"){
document.getElementById('hd_toread').value = "1";
document.getElementById('hd_haveread').value = "0";
document.getElementById('hd_reading').value = "0";
val = 1;
}
else{
document.getElementById('hd_toread').value = "0";
val = 0;
}
break;
case 2:
if (hd_reading == "0"){
document.getElementById('hd_reading').value = "1";
document.getElementById('hd_haveread').value = "0";
document.getElementById('hd_toread').value = "0";
val = 1;
}
else{
document.getElementById('hd_reading').value = "0";
val = 0;
}
break;
}
var parameters = {
"book" : <?php echo $id_book; ?>,
"state" : state_id,
"val" : val
};
$.ajax({
cache: false,
data: parameters,
url: 'change_state_ajax.php',
type: 'post',
dataType: "html",
beforeSend: function (){
},
success: function (response){
switch(state_id){
case 1:
if (hd_haveread == "0"){
$("#img_haveread1").css("display","none");
$("#img_haveread2").css("display","inline-block");
$("#img_toread1").css("display","inline-block");
$("#img_toread2").css("display","none");
$("#img_reading1").css("display","inline-block");
$("#img_reading2").css("display","none");
}
else{
$("#img_haveread1").css("display","inline-block");
$("#img_haveread2").css("display","none");
}
break;
case 3:
if (hd_toread == "0"){
$("#img_haveread1").css("display","inline-block");
$("#img_haveread2").css("display","none");
$("#img_toread1").css("display","none");
$("#img_toread2").css("display","inline-block");
$("#img_reading1").css("display","inline-block");
$("#img_reading2").css("display","none");
}
else{
$("#img_toread1").css("display","inline-block");
$("#img_toread2").css("display","none");
}
break;
case 2:
if (hd_reading == "0"){
$("#img_haveread1").css("display","inline-block");
$("#img_haveread2").css("display","none");
$("#img_toread1").css("display","inline-block");
$("#img_toread2").css("display","none");
$("#img_reading1").css("display","none");
$("#img_reading2").css("display","inline-block");
}
else{
$("#img_reading1").css("display","inline-block");
$("#img_reading2").css("display","none");
}
break;
}
}
});
}
</script>
And the change_state_ajax.php code:
<?php
if(isset($_POST['book']) && isset($_POST['state']) && isset($_POST['val'])){
include 'connection.php';
include('php_lib/config.ini.php');
include_once('php_lib/login.lib.php');
$lib_id = $_POST['book'];
$state = $_POST['state'];
$val = $_POST['val'];
$result=changeState($lib_id, $state, $val);
echo $result;
}
function changeState($lib_id, $state, $val){
session_start();
$usu_id = $_SESSION['USSER']['id'];
$mark = 0;
$pos = 0;
$query = $pdo->prepare('SELECT uliusu_id, ulilib_id, uliedl_id FROM '.TABLE_USSERS_BOOKS.' WHERE ulilib_id = :fil_lib_id AND uliusu_id = :fil_usu_id');
$query->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$query->execute();
while($row = $query->fetch(PDO::FETCH_OBJ)){
$mark = 1;
$state_actual = $row->uliedl_id;
}
if($mark == 0){
$query = $pdo->prepare('INSERT INTO '.TABLE_USSERS_BOOKS.' (uliusu_id, ulilib_id, uliedl_id, uli_posicion, uli_fecha) VALUES (:fil_usu_id, :fil_lib_id, :fil_edl_id, :fil_pos, NOW())');
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$query->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->bindParam(':fil_edl_id', $state, PDO::PARAM_INT);
$query->bindParam(':fil_pos', $pos, PDO::PARAM_INT);
$query->execute();
}else{
if($state == $state_actual){
$query = $pdo->prepare('DELETE FROM '.TABLE_USSERS_BOOKS.' WHERE ulilib_id = :fil_lib_id AND uliusu_id = :fil_usu_id');
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$queryquery->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->execute();
}else{
$query = $pdo->prepare('UPDATE '.TABLE_USSERS_BOOKS.' SET uliedl_id = :fil_edl_id WHERE ulilib_id = :fil_lib_id AND uliusu_id = :fil_usu_id');
$query->bindParam(':fil_edl_id', $state, PDO::PARAM_INT);
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$query->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->execute();
}
}
if($state == 1){
$result = 0;
}else{
$result = 1;
}
return $result;
}
?>
Can anyone help me solve this?
Thanks.
You are not checking for the proper variables. Your JavaScript passes a var called estado but you check in PHP for a var called state.
And because you require all three variables to be set your condition fails.
Also like Hank said in his comment your jQuery.Ajax call uses POST (type: 'post',) but then in your PHP script you check GET variables which of course are not set.
Either change you jQuery call type to GET or change the checking in your PHP script to POST
if(isset($_POST['book']) && isset($_POST['state']) && isset($_POST['val'])){
include 'connection.php';
include('php_lib/config.ini.php');
include_once('php_lib/login.lib.php');
$lib_id = $_POST['book'];
$state = $_POST['state'];
$val = $_POST['val'];
$result=changeState($lib_id, $state, $val);
echo $result;
}
Things I noticed:
1) First you are POSTing but in PHP, you are using $_GET.
2) you are passing "book", "estado", "val" but are trying to get "book", "state", "val", so it never enters into if condition

Categories

Resources