Jquery Error parsing Json data - javascript

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.

Related

Convert a Ajax Json String to a JS Object for my Ajax Get Script

I ideally want the Ajax result to be converted from Jsonstring to OBJ Thank You in advance.
I know the AJAX GET script is working becuase when I alert the Ajax Post result I see the Contents in json string format as below.
alert(JSON.stringify(data));
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I want the AJAX GET result data converted to look like this in OBJ format like below.
{id:31,name:"Mary",username:"R8344",email:"wemail}];
PHP/SQL CODE with the Json encoded Array
<?php
include "../mytest/config.php";
$return_arr = array();
$sql = "SELECT * FROM users ORDER BY NAME";
$result = $conn->query($sql);
//Check database connection first
if ($conn->query($sql) === FALSE) {
echo 'database connection failed';
die();
} else {
while($row = $result->fetch_array()) {
$id = $row['id'];
$username = $row['username'];
$name = $row['name'];
$email = $row['email'];
$return_arr[] = array(
"id" => $id,
"username" => $username,
"name" => $name,
"email" => $email);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
?>
php echo _encode array above returns below Json string format
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I am looking for something like below.( top half of the script)
<script>
$(document).ready(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'get',
dataType: 'JSON',
success: function(result){
var data =(JSONstring convert to OBJ(result);
//-----The top half of script -------------
$.each(data, function( i, person ) {
if(i == 0) {
$('.card').find('.person_id').text(person.id);
$('.card').find('.person_name').text(person.name);
$('.card').find('.person_username').text(person.username);
$('.card').find('.person_email').text(person.email);
} else {
var personDetailCloned = $('.card').first().clone();
personDetailCloned.find('.person_id').text(person.id);
personDetailCloned.find('.person_name').text(person.name);
personDetailCloned.find('.person_username').text(person.username);
personDetailCloned.find('.person_email').text(person.email);
$('.card-container').append(personDetailCloned);
}
});
});
</script>
I will need help with the closing tags as above is just an example
The solution is:
success: function(result){
data =(result);
There was no need o convert the data to OBJ or anything ( blush). Then the code on the 2nd half of the Ajax script will receive the data and populate. Thanks to all contributors.

Sending html code through json from php to javascript

I am getting following error in JS:
SyntaxError: Unexpected token < in JSON at position 0
How can I properly send HTML code (it's a whole page) through the JSON.
I did not made this idea, but this is the plugin that I am trying to install, and I am getting this error. So if anybody can point me out what is wrong in here and how to fix it, it would be great. Thanks.
public function ajaxfilter()
{
$this->registry->set('bf_force_tmp_table_creation', true);
$data = $this->_prepareFilterInitialData();
$json = array();
$route = $this->_getRequestParam('curRoute');
if ($route && $this->_getRequestParam('withContent')) {
$this->request->get['route'] = $route;
$this->load->controller($route, $data);
$json['products'] = $this->response->getOutput();
}
$this->load->model('module/brainyfilter');
$model = new ModelModuleBrainyFilter($this->registry);
$model->setData($data);
if ((bool)$this->_getRequestParam('count', false)) {
$json['brainyfilter'] = $model->calculateTotals();
}
if ((bool)$this->_getRequestParam('price', false)) {
$minMax = $model->getMinMaxCategoryPrice();
$min = floor($this->currency->format($minMax['min'], $this->_currency, '', false));
$max = ceil($this->currency->format($minMax['max'], $this->_currency, '', false));
$json['min'] = $min;
$json['max'] = $max;
}
$this->log->debug($json);
$isMijoShop = class_exists('MijoShop') && defined('JPATH_MIJOSHOP_OC');
if ($isMijoShop) {
header('Content-Type: application/json');
die(json_encode($json));
} else {
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
Use json_encode to get a valid JSON string.
You can encode any scalar value, arrays and stdClass instances. For any other class, you may implement the JsonSerializable interface.
A simple HTML example:
<?php
$html = '<div class="container">What-Ever-Content </div>";
echo json_encode($html);
This will produce this output:
"<div class=\"container\">What-Ever-Content </div>"

Uncaught SyntaxError: Unexpected token (, no error visible

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

php ajax jquery responseText not returned

I am trying to write an insert query with jquery, ajax and php. The record is getting inserted but returns a status error. First I tried to echo the message in php as it didn't work I tried it with print json_encode but both returned the status as error. Why doesn't it return the responseText?
{readyState: 0, responseText: "", status: 0, statusText: "error"}
This is the addmember.php file
<?php
require '../database.php';
function random_password( $length = 8 ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%^&*()_-=+;:,.?";
$password = substr( str_shuffle( $chars ), 0, $length );
return $password;
}
$password = random_password(8);
//$regno=$_POST['regNo'];
$adminno=$_POST['adminNo'];
$batch=$_POST['batchText'];
$type=$_POST["memberType"];
$initials=$_POST["initialName"];
$fullname=$_POST["fullName"];
$address=$_POST["address"];
$telephone=$_POST["contact"];
$email=$_POST["email"];
$nic=$_POST["nic"];
$dob=$_POST["birthDate"];
$priv=$_POST["memberType"];
$userid="";
$sql="select username from memberinfo where username='$adminno'";
$result=mysqli_query($con,$sql);
if(mysqli_num_rows($result)==0){
$sql="insert into memberinfo(username,nic_no,class,name_initial,full_name,address,telephone,email,date_of_birth) VALUES ('$adminno','$nic','$batch','$initials', '$fullname', '$address', '$telephone','$email','$dob')";
$result1=mysqli_query($con,$sql);
$sql = "select * from memberinfo where username='$adminno'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$userid = $row['user_id'];
}
}
$sql="insert into userlogin(user_id,username,privilege,password) VALUES ('$userid','$adminno','$priv','$password')";
$result2=mysqli_query($con,$sql);
if ($result1 && $result2) {
$message = "<p>New record created successfully</p>";
} else {
$message = "<p>Error: " . $sql . "<br>" . $con->error.".</p>";
}
} else{
$message = "<p>Admission no already exists.</p>";
}
print json_encode($message);
$con->close()
?>
This is the .js file with the ajax function
$(document).ready(function(){
$('#addmember').click(function(){
console.log("addmember");
var adminno=$("#adminNo").val();
var nic=$("#nic").val();
var batch=$("#batchText").val();
var initials=$("#initialName").val();
var fullname=$("#fullName").val();
var address=$("#address").val();
var telephone=$("#contact").val();
var email=$("#email").val();
var dob=$("#birthDate").val();
var priv=$("#memberType").val();
//$("#result").html("<img alt='ajax search' src='ajax-loader.gif'/>");
$.ajax({
type:"POST",
url:"../ajax/addmember.php",
dataType: "json",
data:{'adminNo':adminno, 'nic':nic,'batchText':batch,'initialName':initials, 'fullName':fullname, 'address':address, 'contact':telephone,'email':email,'birthDate':dob,'memberType':priv},
success:function(response){
console.log(response);
$("#result").append(response);
},
error:function(response){
console.log(response);
}
});
});
});
Status zero normally means the page is navigating away. Stop it from happening.
$('#addmember').click(function(evt){ //<--add the evt
evt.preventDefault(); //cancel the click
You are not returning valid JSON from the server. You're json encoding a string, but valid JSON requires an object, or array to encapsulate the day coming back.
So at the very least:
echo json_encode(array($message));
No need for the JSON response. Simply return the message from your PHP script as shown below (note the use of echo and the semicolon following close()):
PHP
$con->close();
echo $message;
Also, remove the JSON filetype from your AJAX call and instead append response.responseText rather than response:
JS
$.ajax({
type:"POST",
url:"../ajax/addmember.php",
data:{'adminNo':adminno,'nic':nic,'batchText':batch,'initialName':initials, 'fullName':fullname, 'address':address, 'contact':telephone,'email':email,'birthDate':dob,'memberType':priv},
success:function(response){
console.log(response);
$("#result").append(response.responseText);
},
error:function(response){
console.log(response);
}
});

Ajax Javascript Get JSON value

Hi I am developing an app in phonegap, where I am getting a particular value from server by connecting php file the value I need to pass is a string value 'pmnno'suppose whose value is '2' I need to get the value of '2' in column name 'personalnumber'.. So I am giving my code below
var jsonData;
$.ajax({
type: 'GET',
url: 'http://xxxx.com/app/get_pday1_number.php',
data: { pmnno: '2' },
dataType: 'html',
success: function (response) {
jsonData = response;
alert(jsonData);
}
});
php code
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pone"]))
{
$pone = $_GET['pone'];
// get a product from products table
$result = mysql_query("SELECT *FROM pdaynew WHERE pone = $pone");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["pone"] = $result["pone"];
$product["personaldayone"] = $result["personaldayone"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I am getting a success mesage that means connection is succesful but ineed the value of '2' in column 'personalnumber' for that where I need to add that code..If anyone knows pls help me...
Instead of using * use personaldayone:
$result = mysql_query("SELECT personaldayone FROM pdaynew WHERE pone = $pone");

Categories

Resources