Uncaught SyntaxError: Unexpected token (, no error visible - javascript

I am writing an AJAX function, but it looks like there is an error. I can't seem to find any. Please help! I have browsed these questions: this, this, and this but none of it is working. Here is my code:
function registerDevice(fp,uid)
{
$.ajax({
type: "POST",
async: true,
url: "backend.php",
data: {"fp": fp, "uid" : uid},
success: function(output) {
var json = eval('(' + output + ')');
var status = json['status'];
if(status == "success")
{
//redirect user.
setTimeout(function(){
//do what you need here
<?php
if(isset($_GET['goto']))
{
echo 'window.location.replace("'.$_GET["goto"].'");';
}
else
{
echo 'window.location.replace("index.php");';
}
?>
}, 2000);
}
else
{
$("#login-msg").text("Something went wrong. Please try again.");
$("#login-alert").fadeTo(4000, 500).slideUp(500, function(){
$("#login-alert").hide();
});
}
},
error: function(error) {
$("#login-msg").text("There was an unknown error.");
$("#login-alert").fadeTo(4000, 500).slideUp(500, function(){
$("#login-alert").hide();
});
}
});
}
and it is called like this:
$('body').on("click", "#mybtn", function (e) {
registerDevice(result,uid);
});
Here is the error I get in Google Chrome:
VM411:1 Uncaught SyntaxError: Unexpected token )
success # login_alpha.php:344
j # jquery.js:3148
fireWith # jquery.js:3260
x # jquery.js:9314
b # jquery.js:9718
P.S: line 344 refers to this line:
var json = eval('(' + output + ')');
Edit 1: backend.php
<?php
$uid = $_POST['uid'];
$fp = $_POST['fp'];
//my code here.
$response_array['status'] = "success";
$response_array['type'] = "cookie";
?>

eval function needs a string to evaluate. You are trying to eval a JSON Object I think.
Try:
var json = eval('(' + JSON.stringify(output) + ')');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

I found the solution, and it was very silly.
The backend.php was NOT giving a JSON response!
This was the original code:
<?php
$uid = $_POST['uid'];
$fp = $_POST['fp'];
//my code here.
$response_array['status'] = "success";
$response_array['type'] = "cookie";
?>
I just added this line:
echo json_encode($response_array);
This made sure I was sending back a JSON response to the AJAX call's success function! What a stupid error.
Final edit for backend.php:
<?php
$uid = $_POST['uid'];
$fp = $_POST['fp'];
//my code here.
$response_array['status'] = "success";
$response_array['type'] = "cookie";
//print json response
echo json_encode($response_array);
?>

Related

Showing data and posted values separately in ajax post

i have a task which is about ajax post data and also ask the script to show data...I have 3 files.. HTML file perform an ajax to the php script, passwrapper.php and then include the another script to show all data in the json format on the console.log in the html file.. I implemented some ajax post values such as 'Abdullahlahlahlah' and 'Muslim' so that the passwrapper.php will receive those data and echo on the console separatley from the whole data... Developer said ajax cannot echo 2 times...... Is it totally impossible???? If there is no way, please tell me other options...
Requirement: Please do not modify the student.php as i want the that php script to echo all the data in json..
Modify the paswrapper.php and html file..
When i run the html file, the error states
Status Code: 200
ErrorThrown: SyntaxError: Unexpected token < in JSON at position 1634
jqXHR.responseText:
[{"student_id":"1","student_name":"Ashfur","student_gender":"F","student_age":"19","student_religion":"Muslim","student_course_id":"1"},{"student_id":"2","student_name":"Irfan","student_gender":"M","student_age":"17","student_religion":"Islam","student_course_id":"4"},{"student_id":"3","student_name":"Alice","student_gender":"F","student_age":"21","student_religion":"Chinese","student_course_id":"2"},{"student_id":"4","student_name":"Mohit","student_gender":"M","student_age":"20","student_religion":"Christian","student_course_id":"6"},{"student_id":"5","student_name":"Susy","student_gender":"F","student_age":"27","student_religion":"Chirstian","student_course_id":"5"},{"student_id":"6","student_name":"Ida","student_gender":"F","student_age":"23","student_religion":"Islam","student_course_id":"3"},{"student_id":"7","student_name":"Abdul","student_gender":"M","student_age":"22","student_religion":"Islam","student_course_id":"1"},{"student_id":"8","student_name":"Ernest","student_gender":"M","student_age":"25","student_religion":"Chinese","student_course_id":"4"},{"student_id":"9","student_name":"Wei Ling","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"10","student_name":"Ashtae","student_gender":"M","student_age":"23","student_religion":"Islam","student_course_id":"4"},{"student_id":"11","student_name":"Jasmine","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"65656","student_name":"yyyyty","student_gender":"F","student_age":"65","student_religion":"anything","student_course_id":"009090"}]
Also there is the posted values on the console.log which states LastRowname = Abdullahlahlahlah LastRowReligion = Muslim
HTML File
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="results"</div>
<div id="resulte"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "passwrapper.php",
dataType: "json",
data: {
lastName: 'Abdullahlahlahlah',
lastReligion: 'Muslim',
},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p><p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
};
</script>
</body>
</html>
passwrapper.php
<?php
include 'student.php';
executePass();
receivePost();
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
echo '<script>console.log("LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'");</script>';
}
}
?>
student.php
<?php
function executePass()
{
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
}
?>
in my network tab
[{"student_id":"1","student_name":"Ashfur","student_gender":"F","student_age":"19","student_religion":"Muslim","student_course_id":"1"},{"student_id":"2","student_name":"Irfan","student_gender":"M","student_age":"17","student_religion":"Islam","student_course_id":"4"},{"student_id":"3","student_name":"Alice","student_gender":"F","student_age":"21","student_religion":"Chinese","student_course_id":"2"},{"student_id":"4","student_name":"Mohit","student_gender":"M","student_age":"20","student_religion":"Christian","student_course_id":"6"},{"student_id":"5","student_name":"Susy","student_gender":"F","student_age":"27","student_religion":"Chirstian","student_course_id":"5"},{"student_id":"6","student_name":"Ida","student_gender":"F","student_age":"23","student_religion":"Islam","student_course_id":"3"},{"student_id":"7","student_name":"Abdul","student_gender":"M","student_age":"22","student_religion":"Islam","student_course_id":"1"},{"student_id":"8","student_name":"Ernest","student_gender":"M","student_age":"25","student_religion":"Chinese","student_course_id":"4"},{"student_id":"9","student_name":"Wei Ling","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"10","student_name":"Ashtae","student_gender":"M","student_age":"23","student_religion":"Islam","student_course_id":"4"},{"student_id":"11","student_name":"Jasmine","student_gender":"F","student_age":"23","student_religion":"Chinese","student_course_id":"2"},{"student_id":"65656","student_name":"yyyyty","student_gender":"F","student_age":"65","student_religion":"anything","student_course_id":"009090"}]<script>console.log("LastRowname = Abdullahlahlahlah LastRowReligion = Muslim");</script>
my requirement:
i want to echo all the data(except the posted values) on the html file.
i want to show the posted values on the console.log. it can either be in the passwrapper.php or html file..... Please help me....
ajax cannot echo 2 times;
1.student.php
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
//echo json_encode($json_array);
return $json_array;
2.passwrapper.php
<?php
include 'student.php';
$data['student_arr']=executePass();
$data['post_str']=receivePost();
echo json_encode($data);
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
$post_str= 'LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'';
return $post_str;
}
}
?>
3.html file
success: function(data){
console.log(data.post_str);
$('#results').text(JSON.stringify(data.student_arr));
},
passwapper.php
<?php
include 'student.php';
ob_start();
executePass();
$string = ob_get_contents();
ob_end_clean();
$data['student_arr']=json_decode($string);
$data['post_str']=receivePost();
echo json_encode($data);
function receivePost()
{
if ((!isset($_POST["lastName"])) and (!isset($_POST["lastReligion"])))
{
//do nothing
}
else
{
$post_str= 'LastRowname = '.$_POST["lastName"].' LastRowReligion = '.$_POST["lastReligion"].'';
return $post_str;
}
}
?>

GetJSON not working with PHP file

I am trying to use the getJSON function with a PHP file that echo some JSON. If I save the JSON expected from the PHP file as a JSON file, it works perfect but if I use the PHP file as URL it doesn't work because it fails when parsing the PHP at line 1 column 1.
PHP file:
<?php
$jsondata = array();
if( isset($_GET['param']) ) {
if( $_GET['param'] == 'valor' ) {
$jsondata['success'] = true;
$jsondata['message'] = 'Correct.';
} else {
$jsondata['success'] = false;
$jsondata['message'] = 'Incorrect.';
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsondata);
exit();
}
?>
And this is what I am using in the Javascript file:
$.getJSON('test.php', {format: "json"}, function(data) {
window.alert("Loaded");
}).fail( function(data, textStatus, error) {
console.error("getJSON failed, status: " + textStatus + ", error: "+error)
});
If I change from test.php to test.json it works.
EDIT: I was using mysql instead of mysqli and the server outputted a table and then my JSON and thats why I had the JSON Error parse ...
Fixed just changing from mysql to mysqli.
Thanks everyone.
Try this:
if( $_GET['param'] == 'valor' ) {
$row = array('success'=> true,'message'=>'Correct');
array_push($jsondata,$row);
} else {
$row = array('success'=> false,'message'=>'Incorrect');
array_push($jsondata,$row);
}
And the echo remains the same:
echo json_encode($jsondata);
I've coded like this when I had to work with JSON and PHP with JQuery.I hope it works for you too.

AJAX and HTML element not working

I am trying to set a div tag to display a message if user isn't found in the database.
This is the line I can't get to work:
$("message").html(msg);
If you could help me understand what I'm doing wrong it would help. Thanks
$(document).ready(function(){
$("#submit").click(function(){
var username = $("#username").val();
var code = $("#code").val();
var msg = "Who are you?!";
var dataString = 'username='+ username + '&code='+ code;
localStorage.setItem("number",code);
if(username==''||code=='')
{
alert("Um..you are missing something...");
}
else
{
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
cache: false,
success: function(result){
if(result != 0)
alert(result);
},
error: function(){
$("message").html(msg);
}
});
}
return false;
});
});
My PHP code
<?php
$username = trim($_POST["username"]);
$code = trim($_POST["code"]);
include_once './inc/config.php';
$con = new mysqli(HOST, USER, PASSWORD, DATABASE);
$sql="SELECT * FROM info WHERE First_Name='".$username."' AND Line_Number='".$code."'" ;
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
if($num_rows != 0){
echo true;
}
else{
//echo "Who are you?!";
return false;
}
mysqli_free_result($result);
mysqli_close($con);
If your message element has the ID message, select it like this:
$("#message").html(msg);
If it has the class message, select it like this:
$(".message").html(msg);
The JQuery documentation contains an overview and in-depth description of all selector types.
In addition, to trigger the error method in your Javascript, your server-side code needs to send a HTTP error code, for example like this:
header("HTTP/1.1 404 Not Found");
Or like this:
http_response_code(404);
Is message a class or an ID? Make sure that you use the proper selector on which your output is to be displayed.
Use, # for id and . For class
error: function(){
$("#message").html(msg);
To target a div with id message use
$("#message")
You have missed the #
Try this:
$.ajax({...
success: function(data){
if(data)
$("#message").html (msg);
else
alert(data);
}
});
Apart from the obvious error in the message selector, another problem I can see is in your code is in your PHP.
Your php code does not return an error condition, it returns a true or false, so always your success callback will be called.
So
if($num_rows != 0){
echo true;
}
else{
//echo "Who are you?!";
echo false;
}
then
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
cache: false,
success: function (result) {
if (result) {
alert(result);
} else {
alert(msg);
//make sure you use a proper selector here
$("message").html(msg);
}
},
error: function () {
$("message").html(msg);
}
});
error: function(){
$("message").html(msg);
}
Do you respond with 404 or anything else, except of 2xx, when user is not found? And, yes, selector is incorrect. Your function will be called only in case of HTTP error during request to the server.
This
else{
//echo "Who are you?!";
return false;
}
will not run your function.
This
else{
//echo "Who are you?!";
header("HTTP/1.0 404 Not Found");
exit;
}
can do it, but not a very nice solution. The best one is to return something like this
$response = array('status' => 'failed', 'text' => 'Whatever');
header('Content-type: application/json');
echo json_encode($response);
exit;
and in your success function work with data, check the 'status' and so on.

Why I still get object object error in javascript?

I have this javascript to update a php session variable :
$(document).ready(function(){
$('#facebook_img').live('click',function(){
login_condetion = 1;
$.ajax({
type: "POST",
url: 'facebook_login_condition_variable.php',
data:{login_condetion:login_condetion},
dataType: "json",
success: function(data)
{
alert(123);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
/*alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);*/
}
});
});
});
I print the session value before and after this code but it never change and when I alert responsText I get nothing and XMLHttpRequest gives me object object error .
This is my php code :
<?php
$temp = $_POST['login_condetion'];
if(!empty($temp) && $temp != 0)
{
$_SESSION['do_not_allow_auto_facebook_login'] = 1;
}
else
{
$_SESSION['do_not_allow_auto_facebook_login'] = 0;
}
$go = $_SESSION;
echo json_encode($go);
?>
Is there any problem with dataType of ajax function ? or it is a php session problem ? Please help me because I have been stuck here for long time.
Some suggestions..
Do you start the session at top of the page where you use it.
session_start();
in php code replace
$go = $_SESSION;
with
$go = $_SESSION['do_not_allow_auto_facebook_login'];
3.Do you need the datatype json, if not remove this line
echo json_encode($go);
and use
echo $go;
Use session_start() at the top of your script:
<?php
session_start();
...

Jquery Error parsing Json data

I'm having an error parsing a JSON response from PHP.
Javascript:
function getStock()
{
var color = $("#select_color option:selected").val();
var comp = "<?= $idComp ?>";
$.post( "ajax/getStock.php",
{
idColor: color,
idComp: comp
}).done(function( data )
{
alert(data);
var obj = jQuery.parseJSON(data);
$('#stockReal').val(obj.StockReal);
$('#stockMinimo').val(obj.StockMinimo);
$('#stockMaximo').val(obj.StockMaximo);
});
}
PHP:
<?php
require_once "../../helper/db.php";
require_once "../../helper/security.php";
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(!empty($_POST['idColor']) && !empty($_POST['idComp']))
{
$idComponente = test_input($_POST['idComp']);
$idColor = test_input($_POST['idColor']);
$conn = db_connect($STOCKMANAGER);
$sql = "SELECT * FROM TableStock
WHERE idComponente = '$idComponente'
AND idColor = '$idColor';";
$stock = db_request_one($conn, $sql);
if($stock !== 0)
{
$respuesta = array('StockReal'=>$stock->StockReal
,'StockMinimo'=>$stock->StockMinimo
,'StockMaximo'=>$stock->StockMaximo);
echo json_encode($respuesta);
}
else
{
$respuesta = array('StockReal'=>''
,'StockMinimo'=>''
,'StockMaximo'=>'');
echo json_encode($respuesta);
//echo $respuesta;
}
}
}
?>
The error:
Uncaught SyntaxError: Unexpected token ... jquery-1.10.2.js:550
When I get data from alert for example I get:
{"StockReal":"33","StockMinimo":"0","StockMaximo":"55"}
This is a good Json data. But if I try to validate with http://jsonlint.com/ i get the next error message:
Parse error on line 1:
^
Expecting '{', '['
Also when I try to stringify the Json Data I get a lot of u0000\ before and after the data.
like this:
"\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000{\"StockReal\":\"33\",\"StockMinimo\":\"0\",\"StockMaximo\":\"55\"}\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"
Can anyone help me?
Have you done an output of what is returned from $respuesta array? print_r($respuesta) and see what's in your array.
Also make sure you have NO white space in your getStock.php file.

Categories

Resources