PHP not Sending JSON Object to JavaScript - javascript

<?php
header("Content-Type: application/json");
if(isset($_POST['limit'])){
$limit = preg_replace('#[^0-9]#', '', $_POST['limit']);
require_once("connect_db.php");
$i = 0;
$jsonData = '{';
$sqlString = "SELECT * FROM tablename ORDER BY RAND() LIMIT $limit";
$query = mysqli_query($con, $sqlString) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)) {
$i++;
$id = $row["id"];
$title = $row["title"];
$cd = $row["creationdate"];
$cd = strftime("%B %d, %Y", strtotime($cd));
$jsonData .= '"article'.$i.'":{ "id":"'.$id.'","title":"'.$title.'", "cd":"'.$cd.'" },';
}
$now = getdate();
$timestamp = $now[0];
$jsonData .= '"arbitrary":{"itemcount":'.$i.', "returntime":"'.$timestamp.'"}';
$jsonData .= '}';
echo $jsonData;
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var myTimer;
function ajax_json_data(){
var databox = document.getElementById("databox");
var arbitrarybox = document.getElementById("arbitrarybox");
var hr = new XMLHttpRequest();
hr.open("POST", "json_mysql_data.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
arbitrarybox.innerHTML = d.arbitrary.returntime;
databox.innerHTML = "";
for(var o in d){
if(d[o].title){
databox.innerHTML += '<p>'+d[o].title+'<br>';
databox.innerHTML += ''+d[o].cd+'</p>';
}
}
}
}
hr.send("limit=4");
databox.innerHTML = "requesting...";
myTimer = setTimeout('ajax_json_data()',6000);
}
</script>
</head>
<body>
<h2>Timed JSON Data Request Random Items Script</h2>
<div id="databox"></div>
<div id="arbitrarybox"></div>
<script type="text/javascript">ajax_json_data();</script>
</body>
</html>
PHP code goes on a separate file called "json_mysql_data.php". I'm just following this tutorial from https://www.youtube.com/watch?v=-Bv8P5oQnFw and it runs fine for him but not for me. I tested "connect_db.php" with mysql alone and it works fine. It seems to me like php doesn't go pass if (isset ($_POST['limit'])) but why...On the html file I get the "requesting..." message from the javascript code which means is waiting for PHP. Thanks for your help guys.

You check for the ready state and change the content of databox with the response JSON inside the onreadystatechange function:
hr.onreadystatechange = function(aEvt) {
if(hr.readyState == 4 && hr.status == 200) {
…
databox.innerHTML += …;
…
}
…
databox.innerHTML = "requesting...";
…
}
But you change the HTML of the databox:
databox.innerHTML = "requesting...";
Still inside the block of the onreadystatechange function and after you receive the response, so the databox will always say "requesting..." no matter what you receive. You have to move the part that prints "requesting..." outside of it:
hr.onreadystatechange = function(aEvt) {
if(hr.readyState == 4 && hr.status == 200) {
…
databox.innerHTML += …;
…
}
…
}
…
databox.innerHTML = "requesting...";
…
Update:
Also, it seems that your function ins't defined correctly, as you can see, the one on the MDN reference pages example receives a parameter:
req.onreadystatechange = function(aEvt) {
…
}
But yours doesn't have such parameter:
hr.onreadystatechange = function() {
…
}
Ans that's it.

Thank you for your help #arielnmz. I found the problem. PHP was having issues with the getDate() function because the date.timezone field was not configured in the PHP.ini file. Adding the following line to the file fixed the problem:
date.timezone = "UTC"

Related

Passing values from JS to PHP and Echo back HTML

I am studying a code and need help to learn further.
The JS code below is from a Q/A html form that sends data to server.
It crosschecks answer and on server and scores the user.
I need help writing a PHP code that receives the inputs using GET method and echo "ok" back to the html.
JS:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
if(this.responseText == "ok") {
document.getElementById("messagefont").innerHTML = checkans;
document.getElementById("answer").value = "";
document.getElementById('submit-btn').value = continuebutton;
checkans.focus();
PHP:
<?php
header('Content-Type: application/json');
$errors = array ();
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' );
if (isset ($_GET['answer'])) {
$answer = $_GET["answer"];
}
else {
array_push ($errors, no);
}
$response = "";
if (sizeof ($errors) > 0) {
$response = implode (",", $errors);
}
else {
$response = ok;
}
echo json_encode($response);
?>
I seem not to be getting something right with the PHP, please i need assistance/guide to fix the PHP code rightly.

Multiple XMLHttpRequest in one page

I have a situation where I am making the following requests and for some reason only one of them is working?
The expected result is that the second div which is populated by filter2 will bring in the necessary information, however this is not working even though this is following the same logic as filter 1?
The code for the actual requests is here:
Request 1:
function show1(str) {
if (str == "") {
document.getElementById("id1").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("id1").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "filter1.php?q=" + str, true);
xmlhttp.send();
}
Request 2:
function show2(str) {
if (str == "") {
document.getElementById("id2").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("id2").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "filter2.php?p=" + str, true);
xmlhttp.send();
}
The php code is as follows for both of the requests is as follows:
Filter1:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
include('db.php');
$q = strval($_GET['q']);
mysqli_select_db($mysqli,"database");
$search="SELECT * FROM column WHERE type = '".$q."'";
$result = mysqli_query($mysqli,$search);
echo "<ul id=\"list\">";
while($row = mysqli_fetch_array($result)) {
echo "<li>";
echo "<a class=\"class\">" . $row['column'] . "</a>";
echo "<a class=\"class\"><strong>" . $row['column'] . "</strong></a>";
echo "<button><img src=\"icons/image.png\" style=\"height:42px;width:42px;\" onclick=\"show2(this.value)\" value=\"" . $row['column'] . "\" class=\"class\"></button>";
echo "</li>";
}
echo "</ul>";
mysqli_close($mysqli);
?>
</body>
</html>
Filter2:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
include('db.php');
$p = strval($_GET['p']);
mysqli_select_db($mysqli,"database");
$search="SELECT * FROM column WHERE name = '".$p."'";
$result = mysqli_query($mysqli,$search);
echo "<table>";
while($row = mysqli_fetch_array($result)) {
echo "<tr id=\"id\"><td><strong>" . $row['column'] . "</strong></td></tr>";
echo "<tr id=\"id\"><td>TestContact</td></tr>";
echo "<tr id=\"id\"><td>" . $row['column'] . "</td></tr>";
echo "<tr id=\"id\"><td>Website ></td></tr>";
}
echo "</ul>";
mysqli_close($mysqli);
?>
</body>
</html>
I am not sure if this is a common mistake or I have some kind of clash/stupid syntax error, but this is driving me crazy and I would be forever grateful for anyone to help?
Like I said in a comment ( and was also stated in the 1st comment by #jcubic ) an img element doesn't have a value attribute which is, I suspect, the reason your function is passing undefined
Instead you can use a dataset attribute and alter the parameter passed to the inline function / event handler:
echo "<button><img src=\"icons/image.png\" style=\"height:42px;width:42px;\" onclick=\"show2(event)\" data-value=\"" . $row['column'] . "\" class=\"class\"></button>";
and the javascript function
/* passing event allows access to event.target amongst other things - this is useful */
function show2( e ){
var el=e.target;
var str=el.dataset.value;
if( str )/* etc */
}
that said you'd be much better creating a generic ajax function ( or better yet look into the fetch api ) and write wrapper functions for each use case.

echo is adding a new line to what i output in PHP

I am sending echoing some data to be received in Javascript however when i debug it, it seems that a new line has been added.
PHP
<?php
header("Content-Type: application/json; charset=UTF-8");
require './connection.php';
$obj = json_decode($_POST["x"], false);
$usernamequery = "SELECT * FROM User WHERE username='$obj->newUser'";
$result = mysqli_query($db, $usernamequery);
$row = mysqli_fetch_assoc($result);
if($row["Username"] == null){
$updatequery = "UPDATE User SET User='$obj->newUser' WHERE username ='$obj->username'";
$result = mysqli_query($db, $updatequery);
echo "valid";
} else{
echo "invalid";
}
?>
JS
///// USERNAME
$(document).ready(function () {
$("#userSubmitForm").on("click", function(e) {
$username = document.getElementById("user").value;
$newUser = document.getElementById("newUser").value;
user = $newUser;
obj = { "username":$username, "newUser":$newUser};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
validity = this.responseText;
if (validity === "valid"){
$('#usernameModal .modal-header .modal-title').html("Result");
$('#usernameModal .modal-body').html("Your Username Has Been Changed to '$newUser'");
$("#passSubmitForm").remove();
$("#userCloseForm").remove();
window.setTimeout(redirect,3000);
} else{
$('#error').html("This Username Already Exists"); ;
}
}
};
What is happening is responseText will be receive "valid"/"Invalid" as "valid[newline]"/"invalid[newline]"
As stated at http://php.net/manual/en/function.echo.php that can't be a "problem" of the echo. There must be some newline-character after your -tags
A simple solution would be to just trim your response text like this: var validity = this.responseText.trim(); in order to strip it from unwanted space/tab/newline characters.

calling a function with arguement as a string not working

This is part of my code to display an album on my page. If I call the function like this
<?php
for ($key_Number = 0; $key_Number < count($album); $key_Number++) {
echo 'Gallery1<br>';
}
?>
<script type="text/javascript">ajax_json_gallery('gallery1');</script>
It works fine. gallery1 is a file on my server with test photos inside. If I call it like this
<?php
for ($key_Number = 0; $key_Number < count($album); $key_Number++) {
echo ''.$album[$key_Number].'<br>';
}
?>
<script type="text/javascript">ajax_json_gallery($album[$key_Number]);</script>
It doesn't work. What am I doing wrong? Any ideas?
I need to pass different strings depending on the user so I need to give it a variable.
And yes, my array $album does contain the correct file folder names.
Here is the function that is called.
<script type="text/javascript">
function ajax_json_gallery(folder){
var thumbnailbox = document.getElementById("thumbnailbox");
var pictureframe = document.getElementById("pictureframe");
var hr = new XMLHttpRequest();
hr.open("POST", "json_gallery_data2.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
pictureframe.innerHTML = "<img src='"+d.img1.src+"'>";
thumbnailbox.innerHTML = "";
for(var o in d){
if(d[o].src){
thumbnailbox.innerHTML += '<div onclick="putinframe(\''+d[o].src+'\')"><img src="'+d[o].src+'"></div>';
}
}
}
}
hr.send("folder="+folder);
thumbnailbox.innerHTML = "requesting...";
}
function putinframe(src){
var pictureframe = document.getElementById("pictureframe");
pictureframe.innerHTML = '<img src="'+src+'">';
}
And here is the page that gets the photos json_gallery_data2.php
<?php
header("Content-Type: application/json");
$folder = $_POST["folder"];
$jsonData = '{';
$dir = $folder."/";
$dirHandle = opendir($dir);
$i = 0;
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
$i++;
$src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
This is mixing server-side and client-side code:
ajax_json_gallery($album[$key_Number]);
The variables $album and $key_number aren't defined in JavaScript, so it can't use them. (I'm sure when it's "not working" it's actually telling you on the JavaScript console that those variables aren't defined.)
To emit values from PHP, you need to surround them with <?php ?> tags. Additionally, since it's a string in JavaScript, it needs to be enclosed in quotes in the JavaScript. Something like this:
ajax_json_gallery('<?php echo $album[$key_Number]; ?>');
1st:
$key_Number varibale on your server in the line:
<script type="text/javascript">ajax_json_gallery($album[$key_Number]);</script>
Contains count($album) value, which not exists in the array.
2nd:
If you trying to output php value in this line:
<script type="text/javascript">ajax_json_gallery($album[$key_Number]);</script>
Then try to enclose output in <?php ?> tags:
<script type="text/javascript">ajax_json_gallery('<?php echo $album[$key_Number]; ?>');</script>
3rd:
Single quotes does not allow to parse variables in string.
echo ''.$album[$key_Number].'<br>';
This ^ line doing not what you expecting.
Try to use double quotes:
echo "{$album[$key_Number]}<br>";

Ajax POST / XML not working

I have two buttons I press. one calls function with argument of "1" the other calls with argument of "2"
function getOptions(scheme){
var url = "http://localhost/AV/data2.php";
var XMLHttpRequestObject = new XMLHttpRequest();
XMLHttpRequestObject.onreadystatechange = function(){
if (this.readyState != 4) return;
if (this.status == 200){
var xmlDocument = this.responseXML;
options = xmlDocument.getElementsByTagName("option");
listOptions();
}
}
XMLHttpRequestObject.open("POST", url, true);
XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XMLHttpRequestObject.send("scheme="+scheme);
//XMLHttpRequestObject.send(null);
}
and the data2.php file:
<?php
header("Content-type: text/xml");
if ($_POST["scheme"=="1"]) $options = array('black','pink','orange');
if ($_POST["scheme"=="2"]) $options = array('red','blue','green');
//$options = array('red','blue','green');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
echo '<options>';
foreach ($options as $value)
{
echo '<option>';
echo $value;
echo '</option>';
}
echo '</options>';
?>
this does not work.. it returns something about "junk after document element".. I have other parts in there i commented out and those work when i change it to GET but why doesn't this work?
It should be
if ($_POST["scheme"]=="1") // and
if ($_POST["scheme"]=="2")

Categories

Resources