Send post variable in AJAX to PHP file for varaible - javascript

What should happen:
When button clicked, it calls report.php and sends "main" as type
Type "main" is picked up in report.php and used as $typename
$data varaible is populated with the contents of main.json
What does happen:
> [25-Sep-2018 13:56:56] WARNING: [pool www] child 11 said into stderr: "NOTICE: PHP message: PHP Notice: Undefined index: type in
> /var/www/html/report.php on line 27"
> [25-Sep-2018 13:56:56] WARNING: [pool www] child 11 said into stderr: "NOTICE: PHP message: PHP Warning: file_get_contents(.json):
> failed to open stream: No such file or directory in
> /var/www/html/report.php on line 28"
> 2018/09/25 13:57:00 [error] 8#8: *5 FastCGI sent in stderr: "PHP message: PHP Notice: Undefined index: type in
> /var/www/html/report.php on line 27
index.php
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'report.php',
type: "POST",
dataType:'json',
data: ({type: main}),
success: function(result){
$("#output").html(result);
}
});
});
});
</script>
report.php
$typename = $_POST['type'];
echo $typename;
$data = file_get_contents("$typename.json");
main.json
{
"reportDescription":{ <....>
}

The problem is that you are trying to send an undefined variable main to your php file. This variable doesn't exist, so you get an error. Strings must be wrapped with single or double quotes.
You should change data: ({type: main}), to
data: {type: 'main'},
(The perenthesis are not needed)
To send the string to your PHP file.
Now in your PHP file, you need to output $data.
$typename = $_POST['type'];
echo $typename;
$data = file_get_contents("$typename.json");
echo $data;

You should change data: {type: 'main'}, as answered before.
But the php code in that answer could be improved. This code could lead to security issues, particularly to a Server Side Request Forgery. You need to set a clear boundary between the user supplied data and your application code, you need to validate the code to avoid some evil uses of file_get_contents:
One can request a random website by http or use another protocol like ssh to connect to other server reachable from your web server
Someone can scan your directories and read operating system files
So, beware what you do with user input, you need to validate it. I would use the following code.
// strip all slashes and directories, use only the filename
$typename = basename($_POST['type']);
$filename = __DIR__.'/'.basename($_POST['type']).".json";
if (!file_exist($filename)){
echo "ERROR";
}
// do not output anything till validated
// echo $typename;
// use a header to tell the user that this is a json file
header('Content-Type: application/json');
$data = file_get_contents($filename);
echo $data;

Related

Error 500 When Updating MySql Database from WordPress - Same Code Works Fine Outside of WordPress

I need to update a MySql database from inside a JS function within a WordPress Woocommerce page. I'm using Ajax to do this. The following code works fine as a stand-alone code but when I put it into the WordPress page (on my localhost) it throws an error 500. Also I put the required data (which will eventually be a variable) onto the end of the url (?test=14230) because I couldn't get it to send the data when using the data: line in the Ajax.
Here's the Ajax:
function db()
{
$.ajax({
url: 'update_db.php?test=14230',
type: 'post',
data: 0,
success: function(output)
{
alert('Success, server says '+output);
}, error: function()
{
alert('Something went wrong.');
}
});
}
Here's the update_db.php:
<?php
if(isset($_GET['test']) ){
$id = $_GET['test'];
}
include 'database-handler.php';
$sql = "UPDATE db_name SET column = 'Some Value' WHERE id = $id";
if(mysqli_query($conn, $sql)){
//echo ('<p>'."Success.".'</p>');
} else {
//echo ('<p>'."Something went wrong. $sql. " . mysqli_error($conn).'</p>');
}
mysqli_close($conn);
?>
So I'm just wondering why this works as a stand-alone code but not when it's inside WordPress?
Edit: Here is the error log:
[Wed Nov 09 15:16:47.543162 2022] [php:error] [pid 4564:tid 1828] [client ::1:5888] PHP Fatal error: Uncaught TypeError: mysqli_query(): Argument #1 ($mysql) must be of type mysqli, null given in C:\xampp\htdocs\my-sites\wowcard\wp-content\themes\blocksy-child\woocommerce\single-product\save-card-size.php:17\nStack trace:\n#0 C:\xampp\htdocs\my-sites\wowcard\wp-content\themes\blocksy-child\woocommerce\single-product\save-card-size.php(17): mysqli_query(NULL, 'UPDATE new_card...')\n#1 {main}\n thrown in C:\xampp\htdocs\my-sites\wowcard\wp-content\themes\blocksy-child\woocommerce\single-product\save-card-size.php on line 17, referer: http://localhost/my-sites/wowcard/product/polka-dot-brush-strokes-two-photo-birthday-card-purple/?card=complete&id=14230
Edit:
I believe the issue I had was due to the Ajax being embedded within more than one WordPress function and also a Woocommerce action. The variable I needed was not being passed from my PHP to the Ajax like it normally would be. I used a session variable instead, which fixed that particular issue.
The Ajax now uses the "data:" line to pass the data over to save-card-size.php rather than passing it inside the url. I would show the code but the editor is too glitchy on this site, it wouldn't allow me to copy and paste my code properly.
I also had to replace the include in save-card-size.php with the contents of database-handler.php.
Everything is now working.
WordPress has its own database handler which is automatically loaded, there are most likely conflicts between your code and WordPress, but without seeing the actual error, I can not give more information.
Check this out https://developer.wordpress.org/reference/classes/wpdb/
Example:
global $wpdb;
$results = $wpdb->query($wpdb->prepare( 'UPDATE db_name SET column = 'Some Value' WHERE id = %d' , $id ));

Writing a JSON object to an existing .json file

EDIT: My error checking shows that the php is being executed but when I check my .json file it's still the same as before.
I apologize in advance since this has been asked before but I've spent hours trying out different things and none have worked. Hopefully this might help someone in a similar situation. I'm trying to append a new entry to my existing json object from user input and write the updated json object back to the file. The last part is what's giving me trouble.
Here I'm using ajax to send my json object to a php file
$.getJSON("http://existing.json", function(data){
//append new entry to previous json array
data['posts'].push(objectt);
//confirming that new object is correct
console.dir(data);
//Sending json object to .php file so it can write to .json file
$.ajax({
type : "POST",
url : "json.php",
//data : data, this was changed to
data : {json:data}, //by the suggestion of suggested by madalin ivascu
dataType: 'json'
});
The above block of code executes and no errors are displayed in the console. Here is my json.php file. After the next block of code executes my .json file does not have the new entry.
$json = $_POST['json'];
if ($_POST['json'])
{
$file = fopen('simple.json','w+');
fwrite($file, $json);
fclose($file);
echo: "File was updated";
}
else
{
// user has posted invalid JSON, handle the error
print "Error json was null";
}
Change data : {json:data},
Return something from the php
$json = $_POST['json'];
if (json_decode($json) != null)
{
$file = fopen('simple.json','w+');
fwrite($file, $json);
fclose($file);
echo "File updated";
}
else
{
// user has posted invalid JSON, handle the error
print "Error json was null";
}

Errors while parsing invalid JSON passed from PHP to AJAX

I'm trying to parse JSON sent by PHP.
JSON:
[{"id":"1","value":"1"},{"id":"4","value":"1"},{"id":"2","value":"1"},{"id":"3","value":"1"},{"id":"4","value":"1"}]
I'm trying to parse it to get the id and pass it to another JavaScript function and I'm continuously calling the PHP. When I tried $.ajax, $.get, $.getJSON and used JSON.parse and parseJSON, I get this error:
Uncaught SyntaxError: Unexpected token <
because the JSON looks like this:
id: id: id: html> 1id: 4id: 1id: 2id: 3id: 4id: id: id: >
I tried to fix it using JSON.stringify, which caused this error:
Cannot use 'in' operator to search for 'length' in
and now I'm stuck and have no idea how to fix this.
test.php:
<?php
$link = mysql_connect("localhost", "root", "password");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db("example");
$sql = "select * from data";
$x = mysql_query($sql);
$emparray = array();
while ($row = mysql_fetch_assoc($x)) {
$emparray[] = $row;
}
echo json_encode($emparray);
mysql_close($link);
?>
heatmap.html:
<script>
$(window).ready(function(){
$.ajax({
url:'test.php',
data:"{'id':'1', 'value':'1'}",
contentType: "application/json; charset=utf-8",
datatype: 'json',
success: function (data){setInterval(function(){
/* if I use parseJSON(data), I get "Unexpedted token <"
error */
$.each(data, function (id, value){ // error occures here
liveHeatMap(id); //Never called
});
}, 10000)}});
});
</script>
I think the problem is that the JSON is invalid. I have tried so many things and looked at many other similar problems but I still cannot fix it.
Remove the contentType and dataType properties in your AJAX request, and use an object (rather than a string) for your data. In your success function, remove the setInterval and manually parse the JSON string returned using JSON.parse(data). This ensures you have the most control over the data to prevent jQuery from causing problems (and also makes it clearer). jQuery may be interfering with the data in the process and you want the complete raw data.
It looks like you're receiving HTML. Common causes:
Your AJAX URL is pointing to the incorrect place (and it may not seem obvious -- try ./test.php or using an absolute path).
Your PHP is not killed after echoing the JSON. Replace mysql_close($link) with die() as when the script ends, all database connections are automatically closed anyway.
If you're still having issues, run these commands and comment their output:
console.log(data);
console.log(typeof data);

Download zip works from html form but not from ajax

I have this code and it's working fine
HTML
<form method="POST" action="http://example.com/downloadtest.php">
<button type="submit">Submit button</button>
</form>
PHP (downloadtext.php)
header("access-control-allow-origin: *");
$urls = array("www.domain.com/image1.jpg", "www.domain.com/image2.jpg");
//php code do download the images to a temp folder
function createZipfile($folderName) {
// make sure to send all headers first
// Content-Type is the most important one (probably)
//
header('Content-Type: application/octet-stream');
header('Content-disposition: attachment; filename="myzip.zip"');
// use popen to execute a unix command pipeline
// and grab the stdout as a php stream
// (you can use proc_open instead if you need to
// control the input of the pipeline too)
//
$fp = popen('zip -r -j - tmp/'.$folderName, 'r');
// pick a bufsize that makes you happy (8192 has been suggested).
$bufsize = 8192;
$buff = '';
while( !feof($fp) ) {
$buff = fread($fp, $bufsize);
echo $buff;
}
pclose($fp);
}
I get a zip-file. But I want to know when all the images are downloaded so I am trying to use ajax insted with jsonp. I am using the same PHP code.
I want to replace the html form with ajax post. I now have this html and javascript (ajax post) instead of the html post form. The php script i still the same.
html
<button class="download-all-images">Download</button>
javascript
$(".download-all-images").click(function(){
$.ajax({
url:"http://example/downloadtest.php",
type: "POST",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
success:function(json){
alert("Success ");
},
error:function(e){
alert("Error " + e.message);
}
});
});
I'am not getting any zip file with the ajax method and ajax gives me "Error: undefined". I get "Success" if I comment out the zip-file code but keep the code that downloads the images to a temp folder. My php script is not on the same server as the site (html/javascript). And I get a response with this in my php file
echo $_GET['callback'] . '('.json_encode($urls).')';
if I comment out my zip-function.

How to use AJAX and JSON to get data returned from a PHP file

For starters this website is being run on a Debian machine.
I have a SQLite3 database that has current news articles in it. I am trying to use PHP to query the database for these articles, and pass it as JSON to AJAX, so it can be displayed on my webpage. Right now nothing is being shown and I don't know where the error is.
Here is the PHP code to get the information from the database:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('website.db');
}
}
$db = new MyDB();
$result = $db->query('SELECT * FROM news');
echo json_encode($result);
?>
Here is the JavaScript where the AJAX is located:
<script type="text/javascript">
function getNews()
{
console.log("firstStep");
$(document).ready(function()
{
console.log("secondStep");
$.getJSON("http://localhost/getNews.php",function(result){
console.log("thirdStep");
$('news').append(result); // display result
});
});
}
I think the error is occurring around $.getJSON("http://localhost/getNews.php",function(result), as in the console, thirdStep is never being outputted.
This is the HTML it should be appending to:
<div id = "newsEntry"> <news> test </news> </div>
Any help would be appreciated.
To find out what's going on, you might want to add an error handler:
$(document).ready(function() {
$.ajax({
url: "http://localhost/getNews.php",
dataType: "json",
success: function(result) {
console.log("thirdStep");
},
error: function(err) {
alert(err);
}
});
})
By default, the web server serves content as application/html. So when you simply echo a JSON string, it's treated like text on a html page. To really return JSON from your server, you need to specifically set it.
Include this line before your echo:
header('Content-Type: application/json; charset=utf-8');
Edit
On inspection of you PHP code, you are missing one line. Note that $db->query() returns you an SQLite3Result. You need to call:
$array = $result->fetchArray(SQLITE3_ASSOC); // get an associative array first
$json = json_encode($array);
header('Content-Type: application/json; charset=utf-8');
echo $json

Categories

Resources