I am sending two values to a php page to print those values in the div.
Here is my jquery code and i have given the php page below:
Edit : I have updated the script, But the issue is i am not getting the value of $month from php file
(But i can able to print custom message intead)
Script :
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#driver").click(function(event){
var month=$("#month").val();
var year=$("#year").val();
$.post("summaryreport_result.php",
{month: month, year: year}).done(function(data)
{
$('#stage').html(data).fadeIn(1000);
$('#stage').html(data).fadeOut(3000);
}
);
});
});
</script>
PHP Code :
<?php
$month=$_REQUEST['month'];
$year=$_REQUEST['year'];
echo $month;
?>
But if i print a custom message it is displaying the div stage
What is the mistake i am doing and how can i fix this ?
Try this POST Request
$.post("summaryreport_result.php",
{month: month, year: year}).done(function(data){
$('#stage').html(data).fadeIn(1000);
$('#stage').html(data).fadeOut(3000);
}
);
});
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#driver").click(function(event){
var month=$("#month").val();
var year=$("#year").val();
$.post("summaryreport_result.php",
{month: month, year: year}).done(function(data)
{
$('#stage').html(data).fadeIn(1000);
$('#stage').html(data).fadeOut(3000);
});
});
});
</script>
Related
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.
I wanted to perform jquery post to php and get the data and post to the console log. But however i cant find data on the console.log after performing post the data. my code is found below...........please help me...
student html page
<html>
<head>
<title>NEW AJAX GET</title>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<body>
<script type="text/javascript">
showData();
function showData()
{
$.post("student.php",
{
PostLastName: "Abdullah",
PostLastReligion: "Muslim"
},
function(data)
{
console.log(data);
});
});
</script>
</body>
</html>
student.php script
<?php
if ((empty($_POST["PostLastName"])) && (empty($_POST["PostLastReligion"])))
{
//Return "Posted Values are empty" if the values is empty
$post_string = 'Posted Values Are Empty';
//echo "<script>console.log(".$post_string.");</script>";
echo $post_string;
}
else
{
//Return the Post Data
$post_string= 'Post Last Name = '.$_POST["PostLastName"]."\n".' Post Last Religion = '.$_POST["PostLastReligion"].'';
//echo "<script>console.log(".$post_string.");</script>";
echo $post_string;
}
?>
I have test your code. i think check first check your loaded jquery included in header.
After change some code like below mention and test your browser console.
<html>
<head>
<title>NEW AJAX GET</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script type="text/javascript">
showData();
function showData()
{
$.post( "student.php", { PostLastName: "Abdullah", PostLastReligion: "Muslim" })
.done(function( data ) {
console.log(data);
});
};
</script>
</body>
</html>
I hope u resolve u r issue.
I have (currently) the following bit of code in my module.blade.php:
#section('scripts')
<script type="text/javascript">
createMixin(['{{ $module }}']);
</script>
#endsection
Explanation:
$module is a variable holding a JSON packed with simple key => value, but also with key => object. It is loaded previously in a Controller and displayed in the blade.php.
Example:
{
"title":"Title",
"name":"dummy",
"file":"dummy",
"layout":"normal",
"fields": [
{
"name": "bla"
}
]
}
Function createMixin() would ideally generate a HTML out of Jade with the options inside $module (already existing).
Problem is: This does end in an error message: "htmlentities() expects parameter 1 to be string, array given"
Done so far: I have already tried several things:
#section('scripts')
<script type="text/javascript">
var fields = $.parseJSON("{!! $module !!}");
createMixin(fields);
</script>
#endsection
And:
#section('scripts')
<script type="text/javascript">
createMixin("{!! JSON.parse($module) !!}");
</script>
#endsection
And:
#section('scripts')
<script type="text/javascript">
createMixin("{!! json_encode($module) !!}");
</script>
#endsection
And:
#section('scripts')
<script type="text/javascript">
$(this).createMixin("{{ $module }}");
</script>
#endsection
I have had a look at several posts here (like this one) and in other sources, they tell the people to use the php implode method or just a simple usage of "{!! !!}". But this all ends up in the same error message.
Question: What am I overlooking here? What am I doing wrong?
Edit:
As requested my Javascript function:
//generate one jade mixin
function createMixin(module) {
//first load JSON...
var json = $.parseJSON(loadJSON(module["file"]));
//get options for mixin
var options = json.fields;
//detect jade file
var jadepath = RESOURCES_DIR + "views/jade/" + json.file + "/template.jade";
//check if file exists
$.ajax({
'url': jadepath,
'type': 'HEAD',
'error': function() {},
'success': function () {
var html = renderJade(options, jadepath);
//save html into json
json.html = html;
var tmp = new Blob([html], { type: 'plain/text;charset=utf-8' });
}
});
};
Alright, so I found the solution.
I had to first do the parameter initialisation in PHP:
<?php $json = json_encode($module); ?>
And then separately call the Javascript function via:
#section('scripts')
<script type="text/javascript">
$(document).ready(function() {
var module = {!! $json !!};
createMixin(module);
});
</script>
#endsection
So in total it would look like this:
<?php $json = json_encode($module); ?>
#section('scripts')
<script type="text/javascript">
$(document).ready(function() {
var module = {!! $json !!};
createMixin(module);
});
</script>
#endsection
echo '
<script type="text/javascript">
setInterval( myfunction , 1000);
myfunction(){
window.location = "../index.php";
}
</script>';
if I'm just call window.location = "../index.php" without setInterval it really works I have seen many codes but no one can help me thank you.
If you want to redirect or reload webpage after certain amount of time then event can only be triggered form the client side. You can achieve this using java script and html meta tags.
1: Using HTML
<meta http-equiv="refresh" content="0";url=http://www.domain.com/new-page.html">
you can set the value of content to the time
2: Using Javascript
<script type="text/javascript">
setInterval(function(){
window.location = "../index.php";
} , 1000);
</script>
Redirect the page after 1 second. It runs one time
<script type="text/javascript">
setTimeout(function(){
window.location = "../index.php";
}, 1000);
</script>
If you write in php, use it
<?php
//code here
?>
<script type="text/javascript">
setTimeout(function(){
window.location = "../index.php";
}, 1000);
</script>
<?php
//code here
?>
or use setInterval instead of setTimeout
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 :)