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

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);
}
});

Related

display data js from datebase sql [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I would like to push my value of textbox to sql and then display it.
I read a lot topics but still nothing. I have always problem to explain my problems but I hope u will see what i want to do escpecialy when u look at db2.php
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
nw = newMessage;
$.ajax({
type: "POST",
url: "db2.php",
data: {'name': nw },
success: function (json) {
jss = json.PYT;
oss = json.ODP;
console.log(jss);
}
});
$("#textbox").val("");
var prevState = $("#container").html();
if( prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
ai(newMessage);
});
and my db2.php .
<?php
header('Content-type: application/json');
include 'connect.php';
if (isset($_POST['name'])) {
$name = $_POST['name'];
$queryResult = $connect->query("select * from Chatbot where '$name' LIKE
CONCAT('%',PYT,'%')");
$result = array();
while($pomoc = $queryResult->fetch_assoc()){
$result[] = $pomoc;
}
}
echo json_encode($result);
Now my result is {}, echo is null.
console.log(nw)
VM289:1 dsasa
undefined
I know how to get just output from ajax but if i want to push this data everything goes wrong. Best regards
UPDATE. Now I would like to get jss value out of this function to the other one.
var jss = {}; //(first line code)
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
nw = newMessage;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
}
});
UPDATE 2
var jss2 = {};
var nw;
$(function(){
username();
$("#textbox").keypress(function(event){
if ( event.which == 13) {
if ( $("#enter").prop("checked") ){
$("#send").click();
event.preventDefault();
}
}
});
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
$("#textbox").val("");
var prevState = $("#container").html();
if( prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
ai(newMessage);
});
})
function send_message(message){
var prevState = $("#container").html();
if(prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + "<span class = 'bot'>Chatbot: </span>" + message);
}
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hi!");
}
function myFunction() {
var x = document.getElementById("textbox").value;
}
function ai(message){
var jss;
message = message.toLowerCase();
nw = message;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
}
});
console.log(jss);
if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
send_message(Answer);
return;
}
else{
send_message("Nope ");
}
}
I think this is what you need to do with your function so that you can use the jss variable properly, once the ajax request has completed:
function ai(message){
var jss;
message = message.toLowerCase();
nw = message;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
console.log(jss);
if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
send_message(Answer);
return;
}
else{
send_message("Nope ");
}
}
});
}
Any code which relies on the jss variable must not be executed until after the ajax call has completed. Since ajax calls run asynchronously, the only way to guarantee this is for that code to be included in (or triggered from) the "success" callback function in your ajax request.

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.

insert browsers geoposition into mysql table with php?

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
}

Array not acting as expected in jQuery

I'm doing jQuery Ajax with PHP, and after jQuery passes some $_POST data to PHP, PHP validates those data, and prepares an array with all the errors, and once all validation is done, the count of error is found, and if it is greater than 0, the array is encoded in json and it is printed on the screen. jQuery then grabs those data with 'success:' and it does it, but it doesn't act as expected.
PHP file validating:
<?php
$messages = array();
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['message'])) {
if(empty($_POST['name'])) {
$messages[] = "Please fill in the Name field.";
}
if(empty($_POST['email'])) {
$messages[] = "Please fill in the Email field.";
}
if(empty($_POST['subject'])) {
$messages[] = "Please fill in the Subject field.";
}
if(empty($POST['message'])) {
$messages[] = "Please write your message in the Message field!";
}
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$messages[] = "Invalid email entered!";
}
if(strlen($_POST['name']) > 30 || strlen($_POST['name']) < 3) {
$messages[] = "Your name cannot be less than 3 characters or more than 30 characters.";
}
if(strlen($_POST['email']) > 30 || strlen($_POST['email']) < 3) {
$messages[] = "Your email cannot be less than 3 characters or more than 30 characters.";
}
if(strlen($_POST['subject']) > 30 || strlen($_POST['subject']) < 3) {
$messages[] = "The subject cannot be less than 3 characters or more than 30 characters.";
}
if(strlen($_POST['message']) > 2000 || strlen($_POST['message']) < 40) {
$messages[] = "Your message cannot be less than 40 characters or more than 2000 characters.";
}
if(count($messages) > 0) {
$messages['elements'] = count($messages);
echo json_encode($messages);
} else {
}
}
jQuery code:
$(document).ready( function() {
$(document).on('click', '.contact_submit', function() {
var name = $('input#name').val();
var email = $('input#email').val();
var subject = $('input#subject').val();
var message = $('input#message').val();
var Data = "name=" + name + "&email=" + email + "&subject=" + subject + "&message=" + message;
$.ajax({
type: "POST",
url: "portal/_inc/frontend/form.php",
data: Data,
success: function(messages) {
var Count = messages.length;
$('.messages').empty();
for(var i = 0; i < Count; i++) {
$('.messages').append('<li class"error">' + messages[i] + '</li>\n');
}
}
});
return false;
});
});
All works fine, but my output is in 'char' format like one character at a time. Click here for a screen shot.
It's because your response is a string, and you're iterating over a string.
This PHP code:
echo json_encode($messages);
encodes an object/array into a JSON string.
And this JS code:
var Count = messages.length;
will just return the length of the whole string, not the number of individual objects within the returned JSON.
The simplest way to fix it is to parse the JSON in your success callback:
var messageObject = JSON.parse(messages);
and now the variable messageObject will have the data in the format you expected.
Add dataType:'JSON' to your ajax request:
$.ajax({
dataType:'JSON',
type: "POST",
url: "portal/_inc/frontend/form.php",
data: Data,
.....
and add
header('Content-type: application/json; charset=utf-8');
to your php so that the javascript knows how to handle the response
EDIT
the problem is that the json response is an object, not array, which does not have a .length property.
you'd be better to do it like this:
success: function(messages) {
$('.messages').empty();
$.each(messages,function(){
$('.messages').append('<li class"error">' + this + '</li>\n');
});
}

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");

Categories

Resources