How to use AJAX to POST to PHP? - javascript

As I asked here I would like to know how I could pass the data from a simple JS function to php, and log it there.
I found this answer and tried to follow it. This is my code right now (both in the same file)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getClientScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH)
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
<script type="text/javascript">
getScreenResolution();
</script>
</body>
</html>
<?php
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
if(isset($_POST['screenResolutionW'])) {
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH
."\r\n");
fclose($fh);
}
?>
However, this does not work.
I wouldn't know how to fix this, whenever I try to google this problem people use more advanced methods, that I wouldn't even know how to start with.
Edit: My PHP and HMTL are in the same file (index.php).
Edit 2: Removed old code for clarity.
This results in these error messages:
Notice: Undefined index: screenResolutionW in index.php on line 153
Notice: Undefined index: screenResolutionH in index.php on line 154

What you want to do with $.post is include your data like this:
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
where the first of the pair is the POST identifier (the ['screenResolutionW']) and the second of the pair is the variable value.
You will also want to change your POST identifiers to be quoted:
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
Otherwise, you will get a warning about constants. I have also corrected the spelling in these variables, to reflect what you're trying to write into your file.
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH ."\r\n");
EDIT
Part of the problem is that you never call the function to execute it. Here is your HTML with the additions I have suggested, plus calling the function:
EDIT TWO
Added an onload handler for the document:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
</body>
<script type="text/javascript">
$(function() {
getScreenResolution();
});
</script>
</html>
OTHER NOTES
You really should separate the PHP code and place it in a different file because when you run the page as it is now you should get one line logged that has no variables when the page initially runs, then one logged line when the JavaScript fires after the page loads.
Then once separated you should not run your PHP until you test for the existence of a variable, for example:
if(isset($_POST['screenResolutionW'])) {
// your code to write to the file here
}
EDIT THREE
I placed all of the JavaScript in the same script block in the head of the file and have tested again:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(function() {
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("post_test.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
getScreenResolution();
});
</script>
</head>
<body>
</body>
</html>
Here you can see the variables are being posted:

Adapting the others answers.
try it:
function getScreenResolution() {
"http://example.com/index.php", screenResolutionW + screenResolutionH
$.ajax({
url: '/index.php',
method: 'POST',
data: {
screenResolutionW : screen.width,
screenResolutionH : screen.height
},
success: function(data) { console.log(data); }
});
}
And in your PHP
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
echo $screenResolutionW . " - " . $screenResolutionH;

you have to use serialize the array before doing post request.
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
var serializedArr = {
width: screenResolutionW,
height: screenResolutionH
};
$.post('/index.php', serializedArr, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
In the server end, you will get values in $_POST variable.

Apart of all those mistakes you have discovered thanks to other replies, you have these:
$screenResoltuionW = ...
Notice you wrote "ltuion" and in the fopen command you have it correct. screenResolutionW
Same thing with $screenResoltuionH...
That's why you don't get any value in the file, because those variables doesn't exists.

Related

Getting jquery post value and checking it with php

Briefly, i work on to create a Wordpress plugin. In this plugin, i need a progress bar that moving on according to background process. So, I determined a specific php file which contains my custom functions. Let's call this 'func.php' . Also, there is a file that acts as plugins main page file. We can call it 'main.php' .
So; I designed a concept in my head. On the main page, when I click begin button (named 'buttonbegin'), a jquery post being sent to func.php . I can control this POST value with these codes in func.php:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'buttonbegin':
func1();
break;
case 'otherbutton':
func2();
break;
}
}
After it, func1 executes. In this function, i had these codes for testing:
function func1() { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var itemnumber=0;
for (var i = 1; i <= 3000; i++) { //it should be execute 3000 times because of nature of process
itemnumber++;
if (itemnumber == 30) {
var value = "mystring";
var ajaxurl = 'fullurl+pluginsdirectory/main.php', //func.php and main.php are in same folder
data = {'action': value};
$.post(ajaxurl, data, function (response) {
});
itemnumber=0;
}
}
});
</script>
<?php
}
At this point in this func1, I wanna do another jquery post to make a trigger mechanism for progress bar on main.php . And finally, there is some javascript code to control this last jquery post and expand 1% progress bar. Here is the script codes in main.php :
<script type="text/javascript"> //below are for the first process i told
var width = 0;
var addition = 1;
jQuery(document).ready(function($) {
$('#buttonbegin').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'fullurl/func.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
});
});
//actual part starts here
var continuous = setInterval(function() {
var code = <?php echo !isset($_POST['action']) ?>; // the source of the problem
if(!code) {
var percent = $("#myBar").width() / $("#myBar").parent().width() * 100;
if (percent == 100) {
clearInterval(continuous);
}
var element = document.getElementById("myBar");
element.style.width = (width+addition) + "%";
element.innerHTML = (width+addition) * 1 + "%";
width = width + addition;
}
}, 1000);
});
</script>
But it doesn't work. When i print the 'code' variable with console.log, I see NaN value. The php code inside script tags doesn't work properly. Is there any mistake? Or is there another simpler way to do whole process?
Note: Necessary jquery cdn links are included in main.php and func.php both. This is how its look like:
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>

How to get an php echo with jquery

I know this question was asked many times before, I searched really long for the solution but I couldn'd find one, that's why I'm asking. First: I'm trying to connect my HTML-File to my JavaScript file and that worked pretty well. What I want to do now is to display data from my MySql-DB on my HTML-Site, that's why I'm using PHP. I wanted to start simple, that's why I tried to echo "Hello World". But when I run my site, I don't get only "Hello World", I'm getting the whole PHP-Code. How can I fix that problem?
test.php
<?php
echo 'Hello World';
index.html
<!DOCTYPE html>
<html>
<head>
<title>MySite</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<input type="text" id="size">
<button id="saveBtn" value="Click" type="button" >Save</button>
<script src='test.js'></script>
</body>
</html>
test.js
window.addEventListener("load", function () {
$('button#saveBtn').on('click', function () {
var in= $('input#size').val();
if (size== '')
alert("Error");
else {
$.post("test.php", { input: size}, function (data, status) {
alert("data + " : " + status);
});
}
});
});
Everything is actually working fine, except you have some typos in your Javascript file:
You can't use the word in as a variable name, because it is reserved as a Javascript keyword.
The second parameter that you had on the $.post() function is illegal.
The way you concatenated the message in the alert was faulty.
It should look like this to work:
window.addEventListener("load", function () {
$('button#saveBtn').on('click', function () {
var theInput = $('input#size').val();
if (size== '')
alert("Error");
else {
$.post("test.php", function (data, status) {
alert(data + ":" + status);
});
}
});
});
ALSO
It looks like you're trying to prevent the user from sending off the AJAX request until there is something in the input. If this is what you are trying to do then you can do it like this:
window.addEventListener("load", function () {
$('button#saveBtn').on('click', function () {
var theInput = $('input#size').val();
if (!theInput.length) // Checking to see if there's something in the input
alert("Error");
else {
$.post("test.php", function (data, status) {
alert(data + ":" + status);
});
}
});
});
NOTE: It's important to note that in order for your PHP to run at all, you need to set up a local server (This might be why you are getting
PHP errors). You can do that by either installing XAMPP or you can
follow these instructions.

Can't Get Data Into Flot With AJAX

I am using the code below to graph data into flot, and when I print out dataOne, it returns properly formatted values for flot, however when I set it as the data for flot to graph, flot forms a graph but then has no data points?
<!DOCTYPE HTML>
<html>
<head>
<title>AJAX FLOT</title>
<script language="javascript" type="text/javascript" src="../../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.time.js"></script>
</head>
<body>
<div id="placeholder" style="width: 100%;height: 600px;"></div>
<script language="javascript" type="text/javascript">
var options = {
lines: {
show: true
},
points: {
show: true
},
yaxis: {
min: "0",
max: "1023"
},
xaxis: {
mode: "time"
}
};
function update() {
$.ajax({
url: "http://localhost/data.php",
context: document.body
}).done(function(response) {
dataOne = response;
var d = "[" + dataOne + "]";
var plot = $.plot($('#placeholder'), [d], options);
setTimeout(update, 1000);
});
}
update();
</script>
</html>
Finally to the root of the problem. If it's valid JSON, dataOne must be an array of arrays:
[[1412393775000, 277], [1412393777000, 277], [1412393778000, 277]]
Note the extra brackets. Check your console.log carefully.
Doing this:
var d = "[" + dataOne + "]";
in JavaScript, automatically converts it to a string.
What you need is an array of array of array (the inner most is a point, the second is a series, the outer is a collection of series):
var d = [dataOne];
And then just
var plot = $.plot($('#placeholder'), d, options);
For those of you who may want to do something similar, here is the code I used to finally make it work. :)
First off, the page that produced the value the PHP file collected was incorrect. The Arduino was using AJAX to update the value every second, but I realised this was stupid as the page was called every second from the main AJAX call which called data.php which then called this page. So I removed the AJAX from the Arduino Web Server code.
Since the code was not working and I had spent hours trying I started to look around for alternatives. In highcharts.js I found some AJAX code, and decided to try it. Here is the code I ended up with:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>AJAX FLOT</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script language="javascript" type="text/javascript" src="../../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.time.js"></script>
</head>
<body>
<div id="placeholder" style="width: 100%;height: 600px;"></div>
<div id="div" style="width: 100%; height: 100px;"></div>
<script type="text/javascript">
var options = {
lines: {
show: true
},
points: {
show: true
},
xaxis: {
mode: "time"
}
};
window.setInterval(function(){
$.getJSON('http://localhost/data.php', function (csv) {
dataOne = csv;
var plot = $.plot($('#placeholder'), [dataOne], options);
});
}, 1000);
</script>
</html>
After that, I had to get the data.php working properly. I had a problem where
file_get_contents
Would not only get the output of the Arduino, but also many of the tags surrounding it. This stuffed up my data. So I gave up with the proper html tags and just printed out the plain value. So if you went to the page source of the Arduino's output, there are no tags surrounding the value, all you see is a number. So that stopped that issue.
Here is the php code I use to format the values:
<?php
$file = "data.txt";
$webpage = "http://192.168.1.177/";
$t = time() * 1000;
$current = file_get_contents($file);
$data = file_get_contents($webpage);
if ($current < "1") {
$current .= '[[' . $t . ', ' . $data . ']]';
file_put_contents($file, $current);
echo $current;
}
else {
$cut = substr($current, 0, -1);
$cut .= ', [' . $t . ', ' . $data . ']]';
file_put_contents($file, $cut);
echo $cut;
}
?>
To get the data into the appropriate brackets, you can see that when no data is present in the file, the if statement does not include a comma and space, because there is no other set of data to separate from. As soon as one value is in the file, I use substr to get rid of the last containing bracket, then append the comma, space and then values, with the containing bracket put again at the very end of the data where it should be.
Anyway, this ended up working like a dream. Thanks for everyones help :)

My jquery script only works in Firefox, why?

<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<body>
<div id="div1">dv1</div>
<div id="div2">dv2</div>
<script type="text/javascript">
function getData(){
$.ajax({
type:"GET",
url:"j.json",
dataType:"json",
success: function(jsondata){
output(jsondata);
}
});
}
function output(json){
//var Data = eval('(' + json + ')');
var html = '';
//alert(Data.length);
for(var i=0;i<json.length;i++){
html += ' name:' + json[i].name + ' age:' + json[i].age;
}
document.getElementById('div1').innerHTML = html;
document.getElementById('div2').innerHTML = json[0].name;
}
setTimeout(getData, 3000);
</script>
</body>
</html>
j.json file is
[{"name":"aaa","age":18},{"name":"bbb","age":19}]
The aim of above code is to update div content with data in local json file. I've tried that in IE & Chrome, but neither worked. I've googled a lot but still can't figure it out.
Anyone got any hints? Thanks in advance.
Do you use web server?
AJAX calls doesnt work with URL starting with file://. This because of the same-origin requirements which were instituted to help deal with cross-site scripting (XSS). See here for more details.
And as I noticed, you should use $(document).ready(function(){ your code }) instead of setTimeout(getData, 3000);

Redirecting to the root using javascript

In my project I have the following script in order to open a page:
<script type="text/javascript">
function setPage(pName) {
var iPage = "'" + pName + "'";
document.getElementById('iFrame').src = window.location.href(iPage);
}
</script>
when I run the program it gives me the following problematic url:
Requested URL
http://localhost:7819/Pages/Account/'http:/localhost:7819/Pages/Support/Asp/Help01.aspx'
As we see the address contain the url of the current page plus the requested url.
More of it I'm loosing the second slash / in http:/ which I have it all the way inside the script.
How can I solve this issue?
I assume, you wanted something like this?
<script type="text/javascript">
function setPage(pName) {
document.getElementById('iFrame').src = pName;
}
</script>

Categories