JSON.parse() not working even though JSON string is valid - javascript

I am trying to post a form through AJAX jQuery. The PHP script to which it points returns a JSON encoded array. But, at the receiving end on the main page JSON.parse() is not working.
Please suggest if I am missing on some file types which need to be included
Here is my code.
< script type = "text/javascript" >
$(document).ready(function() {
$("#send").submit(function() {
//$("#submit_form").html('');
$("#modal-text2").html("<img src=" + "img/loader1.gif "
+ "/></br</br><h4>DATA VALIDATION IN PROCESS !!! PLEASE WAIT</h4>");
$("#myModal2").modal('show');
$.post($("#send").attr("action"), $("#send").serialize(), function(data) {
var decode = JSON.parse(data);
if (decode.err > 0) {
alert("Hi");
}
});
//Important. Stop the normal POST
return false;
});
});
< /script>
The JSON encoded array which is being sent back by the PHP script is:
{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}

don't know if its the cause of hte problem or if its just a typo in here, but you have a typo in the following line:
<img src="+"img/loader1.gif "+"/></br</br>
you aren't closing the first linebreak, and the slash should come after the br - also not sure why you have so many quuotes in that html block - it should be :
$("#modal-text2").html("<img src='img/loader1.gif'/><br/><br/><h4>DATA VALIDATION IN PROCESS !!! PLEASE WAIT</h4>")

You should console.log(data) to check if the data value has any problem.
use try/catch to catch message if error happened in JSON.parse.
try {
var decode = JSON.parse(data);
}catch(e){
console.log(e) ;
}
Make sure your php responses the json in the right way. Or there may have some invisible character and make the problem.
<?php
$data = ... ;
header('Content-type:application/json;charset=utf-8');
echo json_encode($data) ;
?>

I thought there is a sytax error in your script just check it out in the last line of script the closing tag of < /script> has space, remove it and try -
</script>
i execute the parsing snippet of your code it is working fine.
var data = '{"err":8,"er1":1,"er3":1,"er4":1,"er5":1,"er6":1,"er7":1,"er8":1,"er9":1,"error1":"First Name is Required","error3":"Last Name is Required","error4":"Email is Required","error5":"Please Select a Gender","error6":"Date of Birth is Required","error7":"Mobile No is Required","error8":"Password is Required","error9":"Please Fill The Captcha"}';
var decode = JSON.parse(data);
if (decode.err > 0) {
alert("Hi");
}

Related

PHP $_POST cutting off '<' character coming from $.post in jQuery

I feel like this should be easy. The character < (and following characters) refuses to be sent to $_POST. My max_input_vars is set to 10000, my memory limit is set to 3GB in my php.ini file, and I'm using PHP 8.0.
I have a text area where the text gets posted to a PHP file.
# HTML
<div class="add-comment">
<textarea style="margin-left: -15px;" placeholder="Add your commentary here" style="white-space:pre-wrap;" id="add-comment" class="form-control" rows="3"></textarea>
</div>
# JS
let comment = $('#add-comment').val();
const post_variables = {
'comment' : comment
};
console.log(post_variables);
$.post('/?c=comments&a=add_comment', post_variables, function(data){});
# PHP
echo '<pre>post:<br>';
print_r($_POST);
echo '</pre>';
Lets say I submit the text 'a < b'.
In JS, the log shows: a < b
In PHP the log shows: a
Is there something I need to do before passing it off to PHP? I'm genuinely surprised I haven't run into this before..
You can print the "<" on PHP using print_r(htmlspecialchar($_POST['comment'])) and if you want to convert it before sending to PHP use below function
# JS
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g,'<').replace(/>/g, '>').replace(/"/g, '"');
}
let comment = $('#add-comment').val();
const post_variables = {
'comment' : htmlEntities(comment)
};

Can't create a button dynamically with php and js

I'm trying to construct a page as a client logs in through php js interaction as fallows
$hold = ("< button onclick = `
function myFunction(){
alert('works!');
}
myFunction();
` >My balance</button>");
echo hold;
and then i want to send dinamicly to html through js
var Permition = localStorage.getItem("Permition");
$.post('MenuConstructor.php',
{
Permition:Permition
},
function(data){
menu = data;
//alert(data);
document.getElementById("div").innerHTML = menu;
}
);
but for some reson the alert don't work do you guys have any suggestions?
some times i get the error not defined some times i get the error "Unterminated template literal"
"Unterminated template literal"
:) You need escape illegal character.
<div onclick="alert("123")">
<div onclick="alert("123")"> // php htmlspecialchars (maybe) (single ' is &apos;) quot with no "e" at it's end
$url = 'index.html?a='.urlescape($value);
echo ''

Jquery if statement not working even if the statement is true

I have a simple if statement where when i send this certain data to the database, i want the php code to send bake a code that tells javascript its ok to continue, but if the php script sends back a bad code, javascript is to now move forward and display a certain text or something.
The php code works fine but for some reason my javascript files would not work at all.
My javascript is suppose to ajax request to parse.php and receive the data that parse.php sends back to it, if parse.php says 200 its suppose to load in specific items.
Here is the code for one of my systems:
$(document).ready(function(){
$("#chatForm").submit(function(){
var chatHash = $("#chatHash").val();
var body = $("#chatPoster").val();
var by = $("#userBy").val();
if(chatHash != "" && body != ""){
$.post('parse.php',{chatHash: chatHash, body: body, userBy: by},function(data){
if(data == "200"){ // Right here is where its messing up
$("#chatPoster").val("");
$.get('getChatMessages.php?hash=' + chatHash,function(data2){
$(".allMsgs").html(data2);
});
} else {
alert('Critical error');
}
});
} else {
alert('Error');
}
});
});
Here is the code for the parse.php page:
$chat = new ChatSystem;
if(isset($_POST['chatHash']) && isset($_POST['body']) && isset($_POST['userBy'])){
$chat->sendMessage($_POST['userBy'],$_POST['chatHash'],$_POST['body']);
}
Here is the code from the class ChatSystem that the parse.php page is referring to:
public function sendMessage($user,$hash,$body){
global $db;
$date = date("Y-m-d");
$time = date("H:i:s");
$timestamp = "$date $time";
if(empty($user) == false && empty($hash) == false){
$db->query("INSERT INTO chat_messages VALUES('','$user','$body','$timestamp','','0','$hash')") or die("error");
echo '200';
}
}
Even though my php code works perfectly the javascript still messes up. My php code sends back 200 like i ask it to but yet the jquery messes it up
Have a look here, http://api.jquery.com/jquery.post/.
You need a second parameter to the success callback function to be able to catch the response status code.
I.E. function(data,statusCode){ // check the status code here}

running a php function inside javascript code [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I hope to run a php code inside a javascript code too and I do like that :
<?php function categoryChecking(){
return false;
}?>
....
function openPlayer(songname, folder)
{
if(<?php echo categoryChecking() ?> == true)
{
if (folder != '')
{
folderURL = "/"+folder;
}else
{
folderURL = '';
}
var url = "/users/player/"+songname+folderURL;
window.open(url,'mywin','left=20,top=20,width=800,height=440');
}else{
alerte('you should click on a subcategory first');
}
}
....
<a href='javascript:void();' onClick="openPlayer('<?php echo $pendingSong['id']; ?>','')">
finally I get this error instead the alert message "you should click on a subcategory first"
ReferenceError: openPlayer is not defined
openPlayer('265','')
You're reduced your test case too far to see for sure what the problem is, but given the error message you are receiving, your immediate problem has nothing to do with PHP.
You haven't defined openPlayer in scope for the onclick attribute where you call it. Presumably, the earlier JS code is either not inside a script element at all or is wrapped inside a function which will scope it and prevent it from being a global.
Update: #h2ooooooo points out, in a comment, that your PHP is generating the JS:
if( == true)
Check your browser's error console. You need to deal with the first error messages first since they can have knock on effects. In this case the parse error in the script will cause the function to not be defined.
Once you resolve that, however, it looks like you will encounter problems with trying to write bi-directional code where some is client side and some is server side.
You cannot run PHP code from JavaScript, because PHP is a server-side language (which runs on the server) and JavaScript is a client-side language (which runs in your browser).
You need to use AJAX to send a HTTP request to the PHP page, and then your PHP page should give a response. The easiest way to send a HTTP request using AJAX, is using the jQuery ajax() method.
Create a PHP file ajax.php, and put this code in it:
<?php
$value = false; // perform category check
echo $value ? 'true' : 'false';
?>
Then, at your JavaScript code, you should first add a reference to jQuery:
<script type="text/javascript" src="jquery.js"></script>
Then, use this AJAX code to get the value of the bool:
<script type="text/javascript">
$.ajax('ajax.php')
.done(function(data) {
var boolValue = data == 'true'; // converts the string to a bool
})
.fail(function() {
// failed
});
</script>
So, your code should look like this:
function openPlayer(songname, folder) {
$.ajax('ajax.php')
.done(function (data) {
var boolValue = data == 'true'; // converts the string to a bool
if (boolValue) {
if (folder != '') {
folderURL = "/" + folder;
} else {
folderURL = '';
}
var url = "/users/player/" + songname + folderURL;
window.open(url, 'mywin', 'left=20,top=20,width=800,height=440');
} else {
alert('you should click on a subcategory first');
}
})
.fail(function () {
// failed
});
}

Output XML code with Jquery

Consider the following script for outputting some XML code:
var xmlAsString = '<?xml version="1.0"?><person><name gender="male"></name></person>';
$(document).ready(function(){
$(".generator").click(function(){
alert(xmlAsString);
$("#container").append("<div id='contXML'>"+xmlAsString+"</div>")
});
});
The alert outputs everything as I want but nothing shows later. If I put some random string variable (without the < > chars everything works fine).
That's because you have to html encode your xml otherwise the browser tries to parse it. I use this simple function.
var xmlAsString = '<?xml version="1.0"?><person><name gender="male"></name></person>';
function htmlEncode(value){
return $('<div/>').text(value).html();
}
$(document).ready(function() {
$(".generator").click(function() {
alert(xmlAsString);
$("#container").append("<div id='contXML'>" + htmlEncode(xmlAsString) + "</div>")
});
});
Fiddle here http://jsfiddle.net/DqDEU/

Categories