SyntaxError: Unexpected token l in ajax call - javascript

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

Related

WordPress callback function is called twice

i have been developing a WordPress plugin that has a form that sends some data to a Database.
My problem is that every time i click the submit button the callback runs twice, and the information that appears in my database is duplicated.
My jQuery code is:
$("#submit_btn").click( function (event) {
event.preventDefault();
let uuid = uuidv4()
let form_serialize = $("form").serializeArray();
let dataForm = {
"id": uuid,
'submitId': uuid
}
$.each(form_serialize, function (i, field) {
dataForm[field.name] = field.value
});
$.ajax({
url: ccandidates.ajax_url,
type: "POST",
crossDomain: true,
cache: false,
data: {
security: candidates.ajax_nonce,
action: 'SendToFormApi',
data: dataForm
},
dataType: 'json',
success: function (data, status, xhttp) {
// event.preventDefault();
if (data === true) {
window.location = candidates.merci_page_url;
} else {
window.location.href = candidates.error_page_url;
$("form").trigger('reset')
}
},
}
);
});
Callback function
function SendToFormApi_callback()
{
$formRandyValues = $_POST['data'];
$virtualagencyApiEmail = new virtualagencyApiEmail();
$result = $virtualagencyApiEmail->NyFormApi($formRandyValues);
$response = $virtualagencyApiEmail->NyFormApiCall($result,$formMyValues['id']);
$code = wp_remote_retrieve_response_code($response);
// if code 503 == service unavailable
// if code 401 == auth fail
// if code 400 == object fail
// if code 201 == success response
if ($code === 201) {
echo json_encode(true);
wp_die();
} else {
echo json_encode(false);
wp_die();
}
}
add_action('wp_ajax_SendToFormApi', 'SendToFormApi_callback', 1);
add_action('wp_ajax_nopriv_SendToFormApi', 'SendToFormApi_callback', 1);
public function NyFormApi($params): array
{
$uuidId = $params['id'] ?? $this->getUid();
$position_criteria_object = new Position_Criteria();
$position_criteria_object->type = 'string';
$position_criteria_object->label = 'besoin';
$position_criteria_object->question = 'votre_besoin';
$position_criteria_object->answer = $params['votreBesoin'];
$position_criteria_object->value = $params['votreBesoin'];
$origin_object = new Position_Criteria();
$origin_object->type = 'string';
$origin_object->label = 'origin';
$origin_object->question = 'candidature_oringin';
$origin_object->answer = 'My form';
$origin_object->value = 'My form';
$secteur_object = new Position_Criteria();
$secteur_object->type = 'string';
$secteur_object->label = 'secteur';
$secteur_object->question = 'secteur';
$secteur_object->answer = $params['secteur'];
$secteur_object->value = $params['secteur'];
$region_object = new Position_Criteria();
$region_object->type = 'string';
$region_object->label = 'region';
$region_object->question = 'region';
$region_object->answer = $params['region'];
$region_object->value = $params['region'];
$metier_object = new Position_Criteria();
$metier_object->type = 'string';
$metier_object->label = 'metier';
$metier_object->question = 'metier';
$metier_object->answer = $params['metier'];
$metier_object->value = $params['metier'];
$talent_object = new Talent();
$talent_object->id = $uuidId;
$talent_object->firstName = $params['firstName'];
$talent_object->lastName = $params['lastName'];
$talent_object->email = $params['email'];
$talent_object->phone = $params['phone'];
if(empty($params['qualificationCode'])){
$qualificationCode = "none";
} else {
$qualificationCode = $params['qualificationCode'];
}
return array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode($this->keyEncoded)
),
'body' => array(
'id' => $uuidId, //$params['id'], // str
'workTeamId' => $params['postClient'], // str
'priority' => 1, // int
'positionCriteria' => array(
$position_criteria_object,
$origin_object,
$secteur_object,
$region_object,
$metier_object
), // [{...},{...},...]
'occupationCode' => $qualificationCode, // str,
'occupationLabel' => $params['qualification'], // str
'talent' => $talent_object, // { key = value, ... }
)
);
}
public function MyFormApiCall($params, $id)
{
$url = $this->apiPathRandy . "/" . $id;
return wp_remote_post($url, $params);
}
// Get an RFC-4122 compliant globaly unique identifier
private function getUid(): string
{
$data = PHP_MAJOR_VERSION < 7 ? openssl_random_pseudo_bytes(16) : random_bytes(16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // Set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // Set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
After reading and trying some solutions that i found, no of them work in my case.
Thank you for your help.
(note: there are some vars names that were changed for privacy)
I would remove all javascript from the form and do
if ($code === 201) {
header("location: merci.html");
wp_die();
} else {
header("location: erreur.html");
wp_die();
}

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

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.

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

Jquery ajax function fails with no reason

I have a web based mobile android application. I built it with php + jquery + mysql. An ajax code fails but no reason. Therefore it returns 'Try again'. Unfortunately I can not debug it in the application. Here is the code:
$('.get-order-button').live('click', function() {
var musteritel = $('#musteritel').val(), musteriad = $('#musteriad').val(), musteriadres = $('#musteriadres').val(), musterinotu = $('#siparisnotu').val(), odemesekli =$('#odemesekli option:selected').val() ;
if(musteritel != ''){
$.ajax({
type : 'POST',
url : '/enfes/temp-order-sent.php', timeout: 10000,
cache : false,
data : 'musteritel='+musteritel+'&musteriadres='+musteriadres+'&musterinotu='+musterinotu+'&odemesekli='+odemesekli+'&musteriad='+musteriad,
dataType : 'json',
beforeSend : function() {
showDialog('Yükleniyor...')
},
whileLoading: function(xhr) {
if (xhr && xhr.readyState != 4)
xhr.abort()
}
}).always(function() {
closeDialog()
}).fail(function() {
showToastShort('Try again.');
}).done(function(r) {
if(r.s==1){
$.each(r.u, function( index, value ) {
unsetMyCookie(index);
});
$('#detail').remove();
$('.basket-added-btn span').text('0');
basketStatus = 0;
showToastLong(r.m);
window.location.hash = 'home';
}else
showToastShort(r.m);
});
}
return false
});
And here is the php code:
<?php
session_start();
include_once 'class.render.php';
include_once 'class.order.php';
$kendim = new render();
if(isset($_SESSION["id"]) && isset($_POST['musteritel'])) {
$kendiId = $_SESSION["kendiId"];
$uniqueIdentifier = $_SESSION["uniqueIdentifier"];
if(isset($_COOKIE)){
$order = new order();
$musteritel = $order->validTel($_POST['musteritel']);
$musteriad = $order->cleanStr($_POST['musteriad']);
$musteriadres = $order->cleanStr($_POST['musteriadres']);
$musterinotu = $order->cleanStr($_POST['musterinotu']);
$odemesekli = $order->cleanStr($_POST['odemesekli']);
$return = array('s' => 0, 'm' => 'Siparis gonderilemedi. Bilgilerinizi kontrol ediniz.');
$ordersent = $order->addOrder($musteritel, $musteriad, $musteriadres, $musterinotu, $odemesekli);
if($musteritel == "") {
$return = array('s' => 1, 'm' => 'Telefon numaranızı hatalı girdiniz.');
} else {
if($ordersent){
$return = array('s' => 1, 'm' => 'Siparisiniz bize ulasmistir.', 'u' => $order->basket);
}else
$return = array('s' => 0, 'm' => 'Siparis gonderilemedi. Bilgilerinizi kontrol ediniz.');
}
}else
$return = array('s' => 0, 'm' => 'Siparis sepetiniz bos.');
}else
$return = array('s' => 0, 'm' => 'Telefon numaranızı yazmalisiniz.');
echo json_encode($return);
?>
Why does it fail?

Categories

Resources