PDA

View Full Version : Pass value to php with ajax



keyboard
02-14-2012, 01:31 AM
Hello everyone,



<html>
<head>
<script type="text/javascript">
function ajaxFunction() {
var field1 = document.getElementById('field1');
if(field1.value.length == "0") {
alert("Please enter a value");
} else {
// ajax goes here
}
}
</script>
</head>
<body>
<input type="text" name="field1" id="field1">
<input type="button" value="submit" onclick="ajaxFunction();">
</body>
</html>


I'm trying to pass the javascript variable called field1 to a php page(check.php) using ajax.

When the variable has been moved to the php page I would like it to be stored in a php variable like this.



<?php
$field1value = ajaxy stuff;
?>


I have no idea how to do this and have very limited experience with ajax.
It needs to be cross browser compatible.
Can anyone help me? :)

jscheuer1
02-14-2012, 04:22 AM
The AJAX side of that can be done, but what's the point?

I ask because:



<?php
$field1value = ajaxy stuff;
?>

contrary to what you assert in your post, doesn't store anything. Like any PHP page, regardless of where it gets its information from, doing that only assigns a value to $field1value while the page that variable is on is being processed.

That's not to say that doing something generally like that cannot be of any worth, it can. But there needs to be a more concrete purpose.

So let's forget about what happens on the PHP page for a moment. AJAX is vastly less complicated when we use jQuery. So on the 'sending' page we can have:


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
var field1 = $('#field1');
$('#send').click(function(){
if(!field1.val()){
alert("Please enter a value");
field1.focus();
return;
}
jQuery.ajax({
url: 'somepage.php',
type: 'post',
data: 'field1value=' + field1.val()
});
});
});
</script>
</head>
<body>
<body>
<input type="text" name="field1" id="field1">
<input type="button" value="Submit" id="send">
</body>
</body>
</html>

And on the 'receiving' page (somepage.php):


<?php
$field1value = isset($_POST['field1value'])? $_POST['field1value'] : '';
?>

But, as I say it doesn't do anything. The somepage.php code runs on the server, the $field1value is set, then the page is done and all is forgotten. Nothing has changed or happened other than a few clock ticks got used up on the server.

If on the other hand we use a 'sending' page like:


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
var field1 = $('#field1');
$('#send').click(function(){
if(!field1.val()){
alert("Please enter a value");
field1.focus();
return;
}
jQuery.ajax({
url: 'somepage.php',
type: 'post',
data: 'field1value=' + field1.val(),
success: function(results){
alert(results);
}
});
});
});
</script>
</head>
<body>
<body>
<input type="text" name="field1" id="field1">
<input type="button" value="Submit" id="send">
</body>
</body>
</html>

And on somepage.php:


Hey, what did you type "<?php
$field1value = isset($_POST['field1value'])? $_POST['field1value'] : '';
echo $field1value;
?>" for?

Now we at least have evidence that something happened.

keyboard
02-14-2012, 09:24 PM
Sorry if I wasn't clear -


Hello everyone,


<?php
$field1value = ajaxy stuff;
?>



Isn't the full contents of the php page, just the way I wanted the information to be stored (as you said temporarialy).

This is absaloutly fantastic,
Thanks jschuer1

jscheuer1
02-15-2012, 06:20 AM
Hey jscheuer1

I was wondering if you could help me?

Index.html


<html>
<head>
<title>
Html Editor
</title>
<style type="text/css">
#window1 p {
margin: 0;
}
#window2 p {
margin: 0;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
function clearwindow(){
var window1contents = document.getElementById('window1').innerHTML;
var window2contents = document.getElementById('window2').innerHTML;
if(window1contents == "<I>Edit Window</I>"){
document.getElementById('window1').innerHTML = "&lt;html&gt;<br />&lt;head&gt;<br />&lt;/head&gt;<br />&lt;body&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;";
}
if(window2contents == "<I>Viewing Window</I>"){
document.getElementById('window2').innerHTML = "";
}
}
function fillwindow(){
var window1contents = document.getElementById('window1').innerHTML;
var window2contents = document.getElementById('window2').innerHTML;
if(window1contents == "&lt;html&gt;<BR>&lt;head&gt;<BR>&lt;/head&gt;<BR>&lt;body&gt;<BR>&lt;/body&gt;<BR>&lt;/html&gt;"){
document.getElementById('window1').innerHTML = "<I>Edit Window</I>";
document.getElementById('window2').innerHTML = "<I>Viewing Window</I>";
}
}
</script>
<script type="text/javascript">
jQuery(function($){
var field1 = $('#window1').html();
$('#window1').keyup(function(){
if(!field1.val()){
alert("Please enter a value");
field1.focus();
return;
}
jQuery.ajax({
url: 'somepage.php',
type: 'post',
data: 'field1value=' + field1.val(),
success: function(results){
alert(results);
}
});
});
});
</script>
</head>
<body style="background-color:grey;">
<div style="float:left; width:120px; height:60%; background-color:grey;"></div>
<div style="float:left; width:33.3%; height:60%; background-color:white; border: 3px darkgrey solid; overflow:auto;" id="window1" onclick="clearwindow()" onblur="fillwindow()" contenteditable><i>Edit Window</i></div>
<div style="float:left; width:300px; height:60%; background-color:grey;"></div>
<div style="float:left; width:33.3%; height:60%; background-color:white; border: 3px darkgrey solid; overflow:auto;" id="window2"><i>Viewing Window</i></div>
<div style="float:left; width:100px; height:61%; background-color:grey;"></div>

<div style="float:left; width:120px; height:70%; background-color:grey;"></div>
<!--<input type="button" value="Reset" onclick="reset()">--><input type="button" value="BOLD" onclick="ajaxFunction();">
</body>
</html>


Somepage.php


<?php
$field1value = isset($_POST['field1value'])? $_POST['field1value'] : '';
echo $field1value;
?>


Can you tell why it isn't working?
Any help would be great!!!

I get the error "field1.val() is not a function". That's because you've got:


var field1 = $('#window1').html();

The .val() function is only valid for input and textarea tags. Here, not only isn't it one of those, it's actually a string representing the innerHTML of a div tag.

This works:


jQuery(function($){
var field1 = $('#window1');
field1.keyup(function(){
if(!field1.html()){
alert("Please enter a value");
field1.focus();
return;
}
jQuery.ajax({
url: 'somepage.php',
type: 'post',
data: 'field1value=' + field1.html(),
success: function(results){
alert(results);
}
});
});
});

keyboard
02-15-2012, 06:36 AM
Index.html


<html>
<head>
<title>
Html Editor
</title>
<style type="text/css">
#window1 p {
margin: 0;
}
#window2 p {
margin: 0;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
function clearwindow(){
var window1contents = document.getElementById('window1').innerHTML;
var window2contents = document.getElementById('window2').innerHTML;
if(window1contents == "<I>Edit Window</I>"){
document.getElementById('window1').innerHTML = "&lt;html&gt;<br />&lt;head&gt;<br />&lt;/head&gt;<br />&lt;body&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;";
}
if(window2contents == "<I>Viewing Window</I>"){
document.getElementById('window2').innerHTML = "";
}
}
function fillwindow(){
var window1contents = document.getElementById('window1').innerHTML;
var window2contents = document.getElementById('window2').innerHTML;
if(window1contents == "&lt;html&gt;<BR>&lt;head&gt;<BR>&lt;/head&gt;<BR>&lt;body&gt;<BR>&lt;/body&gt;<BR>&lt;/html&gt;"){
document.getElementById('window1').innerHTML = "<I>Edit Window</I>";
document.getElementById('window2').innerHTML = "<I>Viewing Window</I>";
}
}
</script>
<script type="text/javascript">
jQuery(function($){
var field1 = $('#window1');
field1.keyup(function(){
if(!field1.html()){
alert("Please enter a value");
field1.focus();
return;
}
jQuery.ajax({
url: 'somepage.php',
type: 'post',
data: 'field1value=' + field1.html(),
success: function(results){
alert(results);
}
});
});
});
</script>
</head>
<body style="background-color:grey;">
<div style="float:left; width:120px; height:60%; background-color:grey;"></div>
<div style="float:left; width:33.3%; height:60%; background-color:white; border: 3px darkgrey solid; overflow:auto;" id="window1" onclick="clearwindow()" onblur="fillwindow()" contenteditable><i>Edit Window</i></div>
<div style="float:left; width:300px; height:60%; background-color:grey;"></div>
<div style="float:left; width:33.3%; height:60%; background-color:white; border: 3px darkgrey solid; overflow:auto;" id="window2"><i>Viewing Window</i></div>
<div style="float:left; width:100px; height:61%; background-color:grey;"></div>

<div style="float:left; width:120px; height:70%; background-color:grey;"></div>
<!--<input type="button" value="Reset" onclick="reset()">--><input type="button" value="BOLD" onclick="ajaxFunction();">
</body>
</html>


Somepage.php


<?php
$field1value = isset($_POST['field1value'])? $_POST['field1value'] : '';
echo $field1value;
?>


When I type in the content editable div, nothing happens.
Any help?

jscheuer1
02-15-2012, 06:43 AM
Works here. It does require a PHP enabled server though. For best results in IE remove:


onclick="clearwindow()" onblur="fillwindow()"

jscheuer1
02-15-2012, 07:12 AM
OK, I played with this a bit more and it seems that the clearwindow and fillwindow functions have a lot of room for improvement. And that the HTML of the contenteditable div cannot always all be passed as POST data for some reason. Escaping it before sending and unescaping it upon return seems to fix that. So try this out. Bear in mind that the clearwindow and fillwindow functions still have a lot of room for improvement. I've just made them a bit more serviceable:


<html>
<head>
<title>
Html Editor
</title>
<style type="text/css">
#window1 p {
margin: 0;
}
#window2 p {
margin: 0;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
function clearwindow(){
var window1contents = document.getElementById('window1').innerHTML;
var window2contents = document.getElementById('window2').innerHTML;
if(/<I>Edit Window<\/I>/i.test(window1contents)){
document.getElementById('window1').innerHTML = "&lt;html&gt;<br />&lt;head&gt;<br />&lt;/head&gt;<br />&lt;body&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;";
fillwindow.test = document.getElementById('window1').innerHTML;
}
if(/<I>Viewing Window<\/I>/i.test(window2contents)){
document.getElementById('window2').innerHTML = "";
}
}
function fillwindow(){
var window1contents = document.getElementById('window1').innerHTML;
var window2contents = document.getElementById('window2').innerHTML;
if(fillwindow.test == window1contents){
document.getElementById('window1').innerHTML = "<I>Edit Window</I>";
document.getElementById('window2').innerHTML = "<I>Viewing Window</I>";
}
}
</script>
<script type="text/javascript">
jQuery(function($){
var field1 = $('#window1');
field1.keyup(function(){
if(!field1.html()){
alert("Please enter a value");
field1.focus();
return;
}
jQuery.ajax({
url: 'somepage.php',
type: 'post',
data: 'field1value=' + escape(field1.html()),
success: function(results){
alert(unescape(results));
}
});
});
});
</script>
</head>
<body style="background-color:grey;">
<div style="float:left; width:120px; height:60%; background-color:grey;"></div>
<div style="float:left; width:33.3%; height:60%; background-color:white; border: 3px darkgrey solid; overflow:auto;" id="window1" onclick="clearwindow()" onblur="fillwindow()" contenteditable><i>Edit Window</i></div>
<div style="float:left; width:300px; height:60%; background-color:grey;"></div>
<div style="float:left; width:33.3%; height:60%; background-color:white; border: 3px darkgrey solid; overflow:auto;" id="window2"><i>Viewing Window</i></div>
<div style="float:left; width:100px; height:61%; background-color:grey;"></div>

<div style="float:left; width:120px; height:70%; background-color:grey;"></div>
<!--<input type="button" value="Reset" onclick="reset()">--><input type="button" value="BOLD" onclick="ajaxFunction();">
</body>
</html>

keyboard
02-15-2012, 08:32 AM
I changed index.html to the code you posted and left somepage.php exactly the same.

When I type into the div with id="window1" nothing happens.
Tested in IE9, Firefox and Chrome.
Any help?

jscheuer1
02-15-2012, 10:14 AM
Here's a demo:

http://jscheuer1.comli.com/postedit/demo.htm

If you want more help, please post a link to the page on your site that contains the problematic code so we can check it out.

keyboard
02-16-2012, 09:50 PM
Hopefully I'll have a link up soon...

jscheuer1
02-17-2012, 03:22 AM
My site and the demo from my last post are back up having passed host inspection, phew. So have a look:

http://jscheuer1.comli.com/postedit/demo.htm

keyboard
02-17-2012, 05:48 AM
My copy still dosen't work. I'll try to post a link soon.

jscheuer1
02-17-2012, 12:42 PM
Well, perhaps I can save us both some time. In putting together that demo I realized that unless quotes are escaped, it could be used by another website to make their content appear to be on your domain. But escaping quotes also prevents inline attributes.

Another drawback is - well I see your default starting code is:


<html>
<head>
</head>
<body>
</body>
</html>

But you cannot paste these as real tags into the Viewing Window, as they're invalid there. Most browsers will strip them automatically, or at the very least not respect them the way that they normally are when used as intended. You would need an iframe to properly do that.

It is tempting. The contenteditable division allows you to enter tags and text, the other division could be used to display the result. All of this with minimal coding required - provided of course you have a host with PHP enabled.

There already is a script for this sort of thing though:

http://www.dynamicdrive.com/dynamicindex16/richtexteditor/index.htm

keyboard
02-17-2012, 09:46 PM
Well, perhaps I can save us both some time. In putting together that demo I realized that unless quotes are escaped, it could be used by another website to make their content appear to be on your domain. But escaping quotes also prevents inline attributes.


I don't understand what you mean. How could quotes let others show there pages on my domain???



Another drawback is - well I see your default starting code is:


<html>
<head>
</head>
<body>
</body>
</html>

But you cannot paste these as real tags into the Viewing Window, as they're invalid there. Most browsers will strip them automatically, or at the very least not respect them the way that they normally are when used as intended. You would need an iframe to properly do that.


This is definatly a problem. On this page http://jscheuer1.comli.com/postedit/postit_2_h.htm are you saving the file to the server when you click update? Because if you were you ould just use an Iframe...



It is tempting. The contenteditable division allows you to enter tags and text, the other division could be used to display the result. All of this with minimal coding required - provided of course you have a host with PHP enabled.

There already is a script for this sort of thing though:
http://www.dynamicdrive.com/dynamicindex16/richtexteditor/index.htm


Isn't that a WYSIWYG editor. I'm not trying to do that. I still want to use html tags, but have a live preview as well.

I hope that explains most of it.
Keyboard1333

jscheuer1
02-18-2012, 01:45 AM
Well, you cannot do this on my version because quotes are escaped. But if they were not, you could paste into the Edit Window:


<script type="text/javascript">
(function(){
document.write('anything at all, even an entire page of code');
document.close();
})();
</script>

And, anything you can paste into the Edit Window could be posted directly to the PHP page, requiring no user interaction other than clicking on a (perhaps cleverly disguised) submit button on another site to make it appear to be on your domain. If the person abusing this vulnerability were to study your site, they could even have the fake page they make link to other real and/or fake pages on your site. If those accept post or get input, the abuser would have total control over that, perhaps (and this would depend upon the sort of site you have) even getting passwords and other sensitive data from your unsuspecting users who think they are on your real site.

You have me though on the other point. You could have a preview in the View Window without the invalid tags while at the same time saving the tags to a separate file where they could be valid, or you could just save to a separate file and show that in an iframe as a preview.

I'd have to think about that one because it might fix the other problem. If the PHP file only writes to a file that shows in an iframe, that might remove the threat. As long as that file couldn't self execute and wasn't a PHP file, it should be fine.

But that's pretty much what that other script does. Except it doesn't save a file. It just writes to the iframe document. Saving a file would be nice if you wanted your users to be able to download their work.

I'm still not 100% sold on this. But tell me more of what you are envisioning.

keyboard
02-18-2012, 07:28 AM
I'm still not 100% sold on this. But tell me more of what you are envisioning.


Very well then.
I dislike wysiwyg editors. While they may be easier/quicker to use, they have serveral disadvantages. They don't provide all the functionality of html. And I haven't seen any with javascript capabilities(correct me if I'm wrong). What I would like to do is create a html editor that still uses html, but provides a preview window for viewing the page without having to click save, minimize, refresh.

Also I intend on adding more features at a future time. I just need help with the basic structure of the editor(mainly the ajax).

I hope that is enough to convince you :)
Keyboard1333

jscheuer1
02-18-2012, 06:33 PM
If this is for your own use, I just use a good context highlighting text only editor like NotePad++ or EditPad Pro and preview in the browsers locally or on my WAMP server localhost. It's a much fuller featured setup than you could ever hope to achieve with javascript/AJAX/PHP.

If its for a live web tool, I think there's CMS setups that include that sort of thing. You should checkout:

http://www.tinymce.com/

It's WYSIWYG, but I'm sure it must have text editing mode.

All that said, I'd be happy to provide you with AJAX tips in response to specific questions.

keyboard
02-18-2012, 09:45 PM
Thanks for your reply. I'd still like to have a go at this so I'm going to leave this thread as not resolved for a little while incase I run into any big problems. Could you please post/email/pm me the code for this (http://jscheuer1.comli.com/postedit/postit_2_h.htm) page. (and the relivent php). I'd like to have a fiddle with it because it should answer this (http://www.dynamicdrive.com/forums/showthread.php?t=67398) thread.
Thanks for your time
Keyboard1333

jscheuer1
02-19-2012, 03:15 AM
You can get the source code of the page with your browser's 'view source'. It's a plain HTML page, all the script code on it is on the page except for the linked in jQuery library, which is hosted on Google. Here's the source code of the PHP page (postedit.php):


<?php
$field1value = isset($_POST['field1value'])? $_POST['field1value'] : '';
echo html_entity_decode(strip_tags($field1value));
?>

keyboard
02-19-2012, 05:45 AM
Just had a thought. If the only problem with quotes being enabled was document.write couldn't you just search the #window1 for document.write on the php page and if it returns true just write an alert. It would be a lot less restrictive than disableling all quotes.
Keyboard1333

jscheuer1
02-19-2012, 07:05 AM
I just gave document.write as an example. There are lots of ways. Another is:


document.body.innerHTML = 'Whatever';

Besides that, disabling document.write would disable it for it's legitimate uses as well.

And I was playing around with the iframe idea a bit. But then I realized you can do the same thing with it by prefacing your other code with:


if(top.location !== location){
top.location = location;
}

which also has many variations. What this would do is make the page in the iframe the top page.

There might be some way of dealing with this drawback. If I think of one I'll let you know.

keyboard
02-19-2012, 09:15 AM
Okay well I was fiddling with this



<!DOCTYPE html>
<html>
<head>
<?php include 'settings.php'; ?>
<title>
Html Editor
</title>
<style type="text/css">
#window1 {
margin: 0;
background-color:<?php echo $fldrwindow1color; ?>;
word-wrap: break-word;
}
#window2 {
margin: 0;
background-color:<?php echo $fldrwindow2color; ?>;
word-wrap: break-word;
}
html, body {
height: 100%;
}
body {
background-color:<?php echo $fldrbgcolor; ?>;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
function clearwindow(){
var window1contents = document.getElementById('window1').innerHTML;
var window2contents = document.getElementById('window2').innerHTML;
if(window1contents == "<i>Click Here to Start Editing</i>"){
document.getElementById('window1').innerHTML = "&lt;html&gt;<br />&lt;head&gt;<br />&lt;/head&gt;<br />&lt;body&gt;<br />&lt;/body&gt;<br />&lt;/html&gt;";
document.getElementById('window2').innerHTML = "";
}
}
function resetwindow() {
var window1contents = document.getElementById('window1').innerHTML;
var window2contents = document.getElementById('window2').innerHTML;
document.getElementById('window1').innerHTML = "<i>Click Here to Start Editing</i>";
document.getElementById('window2').innerHTML = "<I>Viewing Window</I>";
}
</script>
<script type="text/javascript">
jQuery(function($){
var field1 = $('#window1');
var update = $('#update');
update.click(function(){
if(!field1.html()){
alert("Please enter a value");
field1.focus();
return;
}
jQuery.ajax({
url: 'postedit.php',
type: 'post',
data: 'field1value=' + encodeURIComponent(field1.html()),
success: function(results){
//alert(results);
if(fillwindow.filled){return;}
$('#window2').html(results);
}
});
});
});

</script>
</head>
<body onload="this.focus()">
<div style="float:left; width:7.5%; height:80%;"></div>
<div style="float:left; width:33.3%; height:80%; border:3px darkgrey solid; overflow:auto;" id="window1" onfocus="clearwindow()" contenteditable><i>Click Here to Start Editing</i></div>
<div style="float:left; width:2%; height:80%;"></div>
<div style="float:left; width:33.3%; height:80%; border:3px darkgrey solid; overflow:auto;" id="window2"><i>Viewing Window</i></div>
<br style="clear: left;">
<div style="float:left; width:7.5%; height:10%;"></div>
<input type="button" value="Update" id="update" style="margin-left:0;">
<input type="button" value="Reset" onclick="resetwindow()">
</body>
</html>


settings.php



<?php
$fldrbgcolor = "Grey";
$fldrwindow1color = "White";
$fldrwindow2color = "White";
?>


I haven't changed postedit.php

I must have stuffed something up because now when you use the enter key in
#window1, it stuff up the window by adding a double break and moving all the #window1 text down a line. Any help???

jscheuer1
02-19-2012, 10:46 AM
Add the highlighted:


<style type="text/css">
#window1 {
margin: 0;
background-color:<?php echo $fldrwindow1color; ?>;
word-wrap: break-word;
}
#window1 p {
margin: 0;
}
#window2 {
margin: 0;
background-color:<?php echo $fldrwindow2color; ?>;
word-wrap: break-word;
}
html, body {
height: 100%;
}
body {
background-color:<?php echo $fldrbgcolor; ?>;
}
</style>

keyboard
02-20-2012, 06:36 AM
Hmmm, thanks!!!
One more problem.
When you press enter in field1 and put nothing on that line, it shows up as a small white filled, black bordered box.
Any Help?

jscheuer1
02-20-2012, 04:34 PM
I don't know how that's creeping in there but it's not a printable character, Unicode ffff - the highest possible value, I'm not sure what it's used for*. But we can just strip it - where you have:


$('#window2').html(results);

Make that:


$('#window2').html(results.replace(/\uffff/g, ''));

By the way, Firefox doesn't add it. IE may be the only one.


*found this cryptic definition:


Unicode FFFF is used to represent a numeric value that is guaranteed not to be a character, for uses such as the final value at the end of an index.