I have tried to echo my json into my html page with php, but it only prints in console or gives back an error.
I'm pretty new to this so please help.
this is the javascript with fetch and activated onclick to submit one to php
async function hey(){
let click = 1;
await fetch('data.php',{
method: 'POST',
header: {
'Content-Type': 'application/json',
},
body: JSON.stringify(click),
}).then(response => response.json())
.then(data => {
console.log(data);
})
.catch((error) => {
console.error(error);
});}
this is the php but it will only ever print to the console
<?php
$json = file_get_contents('php://input');
echo $json;
?>
let's decripte what you were doing:
first thing first, the way you are calling your method:
async function hey(){
let click = 1;
await fetch('data.php',{
...
}
if you want to return the value of the json through your function, well you have to return it. I think you are expected to get it from the method, so you cound change to:
async function hey(){
let click = 1;
return await fetch('data.php',{
...
}
like this your function is actually returning something. If you expected it from returning through the invocation from then(), it won't work, it is one scope deeper.
I think the fetch part is ok, so I jump directly to the then() part, that actually looks like :
.then(response => response.json())
.then(data => {
console.log(data);
....
I believe that you don't need 2 call to the then() method here. You could simply do:
then(response => return response.json())
I didn't try it, but i don't think you need to call the json method, because you are already sending a json. But to do that you would need to include in php the headers needed to precise it, because php doesnt know you are sending a json and will probably do something else. So your php script should looks like:
<?php
header('Content-Type: application/json; charset=utf-8');
$json = file_get_contents('php://input');
echo $json;
cheers
I am trying to send data from user end to server end: positionList.html <=> dbUpdate.php
issue seen on the developer console
The data format I am going to send is an array of self-defined Javascript objects. Here's one example: [{"position":"code testing","description":"junior"},{"position":"front end developing","description":"junior"}].
There are two objects in the array above, and each one is a self-defined JS object. The object definition is stated below, it has two properties:
function Entry(inpt1, inpt2) {
this.position = inpt1;
this.description = inpt2;
}
And then I used JSON.stringify method (JS array to JSON string) before $.post to the back end. msgPack is the array with two self-defined JS objects in it. From the developer tool, I could see the JSON string looks normal and the data I received back from the server was a JS string. But console.log(data) doesn't show anything and JSON.parse(data) reports an error.
let myJson = JSON.stringify(msgPack);
let url = "dbUpdate.php";
$.post(url, myJson, function(data){
console.log("getting data back...");
console.log('type of data is: ' + typeof(data));
console.log("data: " + data);
alert(JSON.parse(data));
});
The server side's code is listed below:
<?php
require_once 'pdo.php';
$data = isset($_POST)? $_POST:'nothing here';
foreach($data as $obj) {
echo( json_encode($obj['position']));
}
/*
foreach($data as $obj) {
foreach($obj as $k => $v) {
echo "json_encode({$k} => {$v})";
}
}
*/
?>
I tried several ways to extract the data from the front-end, but it seems the data was not recognized.
var_dump, print_r didn't help either.
My questions are:
Any suggestions regarding the AJAX communication? Is the problem happening at the back-end side? It couldn't get any information from $_POST.
How does PHP back-end know there's a message coming and what methods do we developer have to check that Other than isset($_POST)? My concern is the front-end could send multiple data with different contents.
Thanks.
You can directly send array in the post request by setting it to a key positions and access it in backend via same key. Make sure you send json back so the front end also do a parsing.
let myData = { positions: msgPack};
let url = "dbUpdate.php";
$.post(url, myData, function(data){
console.log("getting data back...");
console.log('type of data is: ' + typeof(data));
console.log("data: " + data);
alert(JSON.parse(data));
});
While in php
<?php
require_once 'pdo.php';
if(isset($_POST['positions'])){
echo json_encode($_POST['positions']); die;
}
else{
$response = [ 'error' => 'No input specified'];
echo json_encode($response); die;
}
?>
In my controller I handle POST requests with ajax and adds data from GET requests directly to the js-code
mycontroller.php
$sServiceNumber = isset($_POST['ServiceNumber']) ? $_POST['ServiceNumber'] : $_GET['ServiceNumber'];
//Here I do a db call for sServiceNumber and fetch some data as array $aAllrows
$aResponse['ServiceNumber'] = $sServiceNumber;
$aResponse['Data'] = $aAllrows;
$sJson = json_encode(self::convertToStrictUtf8($aResponse));
if (isset($_POST['ServiceNumber'])) {
echo $sJson;
exit;
} else {
$sJs = '
$(document).ready(function() {
var sData = \'' . $sJson . '\';
handleResponseData(sData);
});';
MyHtmlHead::addExtraJsCode($sJs);
//continue with rendering html page here..
}
When I call this with ajax everything works fine but when I try to run handleResponseData() directly I get Uncaught SyntaxError: Unexpected token on special characters.
My JavaScript
function handleResponseData ( rawData ) {
response = jQuery.parseJSON(rawData); //<--this is where the error occurs (on GET requests)
//Make use of response data
}
$("form[name='searchform']").submit(function( event ) {
event.preventDefault();
// Send post and fetch some data!
$.post(baseUrl, { ServiceNumber: $("input[name='ServiceNumber']").val(), time: "2pm" }).done(handleResponseData);
});
Lastly here comes my conversion method
protected static function convertToStrictUtf8 ($p_aValues) {
function detectEncoding(&$mValue) {
if (!mb_detect_encoding($mValue, 'UTF-8', true)) {
$mValue = utf8_encode($mValue);
}
}
array_walk_recursive($p_aValues, 'detectEncoding');
return $p_aValues;
}
How come the json string parses fine when fetched with jquery $.post but not when embedded into code manually? How do I solve this issue?
edit:
Stripped down version of rawData from console.log(rawData)
GET
{"ServiceNumber":"485218-1138932068","Data":[{"RowId":"AEEA-IU3A61","ServiceRequestId":"AEEA-IU39LX","Name":"SV LIDEHÄLL)","FileSize":"8812","ServiceNumber":"485218-1138932068","Subject":"O(BERGMAN/LIDEHÄLL)
","Area":"svrT","Dir":"1702"}]}
POST
{"ServiceNumber":"485218-1138932068","Data":[{"RowId":"AEEA-IU3A61","ServiceRequestId":"AEEA-IU39LX","Name":"SV LIDEH\u00c4LL)","FileSize":"8812","ServiceNumber":"485218-1138932068","Subject":"O(BERGMAN\/LIDEH\u00c4LL)\r\n","Area":"svrT","Dir":"1702"}]}
The problem was caused by Line breaks .
As the jQuery.parseJSON() docs states: "control characters" such as a tab or newline is not allowed.
When calling with $.post the new line chars were converted to a string "\r\n" which is why that case was working.
Adding something like this to remove new lines finally solved it.
function stripNewLines(&$mValue) {
if(is_string($mValue)) {
$mValue = trim(preg_replace('/\s+/', ' ', $mValue));
}
}
array_walk_recursive($aResponse, 'stripNewLines');
In your PHP controller, before echo JSON respose type the following line
header("Content-Type: application/json");
and also in jQuery Ajax call you need to mention data type as JSON
$.ajax({
...,
...,
dataType: 'JSON', // it is necessary to get JSON response
...
});
I've spend over 6 hours to find an exception or a special character to find in my code but I couldn't. I checked every similar messages in here.
I'm sending the form with magnific popup. First I'm using inline popup to open my form than I'm sending all inputs to main.js to validate.
So, I just need a third-eye.
I've got: index.html, register.php, main.js
Here's the code
FORM
JS/AJAX
PHP-register.php
Here goes the error messages
JSON Output
Chrome Console:
Firefox console :
What am i missing?
For the benefit of searchers looking to solve a similar problem, you can get a similar error if your input is an empty string.
e.g.
var d = "";
var json = JSON.parse(d);
or if you are using AngularJS
var d = "";
var json = angular.fromJson(d);
In chrome it resulted in 'Uncaught SyntaxError: Unexpected end of input', but Firebug showed it as 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'.
Sure most people won't be caught out by this, but I hadn't protected the method and it resulted in this error.
The fact the character is a < make me think you have a PHP error, have you tried echoing all errors.
Since I don't have your database, I'm going through your code trying to find errors, so far, I've updated your JS file
$("#register-form").submit(function (event) {
var entrance = $(this).find('input[name="IsValid"]').val();
var password = $(this).find('input[name="objPassword"]').val();
var namesurname = $(this).find('input[name="objNameSurname"]').val();
var email = $(this).find('input[name="objEmail"]').val();
var gsm = $(this).find('input[name="objGsm"]').val();
var adres = $(this).find('input[name="objAddress"]').val();
var termsOk = $(this).find('input[name="objAcceptTerms"]').val();
var formURL = $(this).attr("action");
if (request) {
request.abort(); // cancel if any process on pending
}
var postData = {
"objAskGrant": entrance,
"objPass": password,
"objNameSurname": namesurname,
"objEmail": email,
"objGsm": parseInt(gsm),
"objAdres": adres,
"objTerms": termsOk
};
$.post(formURL,postData,function(data,status){
console.log("Data: " + data + "\nStatus: " + status);
});
event.preventDefault();
});
PHP Edit:
if (isset($_POST)) {
$fValid = clear($_POST['objAskGrant']);
$fTerms = clear($_POST['objTerms']);
if ($fValid) {
$fPass = clear($_POST['objPass']);
$fNameSurname = clear($_POST['objNameSurname']);
$fMail = clear($_POST['objEmail']);
$fGsm = clear(int($_POST['objGsm']));
$fAddress = clear($_POST['objAdres']);
$UserIpAddress = "hidden";
$UserCityLocation = "hidden";
$UserCountry = "hidden";
$DateTime = new DateTime();
$result = $date->format('d-m-Y-H:i:s');
$krr = explode('-', $result);
$resultDateTime = implode("", $krr);
$data = array('error' => 'Yükleme Sırasında Hata Oluştu');
$kayit = "INSERT INTO tbl_Records(UserNameSurname, UserMail, UserGsm, UserAddress, DateAdded, UserIp, UserCityLocation, UserCountry, IsChecked, GivenPasscode) VALUES ('$fNameSurname', '$fMail', '$fGsm', '$fAddress', '$resultDateTime', '$UserIpAddress', '$UserCityLocation', '$UserCountry', '$fTerms', '$fPass')";
$retval = mysql_query( $kayit, $conn ); // Update with you connection details
if ($retval) {
$data = array('success' => 'Register Completed', 'postData' => $_POST);
}
} // valid ends
}echo json_encode($data);
Remove
dataType: 'json'
replacing it with
dataType: 'text'
I have the exact same issue and I've found something.
I've commented the line :
dataType : 'json',
after that it was successful but... when I did console.log(data) it returned the main index.html.
That's why you have "Unexpected token <" error and it cannot parse.
Changing the data type to text helped
dataType: 'text'
I have check with JSONlint and my json format was proper. Still it was throwing error when I set dataType: 'json'
JSON Data: {"eventinvite":1,"groupcount":8,"totalMessagesUnread":0,"unreadmessages":{"378":0,"379":0,"380":0,"385":0,"390":0,"393":0,"413":0,"418":0}}
Are you sure you are not using a wrong path in the url field? - I was facing the same error, and the problem was solved after I checked the path, found it wrong and replaced it with the right one.
Make sure that the URL you are specifying is correct for the AJAX request and that the file exists.
Sending JSON data with NodeJS on AJAX call :
$.ajax({
url: '/listClientsNames',
type: 'POST',
dataType: 'json',
data: JSON.stringify({foo:'bar'})
}).done(function(response){
console.log("response :: "+response[0].nom);
});
Be aware of removing white spaces.
app.post("/listClientsNames", function(req,res){
var querySQL = "SELECT id, nom FROM clients";
var data = new Array();
var execQuery = connection.query(querySQL, function(err, rows, fields){
if(!err){
for(var i=0; i<25; i++){
data.push({"nom":rows[i].nom});
}
res.contentType('application/json');
res.json(data);
}else{
console.log("[SQL005] - Une erreur est survenue");
}
});
});
I have got same Error while fetch data from json filesee attached link
"SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"
So, i check the path of the json file which isn't correct,
const search = document.getElementById("search");
const matchList = document.getElementById("match-list");
//search json data and filter
const searchStates = async searchText => {
const res = await fetch('../state.json');
const states = await res.json();
console.log(states);
}
search.addEventListener('input', () => searchStates(search.value));
so that i changed the path of the file
const res = await fetch('./state.json');
& it gives me array back as a result.
so, check your path & try changed it. It will work in my case. I hope that's works..
JSON.parse() doesn't recognize That data as string. For example {objAskGrant:"Yes",objPass:"asdfasdf",objNameSurname:"asdfasdf adfasdf",objEmail:"asdfaf#asdfaf.com",objGsm:3241234123,objAdres:"asdfasdf",objTerms:"CheckIsValid"}
Which is like this: JSON.parse({objAskGrant:"Yes",objPass:"asdfasdf",objNameSurname:"asdfasdf adfasdf",objEmail:"asdfaf#asdfaf.com",objGsm:3241234123,objAdres:"asdfasdf",objTerms:"CheckIsValid"}); That will output SyntaxError: missing " ' " instead of "{" on line...
So correctly wrap all data like this: '{"objAskGrant":"Yes","objPass":"asdfasdf","objNameSurname":"asdfasdf adfasdf","objEmail":"asdfaf#asdfaf.com","objGsm":3241234123,"objAdres":"asdfasdf","objTerms":"CheckIsValid"}' Which works perfectly well for me.
And not like this: "{"objAskGrant":"Yes","objPass":"asdfasdf","objNameSurname":"asdfasdf adfasdf","objEmail":"asdfaf#asdfaf.com","objGsm":3241234123,"objAdres":"asdfasdf","objTerms":"CheckIsValid"}" Which give the present error you are experiencing.
Even if your JSON is ok it could be DB charset (UTF8) problem. If your DB's charset/collation are UTF8 but PDO isn't set up properly (charset/workaround missing) some à / è / ò / ì / etc. in your DB could break your JSON encoding (still encoded but causing parsing issues). Check your connection string, it should be similar to one of these:
$pdo = new PDO('mysql:host=hostname;dbname=DBname;**charset=utf8**','username','password'); // PHP >= 5.3.6
$pdo = new PDO('mysql:host=hostname;dbname=DBname','username','password',**array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")**); // older versions
P.S. Outdated but still could be helpful for people who're stuck with "unexpected character".
May be its irrelevant answer but its working in my case...don't know what was wrong on my server...I just enable error log on Ubuntu 16.04 server.
//For PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);
When the result is success but you get the "<" character, it means that some PHP error is returned.
If you want to see all message, you could get the result as a success response getting by the following:
success: function(response){
var out = "";
for(var i = 0; i < response.length; i++) {
out += response[i];
}
alert(out) ;
},
In some cases data was not encoded into JSON format, so you need to encode it first e.g
json_encode($data);
Later you will use json Parse in your JS, like
JSON.parse(data);
Try using MYSQLI_ASSOC instead MYSQL_ASSOC... usually the problem is solved changing that
Good luck!
I had the same error in an AJAX call in an app with pagination and or in any case with a query string in the URL
since AJAX was posting to something like
var url = window.location.href + 'search.php';
...
...
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({search: text}),
})
as soon in the browser URL was added some query string, the error "JSON.parse: unexpected character at line 1 column 1" was popping
the solution has been to simply clean the URL from any query string with
var url = window.location.href.split('?')[0] + 'search.php';
and issue got fixed
So, the error was not the formatting of the Json, instead it was a wrong URL for the POST
#Prahlad is on to something here. I've been seeing this thing for years and it just became background noise to me.
Recently I was doing some brand new stuff and I realized I was seeing that in my console (FF 98.0 (64-bit)) on Mac (12.2.1 (21D62)) where the html is being served by a local NGNIX install (nginx/1.21.6)
Here is the html being served, in it's entirety:
<!doctype html>
<html lang="en">
<head>
</head>
<body>
Some text
</body>
</html>
Now... I don't have a clue why it is happening, but I'm pretty sure it's not the code :-)
I was getting similar error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data".
It turns out I was sending data from the backend in JSON format already, so when it arrives on the front-end, I shouldn't use JSON.parse at all:
$.ajax({
type: "get",
url: 'https://localhost:8080/?id='+id,
success: function (response) { // <- response is already JSON
var data = $.parseJSON(response); // <- I removed this line
modalShow(data); // <- modalShow(response) now works!
}
});