error 200 - SyntaxError: JSON.parse: unexpected character - php

I am trying to fill a dropdown list from a mysql database by using ajax and jquery. The data is should be in json format. But I keep getting syntax error: JSON.parse: unexpected character. Please advise. Thank you for your help.
This is my code in Dreamweaver
$(document).ready(function(){
$.getJSON("http://localhost:8000/states.php", function(data) {
$.each(jsondata, function(index, item) {
$('<option></option>').val(item.state_code).html(item.state).appendTo("select#personalstate");
});
});
});
Database code:
database.php
<?php
$dsn = 'mysql:host=localhost;dbname=elihu';
$username = 'admin';
$password = 'password';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try {
$db = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
$error_message = $e->getMessage();
include ('index.php');
exit();
}
?>
json php file
<?php
require('database.php');
function getStates() {
global $db;
$query = 'SELECT * FROM states';
try {
$statement = $db->prepare($query);
$statement->execute();
$states = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
echo json_encode($states);
} catch (PDOException $e) {
$error_message = $e->getMessage();
include ('index.php');
exit();
}
}
?>

$.getJSON("Model/php/states.php", function(data) {
// No need to parse the json data, it's already been parsed by getJSON
// jsondata = $.parseJSON(data);

Related

Polymer data binding to MySQL table data with PDO

I am trying to sync some polymer element properties with a MySQL database on localhost using MAMP.
How do I pass the SQL data from a PHP variable to a Polymer data binded property?
The Polymer element is as follows:
<iron-ajax id="ajax"
auto
url="../src/data/php/get_data.php"
last-response="{{lastResponse}}"
handle-as="text"></iron-ajax>
...
static get properties() { return {
lastResponse: {
type: Object,
value: {}
}
}}
lastResponse () {
console.log(this.lastResponse);
}
The PHP script is as follows:
<?php
$servername = "localhost";
$username = "***";
$password = "***";
$dbname = "myDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
PHP function
get_data.php
should echo(not return) JSON, as:
$res['data'] = 'Hello!';
echo json_encode($res);
and iron-ajax should be set to receive JSON:
handle-as="json"
as in docs here
https://www.webcomponents.org/element/PolymerElements/iron-ajax/elements/iron-ajax
In Polymer first execute the AJAX request, and then receive the data as this:
get_data_responseHandler: function(e) {
console.log(e.detail.response);
}
That is how API point is created.

Angular returned data

i am trying to create a service that will return a json data from php api, but instead of return pure json data, the angular seem to return JSON together with its config.
services.js
.service('DistinctAPIService', function($http){
var base = 'http://localhost/onseral/api/';
this.listDistinct = function(table, field){
return $http({
method: 'POST',
url: base + '/listDistinct.php',
params: {
table: table,
field: field
}
});
}
})
.controller('DistinctMatcode', function($scope, DistinctAPIService){
DistinctAPIService.listDistinct('material', 'matcode').then(function(data){
$scope.data = data;
console.log(JSON.stringify(data));
})
})
listdistinct.php
<?php
require_once '/config/dbconfig.php';
$table = $_GET['table'];
$field = $_GET['field'];
GetData($table,$field);
function GetData($tablename,$fieldname) {
$sql = "SELECT DISTINCT $fieldname as expr1 FROM $tablename order by expr1 asc";
try {
$db = getdb();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode(array('data' => $data));
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>
instead of returning the correct JSON data, it returned
{"data":{"data":[{"expr1":"CFFBPS16"}]},"status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"url":"http://localhost/onseral/api//listDistinct.php","params":{"table":"material_copy","field":"matcode"},"headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}
any idea?
try this
controller('DistinctMatcode', function($scope, DistinctAPIService){
DistinctAPIService.listDistinct('material', 'matcode').then(function(response){
$scope.data = response.data.data;
console.log(JSON.stringify(data));
})
Use header function before sending data to the client side.
i modified your listdistinct.php file. try it , let me know if issue persist.
<?php $sql = "SELECT DISTINCT $fieldname as expr1 FROM $tablename order by expr1 asc";
try {
$db = getdb();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
header('Content-Type: application/json');
echo json_encode(array('data' => $data));
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>

Why show me the first option in my dropdown?

I don't know what is the problem.
I have this part of my php:
public function fillObject(){
try {
$servername = "localhost";
$username = "root";
$password = "123asd";
$conn = new PDO("mysql:host=$servername;dbname=bd_actividades", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT pro_nombre FROM act_proyecto");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
foreach ($result as $row) {
$aObjects=array();
$oTransfer = new TransferProyeCtr();
$oTransfer->setNombre($row['pro_nombre']);
$oTransfer->setState(1);
$aObjects[]=$oTransfer;
return $aObjects;
} }catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
} }
this send the results : $oTransfer->setNombre($row['pro_nombre']);
And in my dropdown show this:
But I need this :
What is the problem?
Here is my module where I print:
Ajax:
llenarComboProyectos: function(iSecciones){
var self = this;
self.ajaxCall('http://localhost:8080/PROJECTS/dailytasks/api/sistemaTareas/v1/'+"proyectos","GET", null).then(function(data) {
console.info("data",data);
if(self.checkError(data[0].state)){
self.llenarCombos(iSecciones,data);
}else{
alert("error service");
}
});
},
Where I print:
llenarCombos: function(secciones,data){
var self = this;
console.info(data);
for (var i = 0; i < data.length; i++){
var cProyectos = "<option>"+data[i].nombre_proyecto+"</option>";
for(var iCont=0;secciones>=iCont; iCont++){
$("#select_proyecto_"+iCont+"_id").append(cProyectos);
$("#select_proyecto_"+iCont+"_id").selectpicker('refresh');
}
}
},
here I get pro_nombre: var cProyectos = "<option>"+data[i].nombre_proyecto+"</option>";
Please remove
$stmt->setFetchMode(PDO::FETCH_ASSOC);
from your first script.
I think this will solve your problem.
http://php.net/manual/en/pdostatement.fetch.php
http://php.net/manual/en/pdostatement.fetchall.php

How do I send a bunch of json objects in an ajax response with jquery

I'm playing with jQuery's $.ajax and I'm not sure how I should be doing the following:
Here's my javascript (right now its just embedded in the html page)
$.ajax({
type: 'GET',
url: 'DBConnect.php',
data: '',
dataType: 'json',
success: function(data) {
console.dir(data);
},
error:function (xhr, ajaxOptions, thrownError) {
dir(thrownError);
dir(xhr);
dir(ajaxOptions);
}
});
Here is what DBConnect.php looks like:
$username = "root";
$pass = "pass";
$host = "127.0.0.1";
$dbname = "test";
//queries
$table = "events";
$fetchAll = "SELECT * FROM $table";
try {
$DB = new PDO("mysql:host=$host;dbname=$dbname", $username, $pass);
//_WARNING uncommented when debugging
$DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
//$DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$query = $DB->query($fetchAll);
$query->setFetchMode(PDO::FETCH_OBJ);
while($row = $query->fetch()) {
echo json_encode($row);
}
} catch(PDOException $e) {
echo $e->getMessage();
}
$DB = null;
Doing this I get a syntax error. I thought I could get away with returning every row as a json object, but clearly that doesn't work. I could just add all the row objects to one array and convert that to json, but I wanted to know if there was a better\more efficient way to do this.
Change the while loop:
$temp = array();
while($row = $query->fetch()) {
$temp[] = $row;
}
echo json_encode($temp);
Try this, and let me know if that helps!

Autoselect and jQuery post doesnt work together

I have another problem with my code.
<script type="text/javascript">
$("#wojewodz").change(function(){
var id_wojewodztwa = $("#wojewodz").children(":selected").attr("id");
$.post("miasta.php", { id_wojewodztwa: id_wojewodztwa } );
$('#powiat_miasto_auto_complete').autocomplete({source:'miasta.php', minLength:2});
});
</script>
this is functions which get ID of selected select and transfering it to miasta.php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass, $options);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if (($conn) and (isset($_GET['id_wojewodztwa'])))
{
$id_wojewodztwa = $_GET['id_wojewodztwa'];
$ac_term = "%".$_GET['term']."%";
$query = "SELECT DISTINCT nazwa FROM podzial_tm where woj='$id_wojewodztwa' and nazdod!='województwo' and nazwa like :term LIMIT 10";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['value'] = $row['nazwa'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
somebody can tell me where is some mistake?
when i change " where woj='$id_wojewodztwa'" to for example " where woj='26'" and delete " and (isset($_GET['id_wojewodztwa']))" everything is ok, so i think i have problem with POST
happy Easter! :)))
You are POSTing the data. You need to look in $_POST['id_wojewodztwa'] for the value you are looking for, not in $_GET.
$.post("miasta.php", { id_wojewodztwa: id_wojewodztwa } );
to
$.get("miasta.php", { id_wojewodztwa: id_wojewodztwa } );
or if you have to catch up the result, use:
$.get("miasta.php", { id_wojewodztwa: id_wojewodztwa },function(result){
/** some code here */
},'json');
UPDATE:
if you use $.post, edit the following lines:
if (($conn) and (isset($_POST['id_wojewodztwa'])))
{
$id_wojewodztwa = $_POST['id_wojewodztwa'];
Remove isset($_GET['id_wojewodztwa']) and also modify $id_wojewodztwa = intval($_GET['id_wojewodztwa']);

Categories