HTML sends message to PHP back-end and check the response - javascript

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;
}
?>

Related

I need to get the json STRIPE API data converted into php

I need help converting some json data into a php array. I am using the STRIPE API. It is first inputted into a javascript array
// The items the customer wants to buy
var purchase = {
items: [{ id: 2235 }]
};
Then ajaxed like so
fetch("create.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(purchase)
})
on the server side (php)
header('Content-Type: application/json');
try {
// retrieve JSON from POST body
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
//echo $json_obj;
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => calculateOrderAmount($json_obj->items),
'currency' => 'usd',
]);
$output = [
'clientSecret' => $paymentIntent->client_secret,
];
echo json_encode($output);
} catch (Error $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
Where I get into trouble is the calculateOrderAmount function. The function looks like so (the return is just hard coded for now but I will replace with an amount)
function calculateOrderAmount(array $items): int {
// I need to loop through the array and break out the
// product ids
return 1400;
}
For the life of me I cannot figure out how to loop through the array and get the id value. I intend on looping through the array id, getting the values from my mySQL database and returning it.
Can anyone give me an idea of what to do?
I recommend changing your json_decode() call to include the second argument, which specifies if the JSON will be decoded to a PHP object (false) or an associative array (true), like so:
$json_obj = json_decode($json_str, false);
This way you're not depending on the JSON_OBJECT_AS_ARRAY flag setting to determine if you get an object or an array when decoding JSON.
Next, inside calculateOrderAmount(), you can do something like this:
foreach($items as $item) {
// Do something with $item->id
}

SyntaxError: Unexpected token < in JSON at position 0 ajax php

I'm building a website using PHP & Ajax.
I can't fetch data.
I constantly get "SyntaxError: Unexpected token < in JSON at position 0 "
However, the data is sent to my database successfully and there're no errors in the network.
Ajax file:
document.getElementById("btnSendPrivateMessage").addEventListener("click", function (e) {
e.preventDefault();
let chatId = this.dataset.chatid;
let text = document.querySelector('#privateMessageText').value;
console.log(chatId);
console.log(text);
//sent to DB
let formData = new FormData();
formData.append("text_message", text);
formData.append("chat_id", chatId);
fetch("ajax/saveMessage.php", {
method: "POST",
body: formData
})
.then(response => response.json())
.then(result => {
console.log("Success:", result);
})
.catch(error => {
console.error("Error:", error);
});
});
PHP file with json_encode
<?php
require("../classes/Db.class.php");
require("../classes/ChatPrivateMessage.class.php");
require("../datetime.php");
session_start();
if(!empty($_POST)){
header("Content-type: application/json");
$m = new ChatPrivateMessage();
$m->setChatId($_POST['chat_id']);
$m->setText($_POST['text_message']);
$m->setUser1($_SESSION['user_id']);
$m->setDate(getTime());
$textM = htmlspecialchars($m->getText()) ;
$m->saveMessage();
$response = [
"status" => "success",
"body" => $textM,
"message" => "something"
];
header("Content-type:application/json");
echo json_encode($response);
};
?>
It seems like server doesn't respond with JSON but with HTML (maybe it responds with HTML page describing the error occurred). Check what the backend response is exactly.
for friends who want to check up-to-date, if there is any HTML code information on the page where you are processing the code, it reads the information sent from ajax but returns an error. Therefore, there should not be any HTML code on the processed page. Otherwise you will get an error. Note that the page is purely php codes. This way my problem was fixed. It is very simple and requires attention.

AJAX POSTing to PHP isn't working

I am trying to POST a JSON to PHP where it should be decoded and pushed to MySQL database.
This is my JavaScript code.
var dictstring = "{sensorid: \""+ name +"\", x: " +pos.x +" ,y: "+pos.y+"}";
console.log(dictstring);
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
url: "myfile.php",
data: JSON.stringify(dictstring),
success: function(data){
alert('Success');
},
error: function(e){
console.log(e.message);
}
});
And this is my PHP code
<?php
$jsonData = file_get_contents('php://input');
$data_back = json_decode($jsonData);
$unit = $data_back->{"sensorid"};
$x_axis = $data_back->{"x"};
$y_axis = $data_back->{"y"};
// Create connection
$con=mysqli_connect("xxxxxxx:xxxx","xxxxx","xxxx","xxxxxxxx");
// Check
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Insert Values
$sql_hm = "INSERT INTO xxxx(unit, x_axis, y_axis)
VALUES ('$unit', $x_axis, $y_axis)";
if ($con->query($sql_hm) === TRUE) {
echo "values inserted successfully";
} else {
echo "No data ";
}
?>
I know the PHP part works - I tried POSTing JSON data with contentType: application/json from a REST client app and it works. But when I am trying it with my Javascript code, it isnt POSTing. I can see the "dictstring" string value in console. I cannot see the "Success" alert too. Interestingly, "Success" alert is shown if I remove the dataType: "json" line. But, POSTing is still not happening as I cannot see the values in database.
What am I missing here?
var dictstring = "{sensorid: \""+ name +"\", x: " +pos.x +" ,y: "+pos.y+"}";
You have a string.
data: JSON.stringify(dictstring),
Which you then convert to a JSON representation of that string.
$data_back = json_decode($jsonData);
Which you decode to a string.
$unit = $data_back->{"sensorid"};
Which you try to treat like an object.
Start with an object, not a string:
var dictstring = { sensorid: name, x: pos.x, y: pos.y };
… you probably want a different variable name too.
dictstring is already in JSON format, you don't need JSON.stringify in your JS
dataType: "json" is to be used if the data returned from server is JSON
You can create an array of messages and then use echo json_encode($array); to return JSON data to your js.
Coming to your problem, from the question and the information you've supplied, I couldn't find an obvious problem, but I could suggest to use console.log(data) in your success function and see what is returned. You'll at least know if it hit your php page or returned with some error like 404 or 500.
Try $data_back['sensorid']
or
Just print_r($data_back); and see the data structure of $data_back and then try access the data accordingly.
Okay it might sound silly but have you made sure to state that you're using JQuery in the java script because the amount of times I've been doing ajax and i cant figure out why it wont work and its because I haven't declared the JQuery.
like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">

Json object returned from PHP with json_encode() , but then invalid json object in my javascript

I echo a simple associative array read from a mySQL table back to my jquery b.m.o the json_encode($array) method. However, my .ajax call fails back in the jquery and it seems due to the object not being a valid json object. I did some debugging in chrome and under the network tab verified the response preview- does indeed look to be in perfect json format:
{"UserName":"DehanL","UserPassword":"admin","UserEmail":"dehan#rocketmail.com"}
Here is my php:
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName ="dbPodiumPro";
$inUsername = $_POST["name"];
$inPassword = $_POST["password"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Use the dbPodiumPro
mysqli_select_db($conn,"dbPodiumPro");
$sql = "SELECT * FROM users WHERE UserName='$inUsername' AND UserPassword ='$inPassword' ";
$result = mysqli_query($conn,$sql);
// Fetch one row
$row=mysqli_fetch_assoc($result);
//Check to see if the username and password combo exists
if(!empty($row['UserName']) AND !empty($row['UserPassword']))
{
//$_SESSION['UserName'] = $row['UserPassword'];
//echo $_SESSION;
echo json_encode($row);
}
else { echo "Be gone imposter!"; }
$conn->close();
?>
</body>
</html>
Then the jquery:
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'php/loginrequest.php', // the url where we want to POST
data: formData, // our data object
dataType: 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function (data) {
console.log("ajax done callback");
})
.fail(function (data) {
console.log(data, "ajax failed callback");
var IS_JSON = true;
try {
var json = $.parseJSON(data);
} catch (err) {
IS_JSON = false;
}
console.log(IS_JSON);
});
Your PHP starts like this:
<html>
<body>
Whatever else it outputs after that, it isn't going to be valid JSON.
I did some debugging in chrome and under the network tab verified the response preview
Look at the raw preview. You seem to be looking at the rendered HTML preview.
You don't need to parseJSON when you have added dataType as JSON option in the AJAX.
The data you are getting after ajax is completed is already in JSON format.
"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
Docs: http://api.jquery.com/jQuery.ajax/
The data inside fail method is not what you've passed from server. It is the information related to the request.
If you are encoding your password using MD5 and the likes, Json will not encode you can choose to unset the password from you your array or define the column you want to select from your database excluding password column.
Change your ajax as
$.ajax({
type:"POST",
url: 'php/loginrequest.php',
data:$("#form_id").serialize(),
dataType:"json",
success: function(data)
{
alert(data.UserName);
}
});
you can use both data:formData or data:$("#form_id").serialize(),
if you are getting alert message then everything is working fine

Uncaught SyntaxError: Unexpected token - JSON character encoding

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
...
});

Categories

Resources