I want to know how to send variables from javascript to php so i can create a variable that contains dynamic sum of rows.
More specific:
When I search in my search box, i want to get the number of rows (1 match is 1 row, 2 matches is 2 rows and so on
I tried to implement this: document.getElementById("i1").value = allCells.length; so i later could call in the php, but i did not work.
This is my javascript, by the way the javascript works perfectly.
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$('#search').keyup(function() {
searchTable($(this).val());
});
});
function searchTable(inputVal)
{
var table = $('.table');
table.find('tr').each(function(index, row)
{
var allCells = $(row).find('td');
if (allCells.length > 0) {
var found = false;
allCells.each(function(index, td)
{
var regExp = new RegExp(inputVal, 'i');
if (regExp.test($(td).text()))
{
found = true;
return false;
document.getElementById("i1").value = allCells.length;
}
});
if (found == true)
$(row).show();
else
$(row).hide();
}
});
}
$(function()
{
$('#table a').click(function(e)
{
e.preventDefault();
$('#result').val($(this).closest('tr').find('td:first').text());
});
});
</script>
I wanted to spit the dynamicelly sum of rows her in my table header.
<h3>Total: (<?php print_r($_GET["i1"])?>) </h3>
I hope you can help me.
You probably have never learned the difference between javascript and php
Javascript is clientsided, which means everything is processed by your local system. PHP is server sided which means everything is processed by the server and parsed into html.
You can't send a value from javascript into plain php like you did.
You can however send a post or get to the same script and let that reload a part of your script
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.post/
You're not the first to want this, and not the first to be told it is impossible the way you imagine. When you browse to a PHP page things go basically like this:
Browser sends HTTP request to server
Server determines what page to send to the browser
Server discovers you want a PHP page
Server executes PHP
Server sends what is returned by PHP to the browser
Browser doesn't know about the PHP and displays HTML
Browser executes Javascript.
Now the important part is that the browser doesn't know what PHP is, but can execute JavaScript, while the server doesn't know what JavaScript is (for simplicity's sake) but can execute PHP. Bottomline: it is hard to communicate between the two because they are executed in different places. You'll most probably want to use AJAX, so here is a supersimple sample:
The PHP page we're going to fetch:
<?
// We're on the server
// We're going to output something:
echo "Yay! You can see me!"; // So the browser sees only "Yay! You can see me!" (without quotes).
?>
JavaScript (with jQuery) to fetch the PHP page:
$("#anElementID").load("thePHPPageWeWantToFetch.php"); // It's that simple! The element with the ID #anElementID now contains "Yay! You can see me!" (without quotes).
I suggest too, use AJAX or something to pass your javascript values to PHP.
You can create a AJAX call, add the data from your javascript, and catch the data in your PHP file.
var value = "Jan";
$.ajax({
url: "/form.php",
type: "post",
data: "name=" + value
});
in your PHP file you can do:
<?php
$catchedName = $_POST["name"];
?>
Related
Okay so, I've scoured stackoverflow for this answer and have come across several threads talking about how to do this, and well, they just haven't helped me yet.
This is all on one page, so that's probably the big problem. I really don't wanna send the post data to some other page and then redirect back to the one in order to get this to work, but I will if you guys cannot assist me in this endeavor.
Anyway, I have this page and I'm trying to pass data to the php via ajax, and I know that php is a server-side language, so the page would have to be reloaded once the data is passed.
php:
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
}
jquery:
var whateva = "hello";
$.post('index.php', {'location': whateva}, function(){
//alert(data);
//window.location.reload(true);
});
alert(data); does get it to work and echo out given the isset (and also prints out all of the other html), but that is an alert which isn't practical, especially from a user standpoint. But that means that this ajax function is working. The problem here is that I want the same page to load, just with the $_POST['location'] variable set, so I had the bright idea of just reloading the page as the function in this case, which doesn't work. The isset never succeeds
Any help will be appreciated, besides telling me that combining php and javascript is a horrible idea as I already know that
Edit:
I was told to try making another page to post the data back which still didn't work, here's the code for that (with the main page ajax adjusted to direct it there instead):
window.onload = function(){
var inter = <?php echo json_encode($_POST['location']); ?>;
$.post('index.php', {location: inter});
}
I have tried it with and without quotes around location in the .post. Also I have tried to just have the plain javascript there, without the onload, still nothing. The response on the main page when changed to this
$.post('intermediary.php', {location: whateva}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
it prints out the html of the hidden page, with the variable filled in (var inter = "hello" instead of having the php there, as it should), so the passing to that page works
Ok, here's the breakdown.
File one: index.html
This file is HTML and Javascript only, and is the page seen by the user. This could be a php page, but it does not need to be. Notice the quotes around the string 'whateva'.
<html><head></head><body>
<script>
$.post('intermediary.php', {location: 'whateva'}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
</script>
</body></html>
File two: intermediary.php
This file is PHP only. It receives data silently through POST and returns data by echoing it.
<?php
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
} else {
echo 'No data received!';
}
?>
Oh.... It's a simple mistake. your ajax syntax is wrong... Remove the quotes of ajax parameter inside the curly brackets. Just like
var whateva = "hello";
$.post('index.php', {location: whateva}, function(){
//alert(data);
//window.location.reload(true);
});
It will working fine.... But you might use variable to ajax paramete then, you should use variable name for ajax location parameter value. But you might use string for location parameter value, then you should use it value inside the quotes like this, $.post('yourfile.php',{location:'your_name'},function(){});. But you might use some value of location parameter use should type this code.$.post('yourfile.php',{location:30},function(){});
I'm working in PHP and I added the following jQuery code to display the current year:
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="/script/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var currentYear = (new Date).getFullYear();
$(document).ready(function() {
$("#year").text( (new Date).getFullYear() );
});
</script>
<p><span id="year"/></p>
(this code works perfectly: when displaying the page I can see 2015)
What I now want is to put this current year into a PHP variable (like $currentYear), so I will be able to use it in PHP for operations like this one:
$purchaseYear = 1985;
$yearsLivedOld = $currentYear-$purchaseYear;
How to put the year in a PHP variable ?
It's not possible in the way you're trying to do it. Javascript (and thus JQuery) work on the client machine, after the page was sent and the connection with server closed. To get data from client machine your best bet would be an AJAX call which opens a new connection to the server and allows you to load (and send) additional data between the client and the server.
Whole AJAX tutorial is out of scope here, but maybe this link will help you.
If you only want the current year though, you can skip the javascript and do it in PHP, like so:
$purchaseYear = date("Y");
PHP is rendered server side and javascript is rendered client side.
So in a way you can say that PHP is rendered before javascript, which means that you can assign a PHP variable to a javascript variable but cannot do vice-versa.
Therefore you can choose either of the solutions provided by aldrin27 or Till Helge.
Either use
1. AJAX to pass the data generated by javascript to server so that PHP can render it.
2. You can directly get current date in PHP using date('Y'); so there is no need of javascript for this piece of code.
you can use ajax to pass the variable to your php script
var year = $("#year").text();
$.post("your_script.php", {year: year});
and after that you can use the variable in your php script
<?php
$year = $_POST['year'];
echo $year;
?>
you can learn more about ajax in here
Use the jQuery AJAX function (or the post shorthand function).
Javascript:
$.ajax({
url: 'path/to/myscript.php',
type: 'POST',
data: 'current_year=' + currentYear,
success: function(data) {
//Optional callback function on success
}
});
PHP:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['current_year'])) {
//Should really validate/sanitise data here
$currentYear = $_POST['current_year'];
}
}
You could also send it via an HTML post, although that would require a page reload, so AJAX would be more preferable.
So here is the situation. I'm building a page to host a radio stream hosted on an Icecast server. I got the player working great and cobbled together a PHP script to extract and parse out various data points from the server. Information such as current track, number of listeners, etc.
Here's the problem. It loads fine when the page is first opened, but I can't figure out a way to get these variables to be updated every 5-10 seconds or so and update the page with the new information WITHOUT reloading the page completely (it is a radio station after all, and having to re-buffer the station ever 10 seconds just isn't feasible.
Here's what I have so far, after various attempts have been removed from the code. Any ideas? I've seen it done for one or two variables, but I have almost a Dozen here...
<div id="current_song"></div>
<script language="javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script language="javascript">
{
$.ajax({
type: 'POST',
url: 'script.php',
data: 'getLatestInfo',
dataType: 'json',
cache: false,
success : function(dp){
$.getJSON('script.php', function(dp) {
//'data' will be the json that is returned from the php file
$.("#current_song").html("dp[9]");
});
getlatest();
};
});
}
</script>
and here is the PHP parser
<?php
Function getLatestInfo() {
$SERVER = 'http://chillstep.info:1984';
$STATS_FILE = '/status.xsl?mount=/test.mp3';
$LASTFM_API= '27c480add2ca34385099693a96586bd2';
//create a new curl resource
$ch = curl_init();
//set url
curl_setopt($ch,CURLOPT_URL,$SERVER.$STATS_FILE);
//return as a string
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//$output = our stauts.xsl file
$output = curl_exec($ch);
//close curl resource to free up system resources
curl_close($ch);
//loop through $ouput and sort into our different arrays
$dp = array();
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$output,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($dp,$to_push);
}
}
$x = explode(" - ",$dp[9]);
echo json_encode($dp);
}
?>
I know it doesn't look pretty yet, but that's what CSS is for right?
Any ideas? Essentially I need the PHP script to rerun, update the variables, and rebuild the text output without touching the audio tag.
Javascript is code that executes client-side (on the website visitors machine) and PHP executes serverside. The way to insert content into a page without reloading the entire page is to use Javascript to inject code into the HTML. Now, for example, say that you have a PHP file on your server, called getLatest.php with a function called getLatestVariables() that finds out the latest values for all your variables and returns an array containing them. What you can do is use javascript to call getLatestVariables() from getLatest.php, and when the function returns the array, it will return it to the javascript. Once the array of variables has been returned to the javascript you can then insert the variabes into HTML divs without having to refresh the entire page.
to call the php function I suggest using jquery to perform an ajax call
also to insert the data returned from the php, jquery is your best bet too.
You need client side JavaScript for this. Get your hands on basic ajax books.
You can request the script for updated data every 5 seconds and update it on the page, this is complicated and needs some knowledge of JavaScript.
The script will have to be new too, or this one edited to trace type of request and return data accordingly.
var url="http://script-address"
var req = new XMLHttpRequest(); // Begin a new request
req.open("GET", url); // An HTTP GET request for the url
req.send(null);
This is how you can check the response
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
//we got a complete valid HTTP response
var response = req.responseText;
//code to handle response
}
php is a serverside language, so re-running the php inside your page will always result in the entire page refreshing, however if you use a javascript ajax call (I suggest using jquery) to a different php file, that php file can be executed serverside without affecting your page. you can then return the newly found variables from this php file to the javascript, and insert them in the callback of the ajax call.
see the answer to this question
If you need any more detail let me know...
$.getJSON('phpFileThatReturnsJSON.php', function(data) {
//'data' will be the json that is returned from the php file
$.("#idOfDivToInsertData").html("an item from the json array ie data['song']");
});
look at JQuery docs for ajax calls, if you've got this far you should be able to nail it out pretty quickly.
Also dont forget to include the jquery library in your html header...
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
I'd like to have a form on a HTML page not refresh when it's sent, which I've done, but I'd also like to allow the echo command in the PHP file to be able to call JavaScript from within the HTML file.
So far, all the echo commands aren't being carried out, which isn't what I expected.
Here's some code from the HTML and PHP files:
HTML:
<script type="text/javascript">
function functionInFile() {
alert("recieved");
}
$(function() {
$(".postform").submit(function() {
var content = $(this).serialize();
$.post('signup.php?', content);
return false;
});
});
</script>
and the PHP:
echo '<script type=\'text/javascript\'>functionInFile()</script>';
So basically, I'd like the PHP file to be able to invoke a function in the HTML file, while not being redirected when I click submit.
Any help appreciated.
You can use the success callback of the $.post() to execute a function which your PHP passes back. Try this:
PHP
// do some stuff with the posted data
echo 'functionInFile'; // name of js function to execute in calling page
jQuery
function functionInFile() {
alert("recieved");
}
$(function() {
$(".postform").submit(function() {
$.post(
'signup.php?',
$(this).serialize(),
function(func) {
window[func]();
},
'text'
);
return false;
});
});
It could be better to use the callback function of post
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [,
dataType] )
So you would execute what ever code is within the reply or pre determined login onsusccess
$.post( 'signup.php?', content,
function( data ) {
//data contains the reply of the post so you can
//exec the code like this using JavaScript
//altogether eval is frowned upon because it is high overhead and opens
//opens up to code injection or whatever
//eval(data);
//so you just execute whatever method you need
functionInFile();
//or you reply from server in json and converto tobject
//reply: {'executeFunction': true}
var obj = jQuery.parseJSON(data);
if (data.executeFunction == true) { functionInFile(); }
}
);
ParseJSON
In order for PHP echo to work. the page MUST reload baecause it is server side.
A webpage cycle is SERVER SIDE, then Client side.
[SERVER] -> [CLIENT -> AJAX to SERVER -> SERVER REPLY ATTACH]
It looks like you're sending the right <script> tag. XHR return values are treated as data though, not executable code. Luckily for you, jQuery has code to check if you insert a <script> tag into the dom and execute it. You should be able to just do:
$.post('signup.php?', content, function(html) {$(document).append(html);});
and your script will execute.
(I would recommend making this happen in a different way though. I've worked on Apps that send large portions of javascript back in AJAX calls, and it's a pain to debug. It would be much better to send back a JSON object with a string for the next action, then keep an object of "approved" actions as a string -> function lookup table.)
I have an ajax function and while caling that function the php code will execute and check if any rows with the given data is present in the table. If there is no data I would like to display an alert. right now I can display a div with the error message but I could not get the out put such as
echo "<script> alert('error'); </script>";
You can not stick JavaScript on the page using innerHTML since it will not be evaluated. What you would need to do is parse out the JavaScript code and shove it into eval(). OR use a framework that does it for you like jQuery.
It is better to develop a framework on the client that does not rely on this eval. A better messaging system would work.
{ "alert" : "Your alert message", "html" : " the mark up " }
Basic JavaScript idea:
//get the responseText
var result = xhr.responseText;
var json = JSON.parse(result); //This line is not cross browser for older browsers
if(json.alert){
alert(json.alert);
}
if(json.html){
document.getElementById("out").innerHTML = html;
}