Javascript receiving NULL object from PHP - javascript

I'm trying to send a JSON object from PHP to my Javascript code. I'm new to PHP, so I'm running into some troubles achieving this. As a note, all of my HTML, PHP, and javascript code are contained within a single PHP file. I looking for solutions that don't use AJAX or Jquery, so I've been trying the json_encode method. Unfortunately, while my code will compile, my javascript object seems to be NULL after I parse it.
I have tried json_encode from a variable in javascript and, while there are no errors, it still returns a NULL object. I also have tried to send it to a hidden form field and retrieve it from there using DOM, to little success. I suspect that maybe my PHP code is simply not running after form submission, but I don't know if that is the root of my issue or my syntax is incorrect when attempting to transfer a php object to my javascript code.
<?php
$street = $city = $state = $location = $url = $lat = $lon = "";
$geolocation = $coords = $temp = $details = null;
$temparray = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['location']) && $_POST['location'] == 'Yes'){
$geolocation = json_decode($_POST["geolocation"]);
$lat = $geolocation->lat;
$lon = $geolocation->lng;
$details = find_forecast($lat, $lon);
}else{
$street = $_POST["street"];
$city = $_POST["city"];
$state = $_POST["state"];
$temparray = find_coords($street, $city, $state);
$lat = $temparray[0];
$lon = $temparray[1];
$details = find_forecast($lat, $lon);
}
}
?>
I didn't include the functions in my php code above because I know that the php code itself works (I tested in a separate environment with hardcoded values).
<script type="text/javascript">
document.getElementById('theform').addEventListener('submit',
function(evt){
evt.preventDefault();
var stuff = "<?php echo json_encode($details); ?>"; //tried 2 ways
to achieve
var arr = JSON.parse("<?php echo json_encode($details); ?>"); //2nd
way to test if it would work
console.log(arr);
document.getElementById("timezone").innerHTML = "<p
id='timezone'>" + arr.timezone + "</p>";
})
This is my javscript code where I try to retrieve the JSON object, encode it, and parse it. Unfortunately, my "arr.timezone" results in a "undefined" value and my console.log(arr) results in "null".
<form id="theform" onSubmit="return checkInput()" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" target="testiframe">
<h2><i>Weather Search</i></h2>
<label for="street"><b>Street</b></label>
<input id="street" name="street" type="text" value="">
<div class="sub-entry">
<input type="checkbox" id="location" name="location" value="Yes">
Current Location
</div>
<br><br>
<label for="city"><b>City</b></label>
<input id="city" name="city" type="text" value="">
<br><br>
<label for="state"><b>State</b></label>
<select name="state" id="state">
<option value="state">State</option>
<option value="line">----------------</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
<br><br><br><br>
<div class="button">
<input id="search" name="Search" onclick="checkInput()"
type="submit" value="Search">
<input id="clear" name ="clear" onclick="clearform()"
type="button" value="Clear">
</div>
</form>
<div id= "blue" class="blue">
<p id="timezone"></p>
</div>
If it helps, this is part of my form. My file is named hello.php at the moment. Additionally, I have the target = testiframe (also an iframe tag at the bottom of my html) because I researched that it is a way for you page to not refresh after a form submission, as I wanted the user input values to remain after you submit. I tried removing this feature, and my javascript still didn't work properly though.
I've gotten no syntax errors. I should receive a JSON object from my find_forecast() and my data.timezone should not be undefined.Any help would be appreciated, as I've been stuck on this problem for awhile.

json_encode() formats the result so it's a valid JavaScript literal. Don't put quotes in the JavaScript when you use <?php echo json_encode(...) ?>. You also don't need to call JSON.parse() (but if you do, you have to put it in single quotes, because double quotes are used in the JSON itself).
<script type="text/javascript">
document.getElementById('theform').addEventListener('submit', function(evt){
evt.preventDefault();
var stuff = <?php echo json_encode($details); ?>;
console.log(stuff);
document.getElementById("timezone").innerHTML = "<p id='timezone'>" + stuff.timezone + "</p>";
})

Related

Use AJAX to run PHP script and then return single value

Okay, this question was closed for not being clear enough, so I'm going to completely re-write it in as clear a form as I can...
Project: Room Booking System
Required Function: Check the database for existing bookings matching a criteria, return the result of 'COUNT' SQL query to a textbox which another function then looks to.
The values which need to be inserted into the COUNT criteria are as follows:
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
</br>
Problem: I have a functioning php script which counts the number of rows in the database matching a criteria, which will then return the result to a textbox (main function sorted) when set up in a test directory with nothing else on the page. However, when I embed this php into an existing page (the new booking page) it doesn't work when the 'Check Availability' button is clicked. Instead, it reloads the page (as php does) which is not useful when users have already input their data for checking (and would need to re-enter it). I've Googled and have found that I need to use AJAX to run the php function in the background and then return the result to the textbox on the current page. I have never ever used AJAX and are only new to php, js etc. as it is, so I have no idea what I'm doing
How can you help: I need help in converting my existing code into a working solution to the above problem, probably using a combination of AJAX, PHP and JS functions.
Code:
PHP COUNT CODE (works)
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '2019-12-30' AND Time = 'Period 6' AND Room = 'C3'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
Area of php/html in which the result should be returned (id="availresult")
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
Test AJAX function, as suggested by an existing reply to my post
<script>
function soflow() {
$.post('checkAvailability.php', {info: 'start'}, function(data) { //if you don't need to send any data to the php file then you can set the value to whatever you want
document.getElementById('availResult').innerHTML = data;
});
}
</script>
I have tried various ways to do this myself, including modifying the suggested AJAX code above, but I'm not sure how to get my values from my various textbox over to the PHP function. Also, I don't know how to tell whether the AJAX function is running, or whether there is an error somewhere. At present, the value shown in my 'availresult' textbox does not change.
I appreciate any help with this, and thank anyone who has tried to help so far. I'm not sure how much clearer I can make this - please don't close the question again.
UPDATE:
(index.php):
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h4>Date:</h4>
<input required type="text" name = "datebox" id = "datebox" ><br/>
<h4>Timeslot:</h4>
<input required type="text" name = "timebox" id = "timebox" ><br/>
<h4>Location:</h4>
<input required type="text" name = "roombox" id = "roombox" ><br/>
<h4>Person:</h4>
<input required type="text" name = "bookerbox" id = "bookerbox" ><br/>
<br/>
<h2>Check availability</h2>
<h4>Click the button below to check whether your options are available:</h4>
<h4>This will only check against other bookings. It is your responsibility to use the timetable above to check whether the room is actually free.</h4>
<button onclick="soflow()" id="checkAvail" >Check Availability</button>
<input onclick="unhideReview()" type="button" id="continue" value="Continue" disabled />
<input type="text" style="width: 30px;" id="availresult" value="1" />
<script>
function soflow() {
var var_date = $('#datebox').val();
var var_time = $('#timebox').val();
var var_room = $('#roombox').val();
$.post('checkAvailability.php', {info: 'start', date: var_date, time: var_time, room: var_room}, function(data) {
document.getElementById('availResult').innerHTML = data;
});
}
</script>
</body>
</html>
(test.php):
<?php
if(isset($_POST['info'])) {
$con = mysqli_connect("x", "x", "x", "x");
if (mysqli_connect_errno()) { // Check connection
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = mysqli_real_escape_string($con, $_POST['date']);
$time = mysqli_real_escape_string($con, $_POST['time']);
$room = mysqli_real_escape_string($con, $_POST['room']);
$sql="SELECT COUNT(*) FROM `Existing_Bookings` WHERE Date = '$date' AND Time = '$time' AND Room = '$room'";
if ($result=mysqli_query($con,$sql)) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
echo $rowcount; // echo the data you want to send over ajax
}
?>
You could also do ajax with pure JavaScript, but this is simpler.
Also note that this is just an example on how to do an ajax connection in the first place.

How to send an array using GET request from a input form in PHP?

I'm retrieving data from the database and I am using GET request to send the data to a page to delete the data. Now, I want to send an array which contains multiple tr's to delete the data and I want to do this using GET request, not POST request.
Please help!
Thanks
Convert form inputs into an array info[item1], info[item2], info[item3]..
Example:
<form action="process.php" method="GET">
input 1<br>
<input type="text" name="info[item1]"><br>
input 2<br>
<input type="text" name="info[item2]"><br>
input 3<br>
<input type="text" name="info[item3]"><br>
<br>
<input type="submit" value="Submit">
</form>
Get form inputs in PHP:
<?php
//Do not use $_GET to access superglobal $_GET Array Directly.
//Use filter_input_array() function.
$request = filter_input_array(INPUT_GET);
//Get form inputs of array 'info'
$input = $request['info'];
//Get form input value
foreach ($input as $key=>$value)
{
echo "<p>{$key}=>{$value}</p>";
}
Output:
item1=> 1 // Input value to delete.
item2=> 2 // Input value to delete.
item3=>3 // Input value to delete.
You can separate the arguments with ',' and use the code below to get a array.
$id_string = $_GET['id'];
$id_array = explode(',', $id_string);
Let assume that you have data in form of the array $data
<?php
$data= array(1,2,3,4,5,6);
?>
<form action="test.php" method="GET">
<input type="hidden" name="data" value="<?php print base64_encode(serialize($data)); ?>"><br>
<input type="submit" value="Submit">
</form>
After form submition it will create a url with querystring having coded value of you array.
We can get that value on test.php page and use that to delete rows according to your data(getting from URL).
<?php
$str_var = $_GET["data"];
$array_var = unserialize(base64_decode($str_var));
foreach($array_var as $id)
{
echo $id;
$server=mysqli_connect('localhost','root','');
$re=mysqli_query($server,"DELETE FROM `table` WHERE id=$id");
}
?>
Try to pass your data ids as string with commas separated like:
https://your.url.here/?ids=1,3,5,7,8
and server splits the commas to retrieve values.
For example:
var url_string = "http://www.example.com/t.html?ids=1,2,3,4,5";
var url = new URL(url_string);
console.log(url.searchParams.get("ids").split(','));
Hope this helps :)

How do I out put a PHP var containing JS into a form value?

I have a javascript to generate ETH address and private keys. I want to output the value of the private key and the address to a hidden field in a registration form.
However..
As plain PHP, this outputs the desired results:
$wallet_address = "<script type='text/javascript'>document.writeln(wallet.address);</script>";
echo $wallet_address;
But, when I try and put the $wallet_address into a form field:
<input type="hidden" name="user_wallet" id="user_wallet" class="input" value="<?php echo $wallet_address; ?>" />
I dont get the address, I get the javascript source line: <script type='text/javascript'>document.writeln(wallet.address);</script>
How do I get the value of $wallet_address to be the actual address in the form field?
You echo the script, not the render of the script;
Do sth like :
$wallet_address = '<script type="text/javascript">function writeWallet(){ document.getElementById(user_wallet).value = "yourAdress";} window.onLoad(writeWallet);</script>';

Ajax not firing in div populated by ajax

I have a div which is populated via an ajax request.
Within the div is a form which when completed should use the same type of ajax request to populate a further div. I have used the same method to create both but the second javascript does not run:
First one (which works):
<div class="content_text" id="searchbysurname">
<p><form name="searchbysurname">
<b>Search by Surname: </b><input class="inline" type="text" name="q">
<input type="submit"></form>
<script>
$('#searchbysurname form').submit(function(){
var data=$(this).serialize();
// post data
$.post('searchbysurname_test.php', data , function(returnData){
$('#resultstable').html( returnData)
})
return false; // stops browser from doing default submit process
});
</script>
<div id="resultstable"></div>
Second one (which is in the resultstable div) that doesnt work:
<? require_once("dbcontroller.php");
$db_handle = new DBController();
$q = ($_POST['q']);
$employees=array();
$sql = "SELECT employees.employeeid, employees.firstname, employees.surname FROM employees where UCASE(employees.surname) LIKE UCASE('%".$q."%')";
$employees = $db_handle->runQuery($sql); ?>
<table class="invisible">
<?
if(isset($employees) && !empty($employees)){
foreach($employees as $k=>$v) {
?>
<tr><td><?php echo $employees[$k]["firstname"]; ?> <?php echo $employees[$k]["surname"]; ?> </td>
<td><div id="viewemployeedetails<? echo $employees[$k]["employeeid"]?>">
<form>
<input type="hidden" name="id" value="<? echo $employees[$k]["employeeid"]?>">
<input type="submit" value="View">
</form>
</div></td>
<div id="mainpart"><b></b></div>
<script>
$('viewemployeedetails<? echo $employees[$k]["employeeid"]?> form').submit(function(){
var data=$(this).serialize();
// post data
$.post('viewemployeedetails.php', data , function(returnData){
$('#mainpart').html( returnData)
})
return false; // stops browser from doing default submit process
});
</script>
I know it's not related to your question but you shouldn't be using the PHP short tag notation, it has been deprecated: https://softwareengineering.stackexchange.com/questions/151661/is-it-bad-practice-to-use-tag-in-php
Your first block of code is HTML with inline Javascript, which is an awful way to do things, you will get hard to debug errors if you insist on using Javascript in this way. You should be putting your Javascript in a separate file from the HTML and including it just before the final body tag. Ideally you should be using window.onload (or other similar methods, like a closure or jQuery's .ready() method) to ensure that DOM traversing elements of your script are only parsed after the DOM is fully loaded.
Your second block of Javascript code will never run because it doesn't exist when the browser parses the HTML. It's only injected later but Javascript doesn't work that way. You can inject javascript dynamically but not like that. You would have to do something like this:
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://www.somedomain.com/somescript.js';
headID.appendChild(newScript);
I took this code from here: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS

post image, selected values to php via Javascript

Hello as part of my website project I am writing an item input form, the website itself is very simple, the user will:
Write item name
Select some values
Write item description in textarea
Upload item image
the page will collect this info using JS and then sent to PHP page where it will be checked and then inserted into database. I am not sure what is wrong with the code --php page gives no errors-- as it is not responding after submission, tried resolving by process of elimination, deleting the image part in JS seems to make the button respond though no output is given.
<!DOCTYPE HTML>
<html>
<header>
<title> Results </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</header>
<body>
<form method="post" enctype="multipart/form-data">
<fieldset>
<legend>Add item form.. </legend>
<p> fill out the below details </p>
<p> Item name will be publicly viewed by users: <input type="text" id="itemID" name="itemName" placeholder="Enter item name.." /> </p>
location:
<select id="locSelect"> //4 options for every select
<option id="mountainID" value="mountain"> Mountain </option>
</select>
Category:
<select id="catSelect">
<option id="appliancesID" value="appliances"> Appliances </option>
</select>
Price range:
<select id="rangeSelect">
<option id="range1ID" value="range1"> 0-$50 </option>
</select>
<p> <input type="textarea" id="descriptionID" name="descriptionName" style="height:185px;width:400px;" placeholder="Please enter any item relevant info in this area..." /> </p>
<p> Upload Image: <input type="file" id="itemImageID" name="itemImage" /> </p>
<p> <input type="button" id="addID" name="add" value="Add item" onClick="runAdd();" /> </p>
</fieldset>
</form>
<div id="addResult"></div>
<script type="text/javascript">
function runAdd()
{
var item = $("#itemID").val();
var location = document.getElementById("locSelect"); //id of select
var selectedLoc = location.options[location.selectedIndex].text;
var category = document.getElementById("catSelect");
var selectedCat = category.options[category.selectedIndex].text;
var range = document.getElementById("rangeSelect");
var selectedRange = range.options[range.selectedIndex].text;
var textArea = document.getElementById("descriptionID").value;
var itemImg = document.getElementById("itemImageID");
$.post("itemDatabase.php", {
itemDB: item,
locationDB: selectedLoc,
categoryDB: selectedCat,
rangeDB: selectedRange,
textareaDB: textArea,
itemImgDB: itemImg },
function(data)
{
if(data == "int echoed by php page"){
$("#addResult").html("item/text is blank..");
//php will echo back to addResult <div> if input is not set
}
}
);
}
</script>
</body>
</html>
I believe I am sending the textarea, select and image parts wrongly, as php echos nothing for them when they are empty. I looked up codes online though they were separate from my case usually involving AJAX or PHP exclusively.
<?php
session_start(); //for userID, different page stores it
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("project_database");
if (isset($_POST['add'])){
if(empty(trim($_POST['itemDB']))) { // if(!($_POST['itemDB'])) not working
echo "0"; }
else { $item = mysql_real_escape_string($_POST['itemDB']); }
if(isset($_POST['locationDB'])){
$location = $_POST['locationDB'];
} else {
echo "1"; }
if(isset($_POST['categoryDB'])){
$category = $_POST['categoryDB'];
} else {
echo "2"; }
if(isset($_POST['rangeDB'])){
$range = $_POST['rangeDB'];
} else {
echo "3"; }
if(empty(trim($_POST['textareaDB']))) {
echo "4"; }
else { $description = mysql_real_escape_string($_POST['textareaDB']); }
if(getimagesize($_FILES['itemImgDB']['tmp_name']) == FALSE)
{
echo "5";
}
else
{
$image = addslashes($_FILES['itemImgDB']['tmp_name']);
$image = file_get_contents($image);
$image = base64_encode($image);
}
$query = "INSERT INTO item (item_name, item_description, item_price_range, item_img, item_location, user_id, category_id) VALUES ('".$item."', '".$description."', '".$range."', '".$image."', '".$location."', '".$_SESSION["userID"]."', '".$category."')";
$itemAdded = mysql_query($query);
if($itemAdded) {
echo " Item " .$item. " has been added successfully "; }
else { echo " something went wrong "; }
}
?>
category_Id and user_id are foreign keys,
Image is stored as BLOB in database (checked code working on different page)
I understand some functions are deprecated, but this is how I was instructed to complete my task, I am using notepad.
I have posted most of the code to ensure I understand what is wrong or how I can improve it in the future, I appreciate any pointers or tips just to get me on the right path at least so I can fix this.
Thank you again for any help in advance.
To answer your question about uploading images via AJAX, this was not possible before but it is now possible via FormData objects (but it is a relatively new feature and is not compatible with older browsers, if that matters to you).
You might either want to upload the image separately (old fashioned), or I suggest you look into using FormData.
This link below should be helpful (I hope):
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
Hope this helps :)

Categories

Resources