what can I do to prevent xss code? - javascript

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.

Related

cant get concat values and php not working

So my problem is that why jquery concat is not working and also it is not posting and can't inserted into the database
I tried changing the code and read references still cant get enough
This is my jquery
var uid = $('#lname').val() + $('fname').val() + $('#datecreated').val(moment().format('YYYY'));
var datecreated = $('#datecreated').val(moment().format('YYYY'));
var fname = $('#fname').val();
var lname = $('#lname').val();
var email = $('#email').val();
var password = $('#pass').val();
var passcheck = false;
This is my ajax
if (uid && fname && lname && email && password && datecreated)
{
var form = $(this);
var formData = new FormData(this);
$(".formcontent").hide();
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success:function(response)
{
this is my full code php, I dunno if the problem is with xampp or not. Im tackling this problem for 3 day straight now and I dunno where the problem is
valid['success'] = array('success' => true, 'messages' => array());
$uid = $_POST ['uid'];
$pass = $_POST['pass'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$datecreated = $_POST['datecreated'];
if ($_POST)
{
if(true)
{
$sqlmail = "SELECT * FROM acc WHERE (email = '$email') AND acc_stat < 3";
$resmail = $connect->query($sqlmail);
if($resmail->num_rows > 0)
{
while($row = $resmail->fetch_array())
{
if($email === $row['email'])
{
$valid['messages'] = "Email address is already taken";
}
}
$valid['success'] = false;
$connect->close();
echo json_encode($valid);
}
else
{
$sql = "INSERT INTO 'acc' ('uid', 'password', 'lname', 'fname', 'email', 'acc_type', 'acc_stat','date_create') VALUES ('$uid', '$pass', '$fname', '$lname', '$email', '3', '1','$datecreated')";
if($connect->query($sql) === TRUE)
{
$valid['success'] = true;
$valid['messages'] = "Account registration successful.";
$connect->close();
echo json_encode($valid);
}
else
{
$valid['success'] = false;
$valid['messages'] = "Network connection not stable. Please try again later.";
$connect->close();
echo json_encode($valid);
}
}
}
else
{
$valid['success'] = false;
$valid['messages'] = "No internet connection.";
$connect->close();
echo json_encode($valid);
}
}
There is a small mistake in your code, please fix it and it should work fine. the error is at line
var uid = $('#lname').val() + $('fname').val() + $('#datecreated').val(moment().format('YYYY'));
chage it to var uid = $('#lname').val() + $('#fname').val() + $('#datecreated').val(moment().format('YYYY'));.
silly mistake of missing just #. one more thing, you will not receive the uid paramter in php side, just because you are not sending it with form. append it to FormData as give,
var uid = $('#lname').val() + $('#fname').val() + $('#datecreated').val(moment().format('YYYY'));.
var formData = new FormData(this);
formData.append('uid' , uid);
Now you will be able to recieve that uid parameter.
Try to use this:
var uid = $('#lname').val() + $('#fname').val() + $('#datecreated').val(moment().format('YYYY'));
var datecreated = $('#datecreated').val(moment().format('YYYY'));
var fname = $('#fname').val();
var lname = $('#lname').val();
var email = $('#email').val();
var password = $('#pass').val();
var passcheck = false;

How do I submit form without page reload taking into consideration the php script?

So basically I have to work on this loan calculator loancalc.000webhostapp.com
I have looked at other pages on this site "how to submit form without page reload?" but this isn't completely relevant to what i'm working on. So far i've added this into the jquery part of the page...
jQuery('qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else{
}
if (email == ""){
$("input#youremail").focus;
return false;
}
});
But i'm told there is also two other scripts that I need to work with, I'm not really too experienced with php so not sure what's going on, the two php scripts I have to work with are called quick-interest-slider.php and register.php,
//qis_verify_application in register.php
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
//qis_process_application in register.php
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
function qis_loop in quick-interest-slider.php
function qis_loop($atts) {
$qppkey = get_option('qpp_key');
if (!$qppkey['authorised']) {
$atts['formheader'] = $atts['loanlabel'] = $atts['termlabel'] = $atts['application'] = $atts['applynow'] = $atts['interestslider'] = $atts['intereselector']= $atts['usecurrencies'] = $atts['usefx'] = $atts['usedownpayment'] = false;
if ($atts['interesttype'] == 'amortization' || $atts['interesttype'] == 'amortisation') $atts['interesttype'] = 'compound';
}
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
Do I have to edit any of the php and I also don't know what I have to write considering the php.
You can use what is called Ajax to submit the data to the server via POST.
Create a button and give it a class of qis-register, then give each of your input fields a class that matches it's name. Then just add that field to the data object that I have following the format within it.
jQuery(document).on('click', '.qis-register', function(){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "your_php_here.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});

Value not found in php

For login i'm passing mail id and password from javascript file and i've checked through console.log that the values are printed. But when i echo both values in php only password is showed not the mail. But i can't find any error.Here i'm pasting the php file.
<?php
require_once('DBconnection.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
$datamail = $_GET["mailID"];
$datapass = $_GET["psw"];
//$datamail = isset($_GET["mailID"]) ? $_GET["mailID"] : '';
echo $datamail;
echo $datapass;
$login_query = "SELECT * FROM student_table where mail_id = '$datamail' AND password='$datapass'";
//echo $login_query;
$login_res = $db->query($login_query);
if( $login_res->num_rows == 1 ){
//if( $login_res == true ){
echo "success";
}
else {
//echo $login_res;
echo mysqli_error($db);
exit;
}
$db->close();
?>
Javascrit file Here
function globalLogin() {
checkLogInMail();
//pageEntry();
}
function checkLogInMail() {
var mailET = document.getElementById("mailID");
var mailIdError = document.getElementById("mailIdErr");
mailID = mailET.value;
var regex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if (!regex.test(mailID)) {
mailIdError.innerHTML = "Enter a valid Email id";
//loginFlag = 1;
}
else{
checkmailPass();
}
}
function checkmailPass() {
var passET = document.getElementById("psw");
var passError = document.getElementById("pswErr");
psw = passET.value;
console.log(mailID);
console.log(psw);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
alert(response);
if(!response.localeCompare( "success" )){
document.getElementById("loginErr").innerHTML = "Mail or Password is correct";
//alert("Successfully logged in :)");
//window.location.href = "index.html";
}
else{
document.getElementById("loginErr").innerHTML = response;
}
}
}
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID"+mailID, true);
xhttp.send();
}
you miss = in your get request in mailID
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID="+mailID, true);
You missed an equal sign '=' in your javascript at your mailid parameter.

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

Categories

Resources