My PHP code should return a json object of a sql query, but it always throws the error "unexpected end of input". I noticed it doesn't fail if I don't use the variable $row. Here is a snippet of the code:
PHP:
require("pw.php");
class homework {
public $fach;
public $datum;
public $aufgabe;
public function __construct($fach, $datum, $aufgabe) {
$this->fach = $fach;
$this->datum = $datum;
$this->aufgabe = $aufgabe;
}
}
$connection = mysqli_connect($adrs, $usr, $pw, $db);
if(mysqli_connect_errno()) {
die(json_encode(mysqli_connect_error()));
}
if($_POST["feed"] == "hausaufgaben") {
$query = "SELECT fach, datum, aufgabe FROM hausaufgaben WHERE fachgruppe != '";
if($_POST["fremdsprache"] == "latein") {
$query .= "französisch";
}
else {
$query .= "latein";
}
$query .= "' AND fachgruppe != '";
if($_POST["englisch"] == "koch") {
$query .= "schopper";
}
else {
$query .= "koch";
}
$query .= "' AND datum > '" . date("Y-m-d") . "' ORDER BY datum ASC;";
$result = $connection->query($query);
$data = [];
while($row = $result->fetch_row()) {
array_push($data, new homework($row[0], $row[1], $row[2]));
}
echo json_encode($data);
$result->close();
}
$connection->close();
?>
Jquery:
$.ajax({
type: "POST",
url: "php/getFeed.php",
cache: false,
dataType: "json",
data: {feed: "hausaufgaben", fremdsprache: this.fremdsprache, englisch: this.englisch}
})
.done(function(data) {
alert(typeof(data));
document.getElementById("temp").innerHTML = data;
if(typeof(data) != "Object") {
console.log("Error: " + data);
alert("iwas?");
this.hausaufgabenError = true;
this.hausaufgaben = [];
alert(this.hausaufgaben + "\n\n" + this.hausaufgaben.length);
}
else {
this.hausaufgabenError = false;
this.hausaufgaben = data;
}
})
.fail(function(jqXHR, textStatus, error) {
console.log("error: " + error);
alert("iwas?");
this.hausaufgabenError = true;
this.hausaufgaben = [];
alert(this.hausaufgaben + "\n\n" + this.hausaufgaben.length);
});
I hope someone can help me out, because I'm completely stuck :(
Edit: In Mozilla, it thows the error SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data.
In jquery, the command $.parseJSON(''); produces the error you are experiencing. Also, parseJSON will fail similarly if it's given something other than JSON to work with. So my guess is that your php page is either displaying an error, returning no output, or returning JSON mixed with other output.
What to do is either:
fetch the php page in a browser, not via ajax, and look at the output.
or
change the datatype to text for debugging, and use console.log to look at what is actually being sent to your javascript code.
Related
I want to POST data from form. It works fine.
In the other functionality i want to get data from database.
I don't know where is mistake. I suspect that AJAX call is fine.
My PHP code:
<?php
$uuid = $_POST['uuid'];
$minor = $_POST['minor'];
$mayor = $_POST['mayor'];
$lokalizacja = $_POST['lokalizacja'];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
echo "Polaczono";
}
$sql = "INSERT INTO beacons (uuid, major, minor, lokalizacja)
VALUES ('$uuid', '$minor', '$mayor', '$lokalizacja')";
if ($conn->query($sql) === TRUE) {
echo "Dane dodano prawidłowo";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sqlget = "SELECT uuid, major, minor, lokalizacja FROM beacons";
$result = $conn->query($sqlget);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo json_encode(array("value" => "UUID: " . $row["uuid"]));
}
} else {
echo "Brak rekordów w bazie";
}
$conn->close();
?>
AJAX call:
$('#admin').submit(function(e){
e.preventDefault();
if( ($("input[name=uuid]").val().length) > 40 || ($("input[name=minor]").val().length) > 5 || ($("input[name=mayor]").val().length) > 5 || ($("input[name=lokalizacja]").val().length) > 20){
$(".error-pola").show();
} else{
$.post('administrator-connect.php', $(this).serialize() )
.done(function(){
$(".success-wyslanie").show();
})
.fail(function(){
$(".error-wyslanie").show();
});
}
});
$(document).ready(function() {
$.ajax({
type: "GET",
url: 'administrator-connect.php',
dataType: 'json',
success: function(data)
{
alert("fsdfsd"+ data);
},
error: function(){
alert("not");
}
});
});
I am using:
echo json_encode(array("UUID" => $row["uuid"]));
and in ajax:
var jqxhr = $.get( "administrator-get.php", function(data) {
var jsonx = JSON.parse(JSON.stringify(data));
$( "#data-listing" ).html(jsonx);
});
But I get response:
{"UUID":"B9407F30-F5F8-466E-AFF9-25556B57FE6D"}
How to get only string ?
If you write this
dataType: 'json',
It expect for JSON value not string be sure to return only JSON.
You returns string value not JSON.
With like this code
echo "Polaczono";
Any echo would be the return value for ajax
At last you should return only one value like this.
echo json_encode($result);//an array result
You can check by string return. By removing dataType
This is my ajax call.
$(document).on('click','#Quote_create_value',function(){
$.ajax({
type : 'GET',
url : '../../../protected/config/ajax.php',
success : function(response){
$("#Quote_template_value").html(response);
}
});
});
I have many methods in ajax.php. Each and every method throws some response.
<?php
function respose()
{
$query = "select * from quote where template IS NOT NULL";
$result = mysql_query($query, $con);
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['template'].'">' . $row['template'] . '</option>';
}
$query1 = "select * from template";
$data = mysql_query($query1,$con);
while ($row = mysql_fetch_assoc($data)) {
echo json_encode($row);
}
}
function result()
{
}
?>
But i want to get response from one method [ie. from response()].
How can this be done?
You could include a selector in the ajax request data. Like this for example:
$(document).on('click','#Quote_create_value',function(){
$.ajax({
type : 'GET',
url : '../../../protected/config/ajax.php',
data: "function=result",
success : function(response){
$("#Quote_template_value").html(response);
}
});
});
Then in your PHP code, a simple if-statement will check which one to output.
if(isset($_GET['function'])) {
if($_GET['result'] == 'result') {
// do result stuff
} elseif($_GET['function'] == 'response') {
// do response stuff
}
}
The javascript parameter "Step" should trigger a switch-case function in php. If Step is one than trigger this piece of code in php and return the output by JSON.
If I take a look in firebug the post string is: Step=one&inputFname=rick&inputLname=bovenkamp I think this is correct. So the problem must be in the php file and I think it's in the $_POST part...
What am I doing wrong? Any help would be very great!
javascript code:
$(document).ready(function() {
$("form#userForm").submit(function() {
var inputFname = $('#inputFname').attr('value');
var inputLname = $('#inputLname').attr('value');
var Step = "one";
$.ajax({
type: "POST",
url: "main.php",
data: {Step: Step,inputFname: inputFname,inputLname: inputLname},
dataType: "json",
contentType:"application/json; charset=utf-8",
success: function(data) {
$("p.succesText").html(data.jsCode);
$("form#userForm").hide();
$("div.success").fadeIn();
},
error: function(xhr, status, error) {
$("form#userForm").hide();
$("p.errorHead").html("Something went wrong.");
$("p.errorText").text("ResponseText: " + xhr.responseText
+ "Statuscode: " + xhr.status
+ "ReadyState: " + xhr.readyState);
$("div.error").fadeIn();
}
});
return false;
});
});
PHP file:
<?php header('content-type: application/json; charset=utf-8');
$log = array();
$varStep = htmlspecialchars(trim($_POST["Step"]));
switch($varStep) {
case "one":
$varFname = htmlspecialchars($_POST["inputFname"]);
$varLname = htmlspecialchars($_POST["inputLname"]);
//Make Database connection
$db = mysql_connect("192.168.178.254","root","852456");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("Ajax" ,$db);
//Generate code and check if code already exists in the database
do
{
$varCode = rand(10000, 99999);
$dbCheckCode = "";
$dbCheckCode = mysql_query("SELECT * FROM TableAjax WHERE code='$varCode'");
}
while (mysql_fetch_array($dbCheckCode) !== false);
//Save the Form data in the database
$sql = "INSERT INTO TableAjax (fname, lname, code) VALUES (".PrepSQL($varFname) . ", " .PrepSQL($varLname) . ", " .PrepSQL($varCode) . ")";
mysql_query($sql);
//Return code to frontend
$log['jsCode'] = $varCode;
break;
}
echo json_encode($log);
//Clean SQL statement
function PrepSQL($value)
{
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
Put Step in quotes data : {"Step" : Step,....
You are passing the value of the variable as the key in that case, that is to say you are actually passing data : {"one" : "one",.... You should do the same with inputLname and inputFname.
Edit - Explanation
If you look at what the contentType options does here at http://api.jquery.com/jQuery.ajax/, you will see that the default is application/x-www-form-urlencoded which is what you want. Essentially what your PHP error was indicating is that the $_POST array was empty because it did not know how to read your data due to the format. You want your return data to be json, the dataType option was all you needed.
You still would have needed to do what I indicated in the first part of the post, but essentially you had two errors that were tripping you up.
I hope this makes sense!
I am trying to pass some values to my PHP page and return JSON but for some reason I am getting the error "Unknown error parsererror". Below is my code. Note that if I alert the params I get the correct value.
function displaybookmarks()
{
var bookmarks = new String();
for(var i=0;i<window.localStorage.length;i++)
{
var keyName = window.localStorage.key(i);
var value = window.localStorage.getItem(keyName);
bookmarks = bookmarks+" "+value;
}
getbookmarks(bookmarks);
}
function getbookmarks(bookmarks){
//var surl = "http://www.webapp-testing.com/includes/getbookmarks.php";
var surl = "http://localhost/Outlish Online/includes/getbookmarks.php";
var id = 1;
$.ajax({
type: "GET",
url: surl,
data: "&Bookmarks="+bookmarks,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "getbookmarkscallback",
crossDomain: "true",
success: function(response) {
alert("Success");
},
error: function (xhr, status) {
alert('Unknown error ' + status);
}
});
}
function getbookmarkscallback(rtndata)
{
$('#pagetitle').html("Favourites");
var data = "<ul class='table-view table-action'>";
for(j=0;j<window.localStorage.length;j++)
{
data = data + "<li>" + rtndata[j].title + "</li>";
}
data = data + "</ul>";
$('#listarticles').html(data);
}
Below is my PHP page:
<?php
$id = $_REQUEST['Bookmarks'];
$articles = explode(" ", $id);
$link = mysql_connect("localhost","root","") or die('Could not connect to mysql server' . mysql_error());
mysql_select_db('joomla15',$link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT * FROM jos_content where id='$articles[$i]'";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
for($i = 0; $i < count($articles); $i++)
{
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = $post;
}
}
}
header('Content-type: application/json');
echo $_GET['onJSONPLoad']. '('. json_encode($posts) . ')';
#mysql_close($link);
?>
Any idea why I am getting this error?
This is not json
"&Bookmarks="+bookmarks,
You're not sending JSON to the server in your $.ajax(). You need to change your code to this:
$.ajax({
...
data: {
Bookmarks: bookmarks
},
...
});
Only then will $_REQUEST['Bookmarks'] have your id.
As a sidenote, you should not use alert() in your jQuery for debugging. Instead, use console.log(), which can take multiple, comma-separated values. Modern browsers like Chrome have a console that makes debugging far simpler.
Trying to pass data to the server but it keeps returning a "Parameter Missing"
So either the data is not being passed to the PHP script or I am doing something wrong.
Here is the jQuery:
function quickJob(obj) {
var quickJobNumber = $(obj).text();
//alert(quickJobNumber)
$.ajax({
type: "GET",
url: "quickJobCB.php",
data: quickJobNumber,
success: function(server_response)
{
$("#message").removeClass().html(server_response);
}
});
}
Ok....when tracing the issue I created an alert as seen below. The alert is producing the expected results.
Here is the PHP script:
<?php
require_once("models/config.php");
// Make the connection:
$dbc = #mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if (isset($_GET['quickJobNumber'])) {
$quickJobNumber = trim($_GET['quickJobNumber']);
$quickJobNumber = mysqli_real_escape_string($dbc, $quickJobNumber);
$query = "SELECT * FROM projects WHERE projectNumber = '" . $quickJobNumber . "'";
$result = mysqli_query($dbc, $query);
if ($result) {
if (mysqli_affected_rows($dbc) != 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo $row['projectName'];
}
} else {
echo 'No Results for :"' . $_GET['quickJobNumber'] . '"';
}
}
} else {
echo 'Parameter Missing';
}
?>
<?php include("models/clean_up.php"); ?>
data: quickJobNumber,
should be
data: { 'quickJobNumber': quickJobNumber },
You'll need to pass the data either as a query string like so
data: "quickJobNumber="+quickJobNumber,
or a map like so
data: data { quickJobNumber: quickJobNumber },
If you want to use the GET request, use $.get
$.get("/get_request.php", { quickJobNumber: "myAjaxTestMessage"},
function(data){
console.log("WOW! Server was answer: " + data);
});
In php
<?php
if(isset($_GET['quickJobNumber'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('answer'=>'Hello user!'));
}
?>
If you want to use the POST request, use $.post
$.post("/post_request.php", { quickJobNumber: "myAjaxTestMessage"},
function(data){
console.log("WOW! Server was answer: " + data);
});
In php
<?php
if(isset($_POST['quickJobNumber'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('answer'=>'Hello user!'));
}
?>
P.S. or you can use $_REQUEST in php.