Is it possible to use SSE to send POST data to PHP like in Ajax?
I've been using AJAX now for quite a while with bad results in long-polling technicues. I have also been thinking about WebSockets, but it seems a bit redundant.
No, SSE cannot send any data to the server.
You can still use SSE to read data in real time and use AJAX to upload any data (you might need a shared database to pass information between AJAX-receiving processes and SSE-sending one).
You can send data via GET.
e.g.
name=john&name=lea
This is a simple script that sends to server number of iteration and the server return progress using SSE.
This Project consists of two files (index.php and ssedemo.php).
index.php contain a text box and a button. the textbox suppose to contain the number of iteration of the loop in ssedemo.php
<h2>Server Sent Event Test</h2>
<form>
<label>Process Duration</label>
<input type="text" id="progVal">
<input type="button" value="Get Messages" onclick="updateProgress()"/>
</form>
<div id="container">
</div>
updateProgress
function updateProgress() {
var input = $('#progVal').val();
var evtSource = new EventSource("ssedemo.php?duration=" + encodeURIComponent(input));
evtSource.addEventListener("progress", function (e) {
var obj = JSON.parse(e.data);
$('#container').html(obj.progress);
if( parseInt(obj.progress) == 100){
evtSource.close();
}
}, false);
}
this function get the content of the textbox using jQuery and then create an eventSource. The EventSource() constructor takes one or two arguments. The first specifies the URL to which to connect. The second specifies the settings, if any, in the form of an EventSourceInit dictionary.
You can pass what you want by adding it to URL as you do with GET.
"ssedemo.php?duration=" + encodeURIComponent(input)
In the server side, you have to set header type and disable cache according to W3C recommendation
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
then you get the data using $_GET as usual.
$TotalNo = $_GET['duration'];
for ($i = 1; $i <= $TotalNo; $i++) {
updateProgress($i, $TotalNo);
sleep(1);
}
function updateProgress($currentVal, $totalNo) {
$completionPrecentage = $currentVal / $totalNo * 100;
echo "event: progress\n";
echo 'data: {"progress": "' . $completionPrecentage . '"}';
echo "\n\n";
ob_flush();
flush();
}
if you want to send array you can refer to this
The EventSource API does not support POST method, however that does not mean that you cannot use SSE with POST. You just cannot use the EventSource API.
There are alternative implementations however. One example is sse.js which allows you to specify a payload, and also headers if you need. sse.js should be a drop-in replacement for EventSource, eg:
var source = new SSE("get_message.php");
source.onmessage=function(event)
{
document.getElementById("message-window").innerHTML+=event.data + "<br>";
};
In order to use a POST method, you just need to specify a payload, eg:
var source = new SSE("get_message.php", {payload: 'Hello World'});
And, since it is a fully compatible polyfill, you can probably do this:
EventSource = SSE;
var source = new EventSource("get_message.php", {payload: 'Hello World'});
source.onmessage=function(event)
{
document.getElementById("message-window").innerHTML+=event.data + "<br>";
};
Related
I want to pass JavaScript variables to PHP using a hidden input in a form.
But I can't get the value of $_POST['hidden1'] into $salarieid. Is there something wrong?
Here is the code:
<script type="text/javascript">
// View what the user has chosen
function func_load3(name) {
var oForm = document.forms["myform"];
var oSelectBox = oForm.select3;
var iChoice = oSelectBox.selectedIndex;
//alert("You have chosen: " + oSelectBox.options[iChoice].text);
//document.write(oSelectBox.options[iChoice].text);
var sa = oSelectBox.options[iChoice].text;
document.getElementById("hidden1").value = sa;
}
</script>
<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<?php
$salarieid = $_POST['hidden1'];
$query = "select * from salarie where salarieid = ".$salarieid;
echo $query;
$result = mysql_query($query);
?>
<table>
Code for displaying the query result.
</table>
You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.
<DOCTYPE html>
<html>
<head>
<title>My Test Form</title>
</head>
<body>
<form method="POST">
<p>Please, choose the salary id to proceed result:</p>
<p>
<label for="salarieids">SalarieID:</label>
<?php
$query = "SELECT * FROM salarie";
$result = mysql_query($query);
if ($result) :
?>
<select id="salarieids" name="salarieid">
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
}
?>
</select>
<?php endif ?>
</p>
<p>
<input type="submit" value="Sumbit my choice"/>
</p>
</form>
<?php if isset($_POST['salaried']) : ?>
<?php
$query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
$result = mysql_query($query);
if ($result) :
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
echo '</tr>';
}
?>
</table>
<?php endif?>
<?php endif ?>
</body>
</html>
Just save it in a cookie:
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
And then read it with PHP:
<?PHP
$_COOKIE["height"];
?>
It's not a pretty solution, but it works.
There are several ways of passing variables from JavaScript to PHP (not the current page, of course).
You could:
Send the information in a form as stated here (will result in a page refresh)
Pass it in Ajax (several posts are on here about that) (without a page refresh)
Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var PageToSendTo = "nowitworks.php?";
var MyVariable = "variableData";
var VariablePlaceholder = "variableName=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.
Here is the Working example: Get javascript variable value on the same page in php.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's how I did it (I needed to insert a local timezone into PHP:
<?php
ob_start();
?>
<script type="text/javascript">
var d = new Date();
document.write(d.getTimezoneOffset());
</script>
<?php
$offset = ob_get_clean();
print_r($offset);
When your page first loads the PHP code first runs and sets the complete layout of your webpage. After the page layout, it sets the JavaScript load up.
Now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't - it needs to refresh the page. The only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP.
So, we use AJAX to get Javascript to interact with PHP without a page reload. AJAX can also be used as an API. One more thing if you have already declared the variable in PHP before the page loads then you can use it with your Javascript example.
<?php $myname= "syed ali";?>
<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>
The above code is correct and it will work, but the code below is totally wrong and it will never work.
<script>
var username = "syed ali";
var <?php $myname;?> = username;
alert(myname);
</script>
Pass value from JavaScript to PHP via AJAX
This is the most secure way to do it, because HTML content can be edited via developer tools and the user can manipulate the data. So, it is better to use AJAX if you want security over that variable. If you are a newbie to AJAX, please learn AJAX it is very simple.
The best and most secure way to pass JavaScript variable into PHP is via AJAX
Simple AJAX example
var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
$.ajax({
type: "POST",
url: "YOUR PHP URL HERE",
data:userdata,
success: function(data){
console.log(data);
}
});
PASS value from JavaScript to PHP via hidden fields
Otherwise, you can create a hidden HTML input inside your form. like
<input type="hidden" id="mydata">
then via jQuery or javaScript pass the value to the hidden field. like
<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>
Now when you submit the form you can get the value in PHP.
I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.
It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.
One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:
<img src="pic.php">
The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.
PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.
If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.
Here's a previous question that you can follow for more information: Ajax Tutorial
Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.
<?php
if(isset($_POST))
{
print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="data" value="1" />
<input type="submit" value="Submit" />
</form>
Clicking submit will submit the page, and print out the submitted data.
We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -
function statusChangeCallback(response) {
console.log('statusChangeCallback');
if (response.status === 'connected') {
// Logged into your app and Facebook.
FB.api('/me?fields=id,first_name,last_name,email', function (result) {
document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
console.log(document.cookie);
});
}
}
And I've accessed it (in any file) using -
<?php
if(isset($_COOKIE['fbdata'])) {
echo "welcome ".$_COOKIE['fbdata'];
}
?>
Your code has a few things wrong with it.
You define a JavaScript function, func_load3(), but do not call it.
Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
Your form has no means to submit it. It needs a submit button.
You do not check whether your form has been submitted.
It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:
<?php
if (isset($_POST['hidden1'])) {
echo "You submitted {$_POST['hidden1']}";
die;
}
echo <<<HTML
<form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
<input type="submit" name="submit" value="Test this mess!" />
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<script type="text/javascript">
document.getElementById("hidden1").value = "This is an example";
</script>
HTML;
?>
You can use JQuery Ajax and POST method:
var obj;
$(document).ready(function(){
$("#button1").click(function(){
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: "addperson.php",
type: "POST",
async: false,
data: {
username: username,
password: password
}
})
.done (function(data, textStatus, jqXHR) {
obj = JSON.parse(data);
})
.fail (function(jqXHR, textStatus, errorThrown) {
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) {
});
});
});
To take a response back from the php script JSON parse the the respone in .done() method.
Here is the php script you can modify to your needs:
<?php
$username1 = isset($_POST["username"]) ? $_POST["username"] : '';
$password1 = isset($_POST["password"]) ? $_POST["password"] : '';
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";
;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('success' => 1));
} else{
echo json_encode(array('success' => 0));
}
$conn->close();
?>
Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.
May be you could use jquery serialize() method so that everything will be at one go.
var data=$('#myForm').serialize();
//this way you could get the hidden value as well in the server side.
This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.
Just set a cookie with the data you want to pass to PHP using javascript in the browser.
Then, simply read this cookie on the PHP side.
We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
So it's better to use the AJAX to parse the JavaScript value into the php Code.
Or alternatively we can make this done with the help of COOKIES in our code.
Thanks & Cheers.
Use the + sign to concatenate your javascript variable into your php function call.
<script>
var JSvar = "success";
var JSnewVar = "<?=myphpFunction('" + JSvar + "');?>";
</script>`
Notice the = sign is there twice.
I am having a problem with setInterval in the $(document).ready(function(){}
What I am doing is setting the interval to do is call a PHP script that runs some MySQL queries to check the condition of 4 switches and then updating the screen with the values are in the database like so:
$(document).ready(function(){
setInterval(function(){
<?php require('fetchSwitchStatuses.php'); ?>
$("#switch1").css('background', 'rgb(<?php echo $switchColor1 ?>)');
$("#switch1").html('<?php echo $switchState1 ?>');
$("#switch2").css('background', 'rgb(<?php echo $switchColor2 ?>)');
$("#switch2").html('<?php echo $switchState2 ?>');
$("#switch3").css('background', 'rgb(<?php echo $switchColor3 ?>)');
$("#switch3").html('<?php echo $switchState3 ?>');
$("#switch4").css('background', 'rgb(<?php echo $switchColor4 ?>)');
$("#switch4").html('<?php echo $switchState4 ?>');
},1000);
});
Here is the code for fetchSwitchStatuses.php:
$connect = mysqli_connect("localhost", "root", "root");
mysqli_select_db($connect, "db_name");
$fetch1 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '3'"
);
$fetch2 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '5'"
);
$fetch3 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '6'"
);
$fetch4 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '9'"
);
$i = 1;
while($row = mysqli_fetch_array(${'fetch'.$i}))
{
if($row['SwitchStatus'] == 0)
{
${'switchColor'.$i} = "255, 0, 0";
${'switchState'.$i} = "OFF";
}
else if ($row['SwitchStatus'] == 1){
${'switchColor'.$i} = "0, 255, 0";
${'switchState'.$i} = "ON";
}
else {
${'switchColor'.$i} = "100, 100, 100";
${'switchState'.$i} = "ERROR";
}
$i++;
}
mysqli_close($connect);
When the page is loaded the information is correct, whatever is in the database is what is reflected by the colors on the screen.
When I click on the object to change the value, all of the necessary changes are made and the database is updated. However, the problem arises when the Interval is repeated. The values are switched back to whatever the original values were when the page was loaded. So, although the information is correctly changed in the database, for some reason the colors of the buttons is always reset to the first value read by the queries.
How can I fix this so that the information that is reflected on the screen is accurate?
With AJAX technology you can:
Send a request and get results from server by requesting a page (a .txt .js .html or even php).
So with AJAX you can get result of a page save something to database, get something from data base, you can work with sessions and anything you can do with a php file.
When you send an AJAX request to a see a page(i.e /userData.php?userId=5) the page /userData.php?userId=5 will be executed and its output will be returned.(HTML or just a word ‘yes’ or ‘no’ or ‘you can’t access to this user’s information’).
You can send data to file with POST or GET. But the question is how you can get data from page. Because the result AJAX will give you is what the requested page echoed to page like this
<html>
….
</html>
Or
‘Yes’
Or
<?php echo ‘something’; ?>
So what about getting a row of Date or lots of data? Because the only thing you are getting is a text or maybe a long text.
For that you can use JSON which Is something like nested arrays.
[
{
"term": "BACCHUS",
"part": "n.",
"definition": "A convenient deity invented by the...",
"quote": [
"Is public worship, then, a sin,",
"That for devotions paid to Bacchus",
"The lictors dare to run us in,",
"And resolutely thump and whack us?"
],
"author": "Jorace"
},
…
And this is a string too. But you can get Data in it with $.getJSON in jQuery and you can generate JSON data in server side like this.
<?php
$arr=array(
‘data’=>’ffff’,
‘anotherData’=>array(‘rrrrr’,’sssss’);
);
Echo json_encode($arr);
?>
Json_encode() in PHP gets an array and returns json string of it. And we echo it.
Now we can use jQuery to get Data which will be retrieved from server.
This section if from
Learning jQuery 1.3
Better Interaction Design and Web Development with Simple JavaScript Techniques
Jonathan Chaffer
Karl Swedberg
Global jQuery functions
To this point, all jQuery methods that we've used have been attached to a jQuery object that we've built with the $() factory function. The selectors have allowed us to specify a set of DOM nodes to work with, and the methods have operated on them in some way. This $.getJSON() function, however, is different. There is no logical DOM element to which it could apply; the resulting object has to be provided to the script, not injected into the page. For this reason, getJSON() is defined as a method of the global jQuery object (a single object called jQuery or $ defined once by the jQuery library), rather than of an individual jQuery object instance (the objects we create with the $() function).
If JavaScript had classes like other object-oriented languages, we'd call $.getJSON() a class method. For our purposes, we'll refer to this type of method as a global function; in effect, they are functions that use the jQuery namespace so as not to conflict with other function names.
To use this function, we pass it the file name as before:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json');
return false;
});
});
This code has no apparent effect when we click the link. The function call loads the file, but we have not told JavaScript what to do with the resulting data. For this, we need to use a callback function.
The $.getJSON() function takes a second argument, which is a function to be called when the load is complete. As mentioned before, AJAX calls are asynchronous, and the callback provides a way to wait for the data to be transmitted rather than executing code right away. The callback function also takes an argument, which is filled with the resulting data. So, we can write:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
});
return false;
});
});
Here we are using an anonymous function as our callback, as has been common in our jQuery code for brevity. A named function could equally be provided as the callback.
Inside this function, we can use the data variable to traverse the data structure as necessary. We'll need to iterate over the top-level array, building the HTML for each item. We could do this with a standard for loop, but instead we'll introduce another of jQuery's useful global functions, $.each(). We saw its counterpart, the .each() method, in Chapter 5. Instead of operating on a jQuery object, this function takes an array or map as its first parameter and a callback function as its second. Each time through the loop, the current iteration index and the current item in the array or map are passed as two parameters to the callback function.
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
$('#dictionary').empty();
$.each(data, function(entryIndex, entry) {
var html = '<div class="entry">';
html += '<h3 class="term">' + entry['term'] + '</h3>';
html += '<div class="part">' + entry['part'] + '</div>';
html += '<div class="definition">';
html += entry['definition'];
html += '</div>';
html += '</div>';
$('#dictionary').append(html);
});
});
return false;
});
});
Before the loop, we empty out so that we can fill it with our newly-constructed HTML. Then we use $.each() to examine each item in turn, building an HTML structure using the contents of the entry map. Finally, we turn this HTML into a DOM tree by appending it to the .
This approach presumes that the data is safe for HTML consumption; it should not contain any stray < characters, for example.
I would like to pass an array I have in my PHP file to another file that is written in java script.
This is my array:
$pictures = array(
"1" => array("caption" => "1920x1200px", "tag" => "wallpaper", "link" => "#"),
);
And in my java script file this is the place where I want to call the array:
(At the place where they shall be in the code I wrote TAG, LINK and CAPTION.
Sry if this is a stupid question, but as you see, I have no idea about PHP and java script)
F.helpers.title = {
beforeShow: function (opts) {
var text = F.current.title,
type = opts.type,
title,
target;
if (!isString(text) || $.trim(text) === '') {
return;
}
title = $('<div class="fancybox-title fancybox-title-' + type + '-wrap"><h1>' + text + '</h1><p>CAPTION</p></div><div class="fancybox-title fancydownload" ><img src="../../../slider/img/download.png" alt=""/></div><div class="fancybox-title fancytag"><h2>TAG</h2></div>');
switch (type) {
case 'inside':
target = F.skin;
break;
case 'outside':
target = F.wrap;
break;
case 'over':
target = F.inner;
break;
default: // 'float'
target = F.skin;
title
.appendTo('body')
.width(title.width()) //This helps for some browsers
.wrapInner('<span class="child"></span>');
//Increase bottom margin so this title will also fit into viewport
F.current.margin[2] += Math.abs( getScalar(title.css('margin-bottom')) );
break;
}
if (opts.position === 'top') {
title.prependTo(target);
} else {
title.appendTo(target);
}
}
};
Try it using JSON. There are quite a few JSON parsers available
Encode it as JSON to convert it into a JavaScript literal, then access the resultant value as normal.
var data = <?php echo json_encode(array('foo' => 'bar')); ?>;
console.log(data['foo']);
The lifecycle of your PHP script (on the server side) is different from that of JS (on the client side). If you want to pass some information from PHP to client side, you can do one of the following:
You should print this information into the HTML file on the server side itself using your template engine.
You should return this information through another API by converting it into JSON format that is easy to browse through on the javascript side, and call your API using AJAX.
use an ajax call, something like $.post to get the array as a json array,
add an echo json_encode($picture) at the end of your PHP script.
PHP just generates files which then you send to the client. JavaScript is executed on the client side. So you should generate in php something like
var pictures = {'1': {caption: '1920x1200px', tag: 'wallpaper', link: '#'}};
and place it in html in script tag for example.
As a variant you may do it this way:
var pictures = <?= json_encode($pictures); ?>;
Ok so I'm experimenting with the in HTML5 and have made a simple "paint" application in Javascript to draw where the user's mouse is on the screen. Works fine.
I then wanted to save the coordinates to a file. My program already had an array of the x coordinates and an array of the y coordinates from the Javascript code.
When the user presses a button, the onClick calls a function in the Javascript, which using jQuery, as in the Top Answer here How to get JavaScript function data into a PHP variable attempts to pass this into a php file to save.
However it isn't working. Should I be passing the data back into the original php document that contains the canvas? If so how do I then get it to do the code to save as the PHP is run when the document is loaded no?
CODE:
Ok this is in the original php file which contains the HTMl for the webpage including the canvas. Here's the relevant save button:
<button type="button" onclick="saveDrawing()" id="saveButton">Save</button>
This calls the following in a separate JS file
function saveDrawing(){
// First check that not drawing and have data
if (!readyToDraw && clickX!=null){
// If ready then pass back to the PHP file the data
$url = 'file_save_test.php';
$.get($url, {x_coords: getXCoords(), y_coords: getYCoords()});
}
else {
alert("Please add some coordinate points and press Finish before saving");
}
}
and file_save_test.php contains only the following
<?php
// retrieve data from the JS
$buffer_data['x_coords'] = $_GET['x_coords'];
$buffer_data['y_coords'] = $_GET['y_coords'];
$x_s = $_GET['x_coords'];
$y_s = $_GET['y_coords'];
// first want to open a file
$file_name = "data_test.txt";
$file_handler = fopen($file_name, 'w');
// now to loop through arrays and write!
/*for ($i = 0; $i < sizeof($x_s); i++){
fwrite($file_handler, "$x_s[i], ");
fwrite($file_handler, "$y_s[i]\n");
} */
fclose($file_handler);
?>
In your PHP file it looks like your fwrite code is commented out. Are you expecting it to write to that data_test.txt file? Try changing your PHP file to print the results and have it echoed back to your javascript to see if the data is getting communicated properly.
$.get($url, {x_coords: getXCoords(), y_coords: getYCoords()},
function(data){
alert("Data Loaded: " + data);
});
PHP
print_r($_GET);
EDIT
Change your PHP file to something like this if it's alerting the data properly (it should append the coords to your file):
<?php
// retrieve data from the JS
$x_s = $_GET['x_coords'];
$y_s = $_GET['y_coords'];
$file_name = "data_test.txt";
$file_handler = fopen($file_name, 'a');
fwrite($file_handler, "$x_s, $y_s \n");
fclose($file_handler);
?>
EDIT 2
Update your for loop to your original code
for ($i = 0; $i < count($x_s); $i++){
fwrite($file_handler, $x_s[$i] . ", ". $y_s[$i] . "\n");
}
What I would do is have your save button call jQuery's $.post() method. Post the data to another PHP file that either inserts it into a database or saves it as a file. I don't recommend using the original document to post the data to because the client would have to download the entire DOM and the server would run any other code that you don't need.
That's as much as I can really help you without seeing any of your code.
I would send the data into a new php script called saveCoords.php or something..
You say you already have the coordinates in a JavaScript array, so it would look something like this...
//JAVASCRIPT FUNCTION which will request php file to store info
function storeCoords(xCoordArray, yCoordArray){
var xCoords = JSON.stringify(xCoordArray);
var yCoords = JSON.stringigy(yCoordArray);
var request = new XMLttpRequest(); //will need to change for older ie
request.onreadystatechange = function(){
//functions to handle returning information from php file..
}
request.open("GET","saveCoords.php?xCoords="+xCoords+"&yCoords="+yCoords, true);
request.send();
}
And then saveCoords.php file would look something like this:
<?php
$xCoords = json_decode($_GET['xCoords']);
$yCoords = json_decode($_GET['yCoords']);
//now you have a php array of xCoords and yCoords, which you can store
?>
Thats a skeleton but I think it hits on the major points, but comment with any questions.
how i can i change the content of a page without refreshing.I know we need to use hidden frames for this but all the tutorials i have come across teach this only for HTML files what if the content is returned from a PHP file how do i do it in such a case? what should the php file echo or return?
You will have to use Ajax for that, have a look at this tutorial:
AJAX Tutorial
If you use a hidden frame, the content won't be displayed (hence "hidden"), I think you just mean to use an iframe. But this doesn't fit your description of "without refreshing", since you have to refresh the frame.
When loading the PHP file inside the frame, your PHP file just needs to generate HTML the same way you would generate a normal page. It's the same whether the PHP file is loaded inside a frame or not.
I use this method for a lot of my websites and so does Google. If you want to get data from a PHP file and then dynamically update the page you need to "import" the PHP file somehow without the entire page being redirected, or using iframes (which works too but is a lot messier). The way you do this is to import the file as a "javascript" file.
The following code demonstrates a form called "testform" and a text input called "userpost".
When you submit the form, it will import a file, and then update div "outputText" with whatever you entered... and wait for it... all without the page being redirected at all or refreshed!
I have included a lot of extra functions to show how you can access all of your functions on the same DOM unlike if you use frames where you have to use "top.object" or what not
index.html
<html>
<head>
// Get objects by their id. We will use this in the PHP imported file
Get = function(id) {
return (!id) ? null : (typeof id == "object") ? id :
(document.getElementById) ? document.getElementById(id) :
(document.all) ? document.all[id] :
(document.layers) ? document.layers[id] : null;
}
// Formats a string so it does not break in a URL
String.prototype.formatForURL = function() {
var str = escape(this.replace(/ /gi, "%20"));
str = str.replace(/\&/gi, "%26").replace(/\=/gi, "%3D");
str = str.replace(/\//gi, "%2F")
return str;
}
String.prototype.contains = function(str) {
return (!str) ? false : (this.indexOf(str) > -1);
}
Object.prototype.killself = function() {
this.offsetParent.removeChild(this);
}
// Import the script
ImportScript = function(js) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("language", "JavaScript");
script.setAttribute("charset", "utf-8");
// we add the is tag so can delete the "js" file as soon as it executes
script.setAttribute("id", "import_" + head.children.length);
script.setAttribute("src", js + (js.contains("?") ? "" : "?") + "&is=" + head.children.length);
head.appendChild(script);
}
// Get and send value to php file
sendInfo = function() {
var file = "js/myFile.php?userpost=";
file += document.testform.userpost.value.formatForURL();
ImportScript(file);
}
</head>
<body>
<div>
<form name=testform onsubmit="sendInfo(); return false">
<input type=TEXT name=userpost />
<input type=SUBMIT value=Go />
</form>
</div>
<div id=ouputText>
This text will be replaced by what you type
and submit into the form above
</div>
</body>
<html>
js/myFile.php
<?php
// Here you can now use functions like mysql_connect() etc. even exec()
// ANYTHING! Save them into variables and output them as text which goes
// Straight into the javascript! e.g. :
// $con = mysql_connect("localhost", "username", "password");
// if($con) {
// ... code to retrieve data and save into $variable
// }
// print "alert(\"$variable\");"; // this alerts the value in variable
if(isset($_GET['userpost'])) {
$userpost = $_GET['userpost'];
?>
Get("outputText").innerHTML = "<?=$userpost; ?>";
<?php
}
?>
// Clear text area
document.testform.userpost.setAttribute("value", "");
// Remove the file from header after info is changed
Get("import_<?=$_GET['is']; ?>").killself();
If I had typed in "Hello World" into text input "userpost" then
div "outputText" would be filled with the words "Hello World"
deleting what was previously there, and the text input will be cleared
Hidden frames is one design pattern that is a part of the overall AJAX design pattern. This is an extreme high-level overview, but this is essentially how it works:
Javascript in your HTML page makes a request to your PHP script by using an XMLHTTPRequest object, or a hidden frame or iframe. This is usually done asynchronously, so you can continue to work with your HTML page while the request is being made.
The data is returned to your Javascript. At this point, you can then manipulate the page, and update data on the page using various DOM methods.