|
The input doesn't seem to be valid JSON.
Assuming you want the test property to contain the literal string a\b\c\d\e\f\g , you need to encode the backslashes twice - once for the string literal value within the serialized object, and again for the JSON representation of that string:
var json_problem = '{"test": "a\\\\b\\\\c\\\\d\\\\e\\\\f\\\\g"}';
var parsed_json_problem = JSON.parse(json_problem); Pasting your string (including the ' s) into jsonlint.com gives:
Quote: Error: Parse error on line 1:
'{"test": "a\\b\\c\\
^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
I can only assume you pasted it in without the ' s, in which case you would only need to escape the backslashes once.
With your original code, the string property would contain a literal a , a backspace character (\b ), three invalid characters (\c , \d , \e ), a form-feed character (\f ), and another invalid character (\g ). This value cannot be deserialized, which is why you're getting an error.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I'm SMH on this.
I wrote an API in PHP 7.4, that gets the body in the header, converts it to an object and I do the database write. It works fine in Postman, but my app seems to send garbage to my PHP API. Process of elimination tells me that I didn't package my JSON right in plain JavaScript.
const jsonData = {
"projectNumber": projectNoElement.value,
"userName" : userNameElement.value,
"userType" : userTypeElement.value,
"invoiceClass": classElement.value,
"invoiceOperation": opElement.value,
"subContractor": scElement.value,
"invoiceDate": dateElement.value,
"invoiceNumber": invNumberElement.value.trim(),
"invoiceAmount": invAmountElement.value.trim(),
"invoiceDescription": descElement.value.trim()
};
const jsonPayload = JSON.stringify(jsonData);
console.log(jsonPayload);
fetch(urlQuery, { mode: 'same-origin', method: 'POST', headers: { 'Content-Type': 'application/json; charset=utf-8', body: jsonPayload }})
When I stringify it, and paste it in my Postman body, this is what I send, and the PHP side works fine. I send back { "result: true } and the Fetch crashes, because all these PHP error outputs are in the response payload.
{"projectNumber":"3352","userName":"xxxx","userType":"xxxx","invoiceClass":"EQ","invoiceOperation":"16","subContractor":"39","invoiceDate":"2021-03-27","invoiceNumber":"AZ-1000","invoiceAmount":"1.50","invoiceDescription":"Test Kit"}
I've never done this in plain valnilla JavaScript, and have been using Angular 8, in which I just stringify the object and Angular takes care of the rest. I searched around the internet and some examples show a pure string being fabricated, but the info dates back to 2011, nothing really 2020+ out there.
Browser response:
Note: I think I should keep the PHP side as is, because Postman works with it, and modify the JavaScript side. Versus trying to make the PHP side work with the current JavaScript side.
SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
But my browser F12, network, response says result "1"
Notice: Trying to access array offset on value of type null in C:\App\Dev\PCAD\api\invoices\viewInvoices.api.php on line 72
Notice: Trying to access array offset on value of type null in C:\App\Dev\PCAD\api\invoices\viewInvoices.api.php on line 73
Notice: Trying to access array offset on value of type null in C:\App\Dev\PCAD\api\invoices\viewInvoices.api.php on line 74
Notice: Trying to access array offset on value of type null in C:\App\Dev\PCAD\api\invoices\viewInvoices.api.php on line 75
Notice: Trying to access array offset on value of type null in C:\App\Dev\PCAD\api\invoices\viewInvoices.api.php on line 76
Notice: Trying to access array offset on value of type null in C:\App\Dev\PCAD\api\invoices\viewInvoices.api.php on line 77
Notice: Trying to access array offset on value of type null in C:\App\Dev\PCAD\api\invoices\viewInvoices.api.php on line 78
Notice: Trying to access array offset on value of type null in C:\App\Dev\PCAD\api\invoices\viewInvoices.api.php on line 79
Notice: Trying to access array offset on value of type null in C:\App\Dev\PCAD\api\invoices\viewInvoices.api.php on line 80
Notice: Trying to access array offset on value of type null in C:\App\Dev\PCAD\api\invoices\viewInvoices.api.php on line 81
{
"result": "1"
}
If it ain't broke don't fix it
Discover my world at jkirkerx.com
modified 27-Mar-21 16:01pm.
|
|
|
|
|
I went back and did more research.
The payload I sent from my JavaScript fetch was empty, so PHP wasn't able to read anything, or work with the JSON.
Found some technical documentation for fetch, and there is a correct way to attach the payload for PHP V7.4+ to read using $jsonPayload = file_get_contents('php://input') ;
Changing the header to an object and inserting the object into fetch seems to have packaged my payload proper for a smooth transmission. So that's it, I now have all my parts designed, tested and confirmed and it appears to be really fast and rock solid now. I'm off to the pool to hang out.
const jsonData = {
"projectNumber": projectNoElement.value,
"userName" : userNameElement.value,
"userType" : userTypeElement.value,
"invoiceClass": classElement.value,
"invoiceOperation": opElement.value,
"subContractor": scElement.value,
"invoiceDate": dateElement.value,
"invoiceNumber": invNumberElement.value.trim(),
"invoiceAmount": invAmountElement.value.trim(),
"invoiceDescription": descElement.value.trim()
};
const jsonPayload = JSON.stringify(jsonData);
let header = new Headers();
header.append('Content-Type', 'application/json');
header.append('Accept', 'application/json');
fetch(urlQuery, { mode: 'same-origin', method: 'POST', cache: 'no-cache', headers: header, body: jsonPayload })
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Hi, thanks for answering.
I indeed copy pasted the strang into jsonlint without the enclosing single quotes, because that's the string which has to be validated.
And I still dont understand the problem. I don't do \a\b\c etc., because I escape each backslash: \\a\\b\\c so the a, b, c should be characters, not string literals.
And the string in my original code (again, of course without the enclosing single quotes) validates fine in jsonlint.com..
|
|
|
|
|
Dear, I'm testing a CAPTCHA antispam system from PHP (antispam/getimg.php) and I do not understand what happens :
type: 'POST',
url: $("#relpath").val() + 'sendmailcvalidation.php',
data: $("#sendmail").serialize(),
success: function(data) {
data=data.trim();
if(data == "false") {
alert("Erreur lors de l'envoi du message");
mailsendstatus = false;
$("#cvalidationlabel").children(".err").fadeIn('slow');
}
else if(data == "badcapcha"){...}
The thirdth line of code serialize a form with the name "sendmail" and assign the result into DATA then, at the next lines the code check IF DATA=="false"
I miss something, how the serialization result of a form (name/value pairs as string, ie:data=data.trim()) could be evaluated like an BOOLEAN ... ?
(I'm a natvie french speaker)
|
|
|
|
|
...and the code works fine
|
|
|
|
|
It is a common convention that PHP functions return false on failure, instead of their normal return type (such as some kind of object, array, etc)
Software rusts. Simon Stephenson, ca 1994. So does this signature. me, 2012
|
|
|
|
|
Thank Peter BUT your answer bring another question in mind, I did not paste the whole code but in the if condition, DATA is also evaluated tu TRUE or "BADCAPCHA" ... is there a way to override the serialize function or something else .... ?
else if(data == "badcapcha"){
alert("Le code est incorrect");
mailsendstatus = false;
$("#cvalidationlabel").children(".err").fadeIn('slow');
}
else if(data == "true"){
$("#cvalidationlabel").children(".err").fadeOut('slow');
$("#sendmailwrapper").slideUp(650, function(){
$(this).before("<h3>Mail SEND</h3>");
});
|
|
|
|
|
ok, thanks for the "advise"
|
|
|
|
|
There are two different things called data in that code snippet:
- The
data: property of the object passed to jQuery's ajax method[^], which contains the serialized[^] form data; and - The
data parameter passed to the success callback, which represents the parsed response returned from the server.
It might make things easier to understand if you renamed the parameter:
type: 'POST',
url: $("#relpath").val() + 'sendmailcvalidation.php',
data: $("sendmail").serialize(),
success: function(responseFromServer) {
responseFromServer = responseFromServer.trim();
if (responseFromServer === "false") {
...
}
else if (responseFromServer === "badcaptcha") {
...
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank you, This will be very helpfull
|
|
|
|
|
Hello,
so what i want is when my website is loading in the background and the user goes to it for example after 5 s it redirect to PAGE 1.
if the user goes to my website after 10 minute it redirect to PAGE 2.
Using visibilitychange.
Cheers,
|
|
|
|
|
I used node-schedule module to cron a job executed only once at particular time. I also use callable function to trigger Cloud Function and to get client-side data. The big trouble is that all things are fine to cron a single task until 15 minutes. But, on the other hand it doesn't do the task scheduled further time more than 15 minutes. What may occur after 15 minutes to cancel task? I used Firebase Quickstart code and I add only schedule-job module into the code. I didn't changed anything other than getting scheduling time values from client-side. I really need help for this issue. The cloud function script is below.
Thank you.
<pre>
"use strict";
const functions = require("firebase-functions");
const sanitizer = require("./sanitizer");
const admin = require("firebase-admin");
const schedule = require("node-schedule");
admin.initializeApp();
exports.addMessage = functions.https.onCall((data, context) => {
const text = data.text;
if (!(typeof text === "string") || text.length === 0) {
throw new functions.https.HttpsError("invalid-argument", "The function must be called with " +
"one arguments \"text\" containing the message text to add.");
}
if (!context.auth) {
throw new functions.https.HttpsError("failed-precondition", "The function must be called " +
"while authenticated.");
}
const uid = context.auth.uid;
const name = context.auth.token.name || null;
const picture = context.auth.token.picture || null;
const email = context.auth.token.email || null;
const dateWithTimeZone = (timeZone, year, month, day, hour, minute, second) => {
const date = new Date(Date.UTC(year, month, day, hour, minute, second));
const utcDate = new Date(date.toLocaleString("en-US", {timeZone: "UTC"}));
const tzDate = new Date(date.toLocaleString("en-US", {timeZone: timeZone}));
const offset = utcDate.getTime() - tzDate.getTime();
date.setTime( date.getTime() + offset );
return date;
};
const sanitizedMessage = sanitizer.sanitizeText(text);
const dataFuture = [uid, name, picture, email, sanitizedMessage];
new Promise(function() {
schedule.scheduleJob(dateWithTimeZone("Europe/Istanbul",
data.year, data.month, data.day, data.hour,
data.minute, data.second), function(data) {
const theuid = data[0];
const thename = data[1];
const thepicture = data[2];
const theemail = data[3];
return admin.database().ref("/messages").push({
text: data[4],
author: {theuid, thename, thepicture, theemail},
}).then(() => {
console.log("New Message written");
return {text: data[4]};
})
.catch((error) => {
throw new functions.https.HttpsError("unknown", error.message, error);
});
}.bind(null, dataFuture));
});
return {text: "done"};
});
|
|
|
|
|
Hello,
I'm trying to calculate values every time when change it.
<pre lang="HTML"><pre><ol class="firstDigit">
<li data-value="10"> 10 </li>
and
<pre><ol class="secondDigit">
<li data-value="10"> 10 </li>
The sum is 20. The problem is when I change firstDigit or secondDigit to 20
<pre><ol class="firstDigit">
<li data-value="20"> 20 </li>
The sum is 40, but should be 30.
const firstNav = $('#firsNav');
const firstSelection = $('.firstDigit');
const firstValue = firstSelection.find('li');
const secondNav = $('#secondNav');
const secondSelection = $('.secondDigit');
const secondValue = secondSelection.find('li')
var sum = 0;
firstNav.click(function(event) {
if (firstNav.hasClass('active')) {
firstNav.removeClass('active');
selection.stop().slideUp(200);
} else {
firstNav.addClass('active');
selection.stop().slideDown(200);
}
event.preventDefault();
});
secondNav.click(function(event) {
if (secondNav.hasClass('active')) {
secondNav.removeClass('active');
secondSelection.stop().slideUp(200);
} else {
secondNav.addClass('active');
secondSelection.stop().slideDown(200);
}
event.preventDefault();
});
firstValue.click(function() {
firstValue.removeClass('active');
$(this).addClass('active');
var x = $(this).attr('data-value');
sum = parseInt(x);
document.getElementById('total').innerHTML = sum; });
firstValue.click(function() {
firstValue.removeClass('active');
$(this).addClass('active');
var z = $(this).attr('data-value');
sum = parseInt(z);
document.getElementById('total').innerHTML = sum;
})
document.getElementById('total').innerHTML = sum;
<pre><h2 id="firsNav">Choose</h2>
<ol class="firstDigit">
<li data-value="10"> 10 </li>
<li data-value="20"> 20 </li>
</ol>
<h2 id="secondNav">Choose</h2>
<ol class="secondDigit">
<li data-value="10"> 10 </li>
<li data-value="20"> 20 </li>
</ol>
<a id="total" style="font-size: large;font-weight: bold;color: #0a0a0a"></a>
|
|
|
|
|
You've attached two click handles to .firstDigit li , and none to .secondDigit li .
The handler you've attached isn't going to sum anything; it simply takes the attribute from the clicked element, and puts it in the total element.
Try something more like this:
const updateTotal = function(){
let total = 0;
$("ol > li[data-value].active").each(function(){
const value = parseInt(this.getAttribute("data-value"));
if (!isNaN(value)) { total += value; }
});
$("#total").html(total);
};
$(document).on("click", "ol > li[data-value]", function(){
const me = $(this);
me.closest("ol").find("li").removeClass("active");
me.addClass("active");
updateTotal();
}); Demo[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
It's work. Thanks a lot Richard Deeming.
|
|
|
|
|
Hey, Richard
How to create reset button for the total? When I refresh eveything is clear. I created button which remove by id document.getElementById, but this is not working. Because when I click on li I understand that total is not starting from the begining.
modified 30-Mar-21 14:25pm.
|
|
|
|
|
Hi all, first post here...
I am playing with Content Security Policies and some other stuff trying to figure out how to add a bit if security for users. Ive created about a dozen pages, all nicely and neatly working together so far. All garbage test stuff, but its not working as I have hoped.
One of the functions I need to work is to use AJAX to load data from a PHP script including a cookie with an HttpOnly flag set, so Javascript cant read it.
Trouble is that no matter what I try short of turning off ALL security (which aint gonna happen), I can not get my AJAX call to not violate Cross Origin Request Policy. What is throwing me off is that I dont believe it should be Cross Origin at all! I know one way to do it is to process the "Origin" header when sending the request but its never actually sent! Typically it is not, except for when "withCredentials" flag is also set, which it is. If thats what I gotta do, fine, but I cant get it to work. Better solution is make sure it is NOT treated as Cross Origin, and I believe that would also resolve it. Both my solutions are evading me!
The script is in "iframe.php"
So here is my test page on my test server:
https://www.webucate.me/cors_csp/
Full source is here:
https://www.webucate.me/cors_csp/ajax.php
This is where it fails on me. This AJAX call wont send the cookie. I am not sure if this is where I need to fix it however...
const loadLocalXMLCookie = function(){
let url = "jsondata.php";
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.withCredentials = true;
xhttp.onreadystatechange = function() {
console.log(this);
if (this.readyState == 4 && this.status == 200){
outputElement.innerHTML = this.responseText;
}
};
xhttp.onerror = function(){ outputElement.innerHTML = "XML Cookie Error " + url; };
xhttp.send();
}
What can I do so that this XMLHttpRequest object is not treating the request as Cross Origin, thus, use PHP to read and set the cookie? If I have to use Cross Origin, what am I missing in my setup?
|
|
|
|
|
Your comment for the xhttp.open line is inaccurate and misleading. The third parameter has nothing to do with cookies; it simply controls whether the request is asynchronous or not:
XMLHttpRequest.open() - Web APIs | MDN[^]
The withCredentials property has no effect on same-site requests:
XMLHttpRequest.withCredentials - Web APIs | MDN[^]
You're not actually logging any details of the error. Have you checked the network request to see what the actual error is, or are you just assuming it's a CORS issue?
I'd recommend switching to the Fetch API instead:
Fetch API - Web APIs | MDN[^]
Using Fetch - Web APIs | MDN[^]
It's supported pretty much everywhere except Internet Explorer. If you need to support IE, there's a polyfill available[^].
In modern browsers, cookies for same-origin requests should be included by default. If you're using an older browser (prior to April 2018), you may need to supply the credentials:'same-origin' init option[^].
const loadLocalXMLCookie = async function(){
const url = "jsondata.php";
const response = await fetch(url, {
method: 'GET',
cache: 'no-cache',
credentials: 'same-origin'
});
if (!response.ok) {
const errorMessage = await response.text();
console.error(response.status, response.statusText, errorMessage);
return;
}
const responseText = await response.text();
document.getElementById('outputElement').innerHTML = responseText;
};
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
This is the error message I get:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.webucate.me/cors_csp/jsondata.php. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://www.webucate.me’).
I looked at the Origin header, its never sent.
So much for Stack Overflow answers on other questions when youre tired, tend to miss stuff, like misleading comments.
I will take a look further into fetch and maybe the polyfill, but I dont really have any intention of trying to support IE.
Thank you.
|
|
|
|
|
Well, based on the information provided, there's no way you should be violating the same-origin policy. The protocol, domain, and port all match; the only difference is the path.
Same-origin policy - Web security | MDN[^]
Have you tried a different browser, in case there's a problem with the one you're using or one of its plugins?
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Agreed, I do not believe it should be a CORS request... with one exception to that thought... But yes, different browsers and computers. I even tried accessing it with a Super Nintendo from WAY back in the day and that turned out exactly as you'd expect! I went so far as to try VM Kubuntu also running firefox and same thing.
So this is probably affecting it, but the iframe is in Sandbox mode, with scripts allowed, so I think its *possible* I may need to use CORS anyway due to the IFrame being Sandboxed. CSP appears to work perfectly as expected.
I am trying something from an inverse approach. Put it on "full lockdown", then open up for things that are needed. And I cant quite figure out how to "open it back up" without completely unlocking it.
My concept is to do something "super" stupid as far as security pros will say. Users get to upload their own scripts to interact with a Canvas Object that other users can view and interact with. Everything else needs to be in full on lockdown mode. So I know I am asking for things that conflict. Most things work so far. Browsers shouldnt have access to Http Only cookies, this particular IFrame should. This is the only thing I want to work differently that doesnt work. CSP did a great job of only allowing open data connections to scripts and sources specified in the CSP headers from PHP / Apache.
Perhaps a safer idea would be to figure out how to make this a CORS request and do that properly?
---
Edit:
Yay! I have a NEW error! It is different than the OLD error so the fact that I have a NEW error is wonderful news to me!
Firefox Error: (Ambiguous) Error: TypeError: NetworkError when attempting to fetch resource.
Chrome Error: POST https://www.webucate.me/cors_csp/jsondata.php net::ERR_BLOCKED_BY_RESPONSE
fetchData @ iframe.php:76
So now it is between my fetch call and probably PHP headers:
const fetchData = async function(data = {}) {
let url = 'https://www.webucate.me:443/cors_csp/jsondata.php';
const response = await fetch(url, {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
credentials: 'include',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow',
referrerPolicy: 'same-origin',
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.warn('Error:', error);
return;
});
return response.json();
}
<?php
header("Content-Type: application/json; charset=utf-8");
header('Access-Control-Allow-Credentials: true', false);
header('Access-Control-Allow-Methods: POST', false);
header('X-Frame-Options: same-origin' );
header('Cross-Origin-Resource-Policy: same-origin', false);
$cookie = (isset($_COOKIE['TestCookie'])) ? $_COOKIE['TestCookie'] : 'No Cookies';
$time = time();
$msg = array("time" => $time, "cookie" => $cookie);
echo json_encode($msg);
setrawcookie('TestCookie','123456', time() + 86400, '/', 'www.webucate.me', true, 'None');
?>
What is my next step?
modified 15-Mar-21 18:52pm.
|
|
|
|
|
I assume you've tried adding allow-same-origin to the sandbox attribute?
<iframe>: The Inline Frame element - HTML: HyperText Markup Language | MDN[^]
Without it, the content is "treated as being from a special origin that always fails the same-origin policy".
The ERR_BLOCKED_BY_RESPONSE seems to be related to the X-Frame-Options header. The value needs to be SAMEORIGIN , not same-origin :
X-Frame-Options - HTTP | MDN[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I looked at that allow-same-origin iframe attribute and I believe it wont work for what I have it intended for, as the IFrame would be an include on other peoples sites, not my own, I believe it would not be appropriate for that header. ... (?)
Well, I got it "sort of" talking. Im now getting back Opaque responses but no data! Im so confuzzled, and kind of frustrated. I feel like all I am doing is throwing headers at it and hoping something sticks and each header fixes something some other header does! Hour of reading, 2 minutes of code, go back to reading, and very little success... I did take your advice and used fetch instead of XMLHttpRequest, which seems more flexibler! Is that a word?
What do I need to do for me to get data back from the cookie in php and not just an Opaque response?
|
|
|
|
|
Hi All, Hope all is well well. I have a coding question I cant seem to figure out. I have a form in HTML5 which has columns that I want to sum and show in a totals box. The totals are summed when a button that calls the sum() function when clicked. From the code below I'm just trying to sum two boxes which represent a value for each hour total. My problem is that when I click on the button with only a value in the first box, then i get a NaN in the results box...no matter how many times i click it...but when i enter a value in the second box the sum is completed and the correct total is displayed. Could someone explain please why this only works with 2 values and not just 1....hope this is clear. Thanks to all who try
regards
<pre><script type="text/javascript" ></script>
<script type="text/javascript">
function sum() {
var result= 0;
var txtFirstNo = document.getElementById('Text1').value;
var txtSecondNo = document.getElementById('Text6').value;
if (!isNaN(txtFirstNo)){
result = parseInt(txtFirstNo);
document.getElementById('Tar').value = parseInt(result);
}
if (!isNaN(txtSecondNo)){
result = parseInt(txtFirstNo) + parseInt(txtSecondNo);
document.getElementById('Tar').value = result;
}
if (!isNaN(result)) {
document.getElementById('Tar').value = result;
}
}
</script>
|
|
|
|
|