I have this PHP:
function getList() {
$sql = " SELECT * FROM list ";
try {
$db = getConnection();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(array('result' => $result));
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
and this javascript:
$.ajax({
type: 'GET',
url: rootURL + '/' + myAPI,
dataType: "json",
success: function(list) {
var list = list.result;
console.log (list);
}
error: function( jqXHR, textStatus, errorThrown ) {
console.log (" errors: " );
console.log (jqXHR);
console.log (textStatus);
console.log (errorThrown);
}
});
now everything was working fine until I added some rows in the list table of my DB.
So now the js list result from AJAX is empty:
{"result": }
The error I receive from AJAX is:
Object { readyState=4, status=200, statusText="OK", more elements...}
parsererror
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
so I tried to remove: dataType: "json", but result is still empty.
the only way to make it works is to limit the SQL query like this:
$sql = " SELECT * FROM list LIMIT 9 ";
and it works:
{"result":
[
{"ID":"1","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"2","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"3","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"4","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"5","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"6","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"7","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"8","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"9","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
]
}
I don't understand why there is such a limit. I also tried:
$sql = " SELECT * FROM list LIMIT 10 ";
and so on, but the result is still empty:
{"result": }
Can you help me please?
Thanks
Read the manual at http://php.net/json_encode. It says:
All string data must be UTF-8 encoded.
Make sure your data is in UTF-8 encoding in the database. If not you have to convert it first.
If it is working with LIMIT 9 and not working with LIMIT 10 so problem is in your records after 9th row so please check your 10th row It may have any 'special character', 'new line character' which is creating problem.
There are 2 points I'd like to point out in your code to have a look at. First of all, the construction of the error should be using the json_encode function, which will ensure valid format, so instead of doing echo '{"error":{"text":'. $e->getMessage() .'}}'; you should do
$response = new stdClass();
$response->error = new stdClass();
$response->error->text = $e->getMessage();
echo json_encode($response);
Note, that it looks overly complex, but I tried to retain the format you specified in your example.
The other thing is that Javascript will not like type: 'json' if the correct headers are not set. So what I suggest your PHP function should look like is this:
function getList() {
$response = new stdClass();
$sql = " SELECT * FROM list ";
try {
$db = getConnection();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$response->result = $result;
unset($db);
} catch(PDOException $e) {
$response->error = new stdClass();
$response->error->text = $e->getMessage();
}
header("Content-Type: application/json");
echo json_encode($response);
exit();
}
I hope this helps!
Related
I have a filter for some devices in a webpage, made of checkbox. Whenever one of the checkbox is clicked, i call a function which add to an object the value of the checkboxes checked. I want to send this object to a php file, via ajax, and use it to perform some MySQL query, then return the results from the php and display them on the page. The problem is, i'm missing something, since i kept getting a parseerror in my js.
Here's my code:
device-filter.js
$(document).ready(function(){
$(".ez-checkbox").click(function() {
console.log("ok");
var re = {Brand: "", Cost: "", OS: ""};
$("#Brand :checkbox:checked").each(function(){
re.Brand += $(this).val()+" & ";
});
$("#Cost :checkbox:checked").each(function(){
re.Cost += $(this).val()+" & ";
});
$("#OS :checkbox:checked").each(function(){
re.OS += $(this).val()+" & ";
});
if(re.lenght==0){
}
else{
$.ajax({
method: "POST",
dataType: "json", //type of data
crossDomain: true,
data: re,
url:"./php/filtered-device-query.php",
success: function(response) {
//display the filtered devices
},
error: function(request,error)
{
console.log(request+":"+error);
}
});
}
});
});
filtere-device-query.php
<?php
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_db");
if (mysqli_connect_errno()) { //verify connection
echo "Error to connect to DBMS: ".mysqli_connect_error(); //notify error
exit(); //do nothing else
}
else {
//echo "Successful connection"; // connection ok
$devices =json_decode($_POST['re']);
echo var_dump($devices)."<br>";
$myArray = array();//create an array
$brand = rtrim($devices["Brand"], " &");
$cost = rtrim($devices["Cost"], " &");
$os = rtrim($devices["OS"], " &");
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND 'Cost' = '$cost' AND 'OS' = '$os' ";
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
//free result
$result->close();
//close connection
$mysqli->close();
}
?>
Thanks in advance for any help!
You have some typos, first in the jQuery:
if(re.lenght==0){
should be:
if(re.length==0){// note the correct spelling of length
Then in your PHP you're using quotes on column names in the query. Those should be removed or better yet, back ticked:
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND `Cost` = '$cost' AND `OS` = '$os' ";
More importantly...
An object, as you've described it, has no length. It will come back as undefined. In order to find the length you have to count the keys:
if(Object.keys(re).length == 0){...
The object re, as you've declared it, already has 3 keys, a length of 3. Checking for length of 0 is a waste of time.
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
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);
}
});
I'm having trouble getting data from my database. My goal is to get all groups from my database and return them in JSON (in an alert box or whatever).
Now it won't convert to JSON and I am getting weird response text from the ajax call. If you need anything else to solve this problem, please do not hesitate to ask.
Here is what I did.
PHP
$servername = "redacted";
$username = "redacted";
$password = "redacted";
$dbname = "redacted";
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'getGroups' : getAllGroups();break;
}
}
function getAllGroups() {
$mysqli = new mysqli($servername, $username, $password, $dbname);
$query = $mysqli->query("SELECT * FROM groups");
while($row = $query->fetch_object()) {
$result[] = $row;
}
echo "{\"results\":";
echo json_encode($result);
echo "}";
$mysqli->close();
}
JS
function getPosts() {
$.ajax({
url: 'functions.php',
data: {action: 'getGroups'},
type: 'post',
success: function(output) {
var result = JSON.parse(output);
result = result.resultaten;
alert(result);
}
});
}
getPosts();
Thanks in advance,
Mistergrave.
No need for that extra echos. Try with -
echo json_encode(array('results' => $result));
Instead of -
echo "{\"results\":";
echo json_encode($result);
echo "}";
No need for - if(isset($_POST['action']) && !empty($_POST['action'])) {
if(!empty($_POST['action'])) { - do the all.
Define $result first.
$result = array();
while($row = $query->fetch_object()) {
$result[] = $row;
}
Okay guys, I managed to solve everything. Apparently the php function couldn't find my credentials to log in to the database server because I defined them on top of the php file (and since javascript only executed the function, these credentials were undefined).
Solution:
I just copy-pasted the credentials at the start of each function so these were defined. And tadaah! It worked :).
Now I realize why the responseText was full of tables, because it started to return error tables about the connection.
I hope my explanation will help other people who have this issue as well.
Cheers, and thanks for all the helpfull answers,
Mistergrave.
use
echo json_encode(array('result'=>$result));
As it takes array as parameter. Check here
Just a note :
If are sure you will return json data, use dataType:json , so you wont need JSON.parse(output).
I have an $.ajax call in one of my pages that links to a simple php page.
I am getting my alert for the error: property. I am not getting anything back in the errorThrown variable or in the jqXHR variable. I have never done this kind of thing before and i am not seeing what is wrong with my page.
JQuery $.ajax call :
function jsonSync(json) {
$.ajax({
type: 'POST',
url: 'http://www.cubiclesandwashrooms.com/areaUpdate.php',
dataType: 'json',
data: json,
context: this,
success: function () {
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error has occured! \n ERR.INDEX: Sync failed, ' + jqXHR.responseText + ';' + textStatus + ';' + errorThrown.message);
return false;
}
});
And this is my PHP Page :
$JSON = file_get_contents('php://input');
$JSON_Data = json_decode($JSON);
//handle on specific item in JSON Object
$insc_area = $JSON_Data->{'insc_area'};
//mysqlite connection.open() equivilent
$insc_db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($insc_db)) {
die('Could not connect: ' . mysql_error());
echo "Failed to connect to MySql: " . mysqli_connect_error();
//mysqli_close($insc_db);
}
//$insc_area.length equivilent
$insc_area_size = sizeof($insc_area);
//cycle through reult set
for ($i = 0; $i < $insc_area_size; $i++) {
//assign row to DataRow Equivilent
$rec = $insc_area[$i];
//get specific column values
$area = $rec->{'area'};
$id = $rec->{'srecid'};
//sqlcommand equivilent
$query = "SELECT * FROM insc_products WHERE id='$id' LIMIT 1";
$result = mysqli_query($insc_db, $query);
$num = mysqli_num_rows($result);
//dataReader.Read equivilent
while ($row = $result->fetch_array()) {
$query = "UPDATE insc_products SET area='$area' where id = '$id'";
$res = mysqli_query($insc_db, $query);
//checking if update was successful
if ($res) {
// good
error_log('user update done');
echo 'update was successful';
} else {
error_log('user update failed');
echo 'error in update';
}
}
}
echo 'testing php';
dataType: 'json'
means: give me json back. your PHP file isn't returning json formatted data
similar question: jQuery ajax call returns empty error if the content is empty
to buid a json response fill an array in the php file with the return information and use echo json_encode($array); at the end of the file. if you are using dataType:'json' because the code is copy/pasted, and you won't need the response to be in json format, simply remove this option...
Add following line in php file, $JSON_Data encode then it will work.
echo json_encode($JSON_Data);
So I have a database pass a whole bunch of data using PHP back to jQuery through JSON.. I'm trying to access individual columns from the returned data but no luck..
My PHP:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Here's my JS:
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
success:function(data){
$('.quoteList').append(data[0]);
}
});
}
Currently that appends the following to the element:
[{"id":"1","text":"The most wasted of all days is one without laughter.","author":"E.E. Cummings","status":"1"}]
So for example.. if I wanted the jQuery to go through data[0] to data[92] (the last one) and append the author of each to .quoteList, how could I do that? I've tried data[0][1] and data[0][author]
You can use $.each() to loop through the data and append the author:
$.each(data, function(i) {
$('.quoteList').append(data[i]['author']);
});
The PHP might be defective because json_encode is called twice, and this is unusual. As written this would be flattening the rows into JSON strings, but mere strings nonetheless, which then get JSON encoded again into an array of strings. This is probably not what you intended, as it would be making it possible to print the received data but not access the components of rows which will be decoded to strings and not objects.
Compare https://stackoverflow.com/a/6809069/103081 -- here the PHP echoes back a callback with a single JSON object inside parenthesis ().
I suspect the fix looks like https://stackoverflow.com/a/15511447/103081
and can be adapted as follows:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Once you have this, you should be getting back proper JSON for your array of objects and be able to use #Felix's code on the client side.
you need to use loop on your data, try this
success:function(data){
for (var i in data) {
$('.quoteList').append(data[i]);
}
}
This should work:
(upd. all code:)
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
contentType: "application/json",
success:function(data){
var str = "";
$(data).each(function(index, item){
str += item.author + " ";
});
$('.quoteList').append(str);
}
});
}
Your problem is here:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
you need something like this:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
$myjsons['callback'] = $_GET['callback'];
echo json_encode($myjsons);