I'm running into an issue where the JSON returned from a PHP query is not valid and I'm not really sure why; I'm still learning. When the datatype is excluded the below code returns:
{"Customer_ID":"0", "FirstName":"John", "LastName":"Smith"}
{"Customer_ID":"1", "FirstName":"Jane", "LastName":"Smith"}
otherwise it returns:
SyntaxError: "JSON.parse: unexpected non-whitespace character after ..."
I thought this might be because the record is not being returned in a single JSON response, but I can't see that being the issue as the concurrent responses are JSON. Any ideas? Any suggests? Feel free to point out the semantic issues.
HTML:
getRecord("*", "customer", "");
JavaScript:
function getRecord(field, table, condition) {
var request = $.ajax({
url: "./handler.php",
method: "GET",
dataType: "JSON",
cache: "false",
data: {
action: "SELECT",
field: `${field}`,
table: `${table}`,
condition: `${condition}`,
},
});
request.done(function(data, status, xhr) {
console.log(data, status, xhr);
});
request.fail(function(xhr, status, error) {
console.log(xhr, status, error);
});
};
PHP:
<?php
# IMPORT SETTINGS.
include "settings.php";
# FUNCTION DISPATCHER.
switch($_REQUEST["action"]) {
case "SELECT":
getRecord($conn);
break;
default:
printf('Connection Error: Access Denied.');
mysqli_close($conn);
}
# LIST OF COLUMNS THAT WE NEED.
function getRecord($conn) {
$table = $_REQUEST["table"];
$field = $_REQUEST["field"];
$condition = $_REQUEST["condition"];
if (!empty($condition)) {
$query = "SELECT $field FROM $table WHERE $condition";
} else {
$query = "SELECT $field FROM $table";
}
if ($result = mysqli_query($conn, $query)) {
while ($record = mysqli_fetch_assoc($result)) {
echo json_encode($record);
}
}
# CLOSE THE CONNECTION.
mysqli_close($conn);
}
?>
Your JSON is not valid because it consists of multiple objects. What you need to do is put all your results into an array and then echo the json_encode of that. Try something like this:
$records = array();
if ($result = mysqli_query($conn, $query)) {
while ($records[] = mysqli_fetch_assoc($result)) {
}
}
echo json_encode($records);
This will give you an output that looks something like this:
[
{"Customer_ID":"0", "FirstName":"John", "LastName":"Smith"},
{"Customer_ID":"1", "FirstName":"Jane", "LastName":"Smith"}
]
and you can access each of the elements in your Javascript by something like
let customer = data[0].FirstName + ' ' + data[0].LastName;
Related
I have an AJAX call that makes my JSON look this in my JSON file:
{
"main_object": {
"id": "new",
"formData": "language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"
}
}
But I would like to have it like this (and this was before I changed my AJAX call with: id: getUrlParameter('id'):
{
"main_object": {
"language": "nl_NL",
"getExerciseTitle": "asd",
"question_takeAudio_exerciseWord": ["asd"],
"Syllablescounter": ["ASDasd", ""]
}
}
The only thing I want to add is the "id": "new", but when I do so (with id: getUrlParameter('id') it gets the id, but it messes up my code.
This is my AJAX call (my JSON starts looking like the first piece of code when I use this)
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
formData: $('#my_form').serialize()
},
dataType: 'json',
}).done(function(response) {
});
});
}
How could this be achieved? I know it isn't my saveJson.php that's the problem. I know it's my AJAX call since it starts showing like the first JSON piece of code when I add the id: getUrlParameter('id').
edit: Since someone said it could be my php code.. here is my php code:
<?php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData['main_object'] = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} // ending database['data'] count 0.
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
} // ending the max ID else statement.
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} // } op regel 34 lijkt verdwaald...?
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $data['id'],
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
} // closing off the else statement
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
} //closing off the if isset.
?>
you can use parse_str($str, $output); it will help you achieve what you need.
Note that parse_str takes two parameters, the first one is the string (get Parameters), second one is the array to return the result on. you can use the below code
parse_str($str, $output);
echo json_encode($output);
The issue is how you process formData parameter. serialize() is building url encoded string, however you want key-value pairs. Try this:
$("#my_form").on("submit", function(event) {
event.preventDefault();
var myData = {id: getUrlParameter('id')};
for (var pair of formData.entries()) {
myData[pair[0]] = pair[1];
}
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: myData,
dataType: 'json',
}).done(function(response) {
window.location = 'index.php';
});
});
}
My ajax function goes in error after I set the dataType to Json.
That's the code:
Ajax script:
$('#da').on("change",function() {
$.ajax({
url: "callAjaxIndex.php",
type: "POST",
dataType: "json",
data: {
method: 1,
id: $('#da').val(),
},
success: function() {
alert('test');
},
error: function() {
alert('error');
}
});
});
callAjaxIndex.php
<?PHP
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as 'nome_arrivo', tratte.id as 'id_arrivo' FROM tariffe, tratte WHERE id_arrivo = tratte.id AND id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
?>
What's wrong?
Thank you
You can try this
$(document).on('change', '#da', function(){
$.post("callAjaxIndex.php", {'method': 1, 'id': $(this).val()}, function(data){
var d = $.parseJSON(data); //here is the data parsed as JSON
//data is that returned from callAjaxIndex.php file
});
});
<?php
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as nome_arrivo, tratte.id as id_arrivo FROM tariffe INNER JOIN tratte ON id_arrivo = tratte.id WHERE id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
You can find out the error by changing your function to this:
//other code
error: function(data)
{
console.log(data.responseText)
}
//other code
This will tell you why it fails, might be something generic but better than 'error'
Also note:
this was done from a phone so excuse any mistakes
I'd rather this be treated as a comment until I can get to a machine to help more :)
So I have a js file that posts a JSON object using $.ajax, and then my php script takes that JSON object and does stuff to it, however, i can't get a json response back from the php script (the success callback function never runs).
register_script.js:
$.ajax({
method: "post",
dataType: "json",
url: "http://localhost/login/webservices/register2.php",
data: {
reg_username: username,
email: email,
reg_password: password,
confirm_password: confirm_pass
},
success: function (data) {
alert("hello?");
//alert(data.status);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("Post error: " + errorThrown);
});
register2.php:
if (isset($_POST['reg_username'], $_POST['email'], $_POST['reg_password'], $_POST['confirm_password'])) {
$username = $_POST['reg_username']; //$_POST['from html']
$email = $_POST['email'];
$password = hash('md5', ($_POST['reg_password']));
$confirm_password2 = hash('md5', ($_POST['confirm_password']));
$sql = "INSERT INTO users (username, email, password) VALUES ('$username','$email','$password')";
if ($password == $confirm_password2) {
$response = sqlsrv_query($conn, $sql);
if ($response) {
$data = array(
"username" => $username,
"email" => $email,
"password" => $password,
"confirmPass" => $confirm_password2,
"status" => "Registered",
);
echo "Registered \n";
}
}
}
//...
//some other validations
//...
echo json_encode($data);
I have a feeling the way i am handling the json object is incorrect. any help would be really appreciated.
you should not
echo
anything other than json_encode when working with ajax dataType : json you have
echo "Registered \n";
before
echo json_encode
remove that and it should work
EDIT:
when you set the dataType : "json" in your ajax call then the response is expected to be in json when the call is finished, and any text other than json encoded string in response will result in an error. if you still need to debug and see what route the script is taking, you can add another index in $data (i assume that $data is an array), so it would be like
if($registered){
$data['debug_logs'] .='Registration successfull----';
}
if($emailSent){
$data['debug_logs'].='Email sent for registration-----';
}
echo json_encode($data);
and then in your ajax success function you can use it like
success:function(data){
console.log(data.debug_logs);
}
hope it clears your confusion.
Please remove echo "Registered \n"; the line from your code when you echo "Register"; the Ajax request return this back to the browser, and your actual data echo json_encode($data); never return back to the browser.
I've been trying to post data using AJAX that will update a field in my database however I am having trouble doing so. Everything seems like it should run fine and I get no errors in the console but I've no idea why my db won't update.
Can someone help me out here please?
AJAX:
function ajaxUpdate() {
var arr = {var1: name, var2: age};
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data) {
console.log("success");
}
});
}
Confirm.php:
$name=$_POST['var1'];
$age=$_POST['var2'];
if($name == "Stuart") {
mysqli_query($connection,"UPDATE people SET age='$age'");
}
else if($name == "Peter") {
mysqli_query($connection,"UPDATE people SET age='$age'");
}
The connection to my database is working as I have $connection setup and went to the page /ajax/confirm.php in my browser and I see "Connection successful" in my console as I defined if successful.
So I am unsure as to why this isn't updating?
Are my values not being posted correctly?
I'm new to AJAX so forgive me if this is something very simple!
Thanks
Try the following:
function ajaxUpdate() {
var arr = {var1: name, var2: age};
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: arr,
success: function(data) {
console.log("success");
}
});
}
Instead of converting the object into json string send it as is.
Edit: Also remove dataType and probably contentType too. Your code is at risk of SQL Injection. Look into prepared statements and escaping mysql data.
Maybe this well help.
<script type="text/javascript">
function ajaxUpdate() {
var data = $('#formID').serialize();
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: data,
dataType: 'json',
encode : true,
success: function(data) {
if(data == "ok"){
console.log("success");
}else{
console.log(data);
}
}
});
}
</script>
confirm.php
<?php
$name = $_POST['name'];
$age = $_POST['age'];
switch ($name) {
case 'Stuart':
$sql = "UPDATE people SET age = ? WHERE name = ? ";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'si', $name, $age);
if (mysqli_stmt_execute($stmt)) {
echo json_encode('ok');
} else {
echo json_encode(mysqli_stmt_error($stmt));
}
break;
case 'Peter':
$sql = "UPDATE people SET age = ? WHERE name = ? ";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'si', $name, $age);
if (mysqli_stmt_execute($stmt)) {
echo json_encode('ok');
} else {
echo json_encode(mysqli_stmt_error($stmt));
}
break;
default:
echo json_encode('Unknown name ');
}
I use this jQuery function to get data through Ajax:
function addContentPrt(cid){
$.ajax({
url: "<?=parseLink('addContent.php')?>",
type: "POST",
cache: true,
dataType:'json',
data: {id: cid},
success: function(returnedData){
console.log(returnedData);
},
error: function (xhr, tst, err) {
console.log(err);
}
});
}
and on the receiving end:
<?
header("Content-Type: application/json", true);
if(isset($_POST['id'])) {
$id = $_POST['id'];
}
$sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id");
$r = mysql_fetch_array($sql);
echo $r['title'];
echo $id;
?>
the echo $id does return to ajax, but not $r['title'], with that it goes null in console. If I add some dummy text like hello world, I get a synthax error SyntaxError: Unexpected token h {stack: (...), message: "Unexpected token h"}
What could be the cause of this and what could I do to fix it?
<?
header("Content-Type: application/json", true);
if(isset($_POST['id'])) {
$id = $_POST['id'];
}
$sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id");
$r = mysql_fetch_array($sql);
echo json_encode('id' => $id, 'title' => $r['title']);
?>
and in your ajax success:
success: function(returnedData){
console.log(JSON.parse(returnedData));
},
In the ajax, you specified the datatype as json which is the format expecting from the server, So in order to get a result, you need to return the json result from the server. Either by using json_encode($r) where $r can be any array.
return json_encode($r); then you can read variable $r in sucess