HTML form with PHP - php

I'd like to have a form that executes some php code without having to open a completely new php page. Right now, I'm familiar with "POST" so that I can execute a php file and call the variables from the HTML form using $_POST[variable] but, it takes time to open a new page, and I want to have a form that does the action right then and there.
For example, can someone write html code that creates a text box and a button, and when the user presses go, it displays the text that the user entered right next to the button.
Thanks!

Here's an HTML and PHP snippet to get you started. It uses jQuery and just writes the value of textarea beneath the submit button using AJAX.
HTML Snippet [file=so.html]
<!DOCTYPE html>
<html><head><title>SO Example</title>
<script
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js">
</script>
</head>
<body>
<form id="frm" name="frm">
<textarea id="txt" name="txt" rows="4" cols="40">
</textarea><br />
<input type="submit"><br />
<span id="result"></span>
</form>
<script type="text/javascript">
$('#frm').submit(function(e){
e.preventDefault();
$.ajax({
url:"/so.php",type:"post",dataType:"html",
data:$('#frm').serialize(),
success:function(obj){
$('#result').text(obj);
}
});
});
</script>
</body>
</html>
PHP Snippet [file=so.php]
<?php
echo $_POST['txt'];

If you want to execute php code after the page is loaded without opening a new page then you should be using a technology like AJAX. PHP is a pre-processor and is meant to be run to process a page, not for functions after that.
With AJAX you can use javascript to call a webpage that's processed by PHP. Then with that returned page/data you can do your page function.
For more info on ajax check here: http://en.wikipedia.org/wiki/Ajax_(programming)
I recommend looking at jQuery as an ajax wrapper: http://api.jquery.com/jQuery.ajax/
You can find a ton of tutorials online to get you started.

I'd look into AJAX, more specifically an AJAX call using jQuery. It looks a little bit like this for a POST request:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
});
And if I filled that out, it might look like this:
$.ajax({
type: 'POST', // Method of submission: POST or GET
url: 'processor.php', // The script to send to.
data: { id: 1, name: 'John' }, // The data to give to PHP.
success: function(data) { // Do something with what PHP gives back.
console.log(data);
}
});
For more info on jQuery's AJAX functions, head here: http://api.jquery.com/category/ajax/
You're interested in jQuery.ajax(), jQuery.post(), and jQuery.get() probably.

Related

Save data to PHP / Mysql with inline edit in CKEditor

I want to use "inline edit" of the new CKEditor 4 (http://docs.ckeditor.com/#!/guide/dev_inline-section-2), but can not find any example of how to save the data with PHP / MySQL.
Can you help me?
You need some AJAX magic. Via JavaScript inside the page you get the edited HTML. Then you send it to the server where a PHP script gets it and can pass it onto MySQL.
Here is a simple test case which will show you the ropes.
Let's start with the editable HTML.
<div id='textToBeSaved' contenteditable='true'>
<p>Using the <strong>Terminal</strong> in OS X makes you all-powerful.</p>
</div>
We also need a "Save" button which will be used to start the POST event.
<button onclick='ClickToSave()'>Save</button>
Such a button could well we positioned in the CKEditor toolbar itself, but that would require more coding and I'll leave it to someone who's better at JavaScript than me.
Of course you want to include CKEditor. For my sample code I'll also make use of jQuery, which I'll use for AJAXing the results.
<script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
<script type='text/javascript' src='CKEditor4/ckeditor.js'></script>
Now the script which will execute when you press the "Save" button. It will use CKeditor to grab the edited HTML, then jQuery to send it.
<script type='text/javascript' language='javascript'>
// <![CDATA[
function ClickToSave () {
var data = CKEDITOR.instances.textToBeSaved.getData();
$.post('save.php', {
content : data
})
}
// ]]>
This is it, you don't need anything else clientside.
On the server, you must have the PHP code which will act when the script POSTs the updated HTML. The script must be called save.php and be positioned in the same directory where the HTML is if you use my code verbatim.
My one-liner here will just save your HTML in a temporary file inside the /tmp folder. Feel free to add your MySQL magic instead.
<?php
file_put_contents('/tmp/serverside.html', $_POST['content']);
?>
This is the way I've done it in the past:
The current_page_id relates to the table row we wish to update, otherwise we wouldn't know what record we need to update.
<div id="editable">My body text</div>
<input type="hidden" name="page_id" id="current_page_id" value="10" />
<script type="text/javascript">
CKEDITOR.disableAutoInline = true;
CKEDITOR.inline('editable', {
on: {
blur: function( event ) {
var params = {
page_id: $("#current_page_id").val(),
body_text: event.editor.getData()
};
$.ajax({
url: 'php_file_to_post_to.php',
global: false,
type: "POST",
dataType: "text json",
data: params,
success: function(result) {
console.log(result);
}
});
}
}
});
</script>
The inside of your php_file_to_post_to.php PHP file you simply catch the ajax post request and update the row based off of the page_id variable which has also been posted along with the edited content.
This is how you will get text area data
CKEDITOR.instances.editor1.getData()
CKEDITOR is nothing but the object you used to create functionality.
Thanks so much for the code. Try to improve de code with file_put_contents('page.php', stripslashes($_POST['content']));
And add to the div onBlur="ClickToSave()" and now you can to delete de save button.

Why does a submission form work, but my ajax doesn't?

I am trying to create a button on my chat that will allow someone to print the conversation. So I made the button that runs a PHP script that creates a new file, writes the conversation to file, and also writes the following jQuery.
jQuery AJAX Call
function OnBeforeUnLoad () {
$.ajax({
type: 'GET',
url: 'deleteFile.php',
data: {
pageName: ".$pageName."
},
dataType: 'text',
success: function(data){alert('Good bye 1!');}
});
return;
}
HTML Put into page
<br/><br/><form method="get" action="deleteFile.php"> <input type="submit" value="Close this Window"/>
<input type="text" value="'.$pageName.'" name="pageName" style="visibility:hidden"/></form>
deleteFile.php
<?php
$pageName = $_GET['pageName'];
$fullURL = 'PrintPage'.$pageName.'.php';
unlink($fullURL);
echo '<script>window.close();</script>';
?>
When the page shows up and I click the "Close this Window" button it does exactly what I want. It deletes the file and closes the window. But I do not get the same results when I close the window (aka OnBeforeUnLoad()). I even tried triggering submit by giving the form an id of deleteFiles and then doing $('#deleteFiles').submit() and it still didn't work.
How do I get the AJAX to work within the OnBeforeUnLoad function?
The form calls the data pageName but the ajax calls it url.
You probably don't want to prefix and suffix the value with . characters either.
Feel like a dummy.... After making all those changes... I found out all I needed to do was add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
to the header.
Because I was dynamically creating the page in php, I forgot I needed to readd the jQuery.
Always the small things.. Thanks everyone for the help.

Mootools script corrupts php tags when sets html into document

I am developing module for Joomla 2.5. and I had one problem. I wanted to send data to same page and receive answer in it, without reloading. I found solution for it, but then I stuck again.
The problem is that when I want to insert into div tags code <?php echo $msg; ?> using javascript it turns into comment <!--php echo $msg; ?-->.
Here is full function
<script type="text/javascript">
window.addEvent('domready', function request() {
$('SNbutton').addEvent('click', function(event) {
event.stop();
var url = window.location.href;
var message = document.getElementById('message');
var msg = '<?php echo $msg; ?>';
var req = new Request.HTML({
method: 'post',
url: url,
data: {'artID' : $('artid').get('value')},
onComplete: function(response) { message.set('html', msg).setStyle('display','inline');
}
}).send();
});
});
</script>
and here is result html:
<form name="accept_form" action="#" ><br/>
<input type="hidden" id="artid" name="artID" value="4"/>
<input type="button" class="SNbutton" id="SNbutton" value="I take it!" title="Accept this job and bound it to your profile.">
</form>
<div id="message" style="display:inline;" ><!--php echo $msg ?--></div>
P.S. This script should take article id and send it to same page, where, depending on article, page will generate message which should be displayed in right place, but somehow its getting corrupt.
P.S.S. Don't worry about that server executes php code. As far as I know its not wotking if script is included trough src in head tags.
Could you try doing it this way?
var msg = <?php echo "'".$msg."'"; ?>;
I'm thinking that maybe the fact it's inside quotes is messing up the interpreter.
A chunk of PHP code inserted into a page that has already been loaded into a browser can't be interpreted by the server - it's just a string. To get the $msg value you want, you need another page that can respond to your Request.HTML call and get some code back.
The distinction here is between server-side and client-side code. I think to test this make your url something like provideMessage.php and then have THAT page respond to your Request.HTML.
It's possible I'm missing something about how Joomla modules work.

jquery php insert data into mysql without refreshing the page

Hello I have the next code into my website:
<input type="text" id="name" name="name" width="25px"/>
Add User
I need that when I click "newUser" the value of the name is saved into my mysql database without refreshing the page.
Any exemple of how to do this?
If you don't want to use a <form> and a submit button which would be the absolutely correct way to do this, you will need to use javascript and AJAX:
Subscribe for the onclick event of the anchor
Send an AJAX request to the server passing the value of the name entered in the textbox
Cancel the default action of the link
Add User
and the insert function could be defined in a separate javascript file:
function insert() {
var name = document.getElementById('name').value;
// TODO: send an AJAX request to the server
return false;
}
http://api.jquery.com/jQuery.ajax/
$('#newUser').click(function(ev){
$.ajax(...);
ev.preventDefault();
});
This can be done on the client side with jquery's ajax libraries to create the refreshless submit.
Here's an example of some html and javascript
<html>
<head>
<script type="text/javascript" src="jq/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
function adduser()
{
var data=$("#adduserform").serialize();
$.ajax({
type: "POST",
url: "adduser.php",
data: data,
dataType: "html",
});
}
</script>
</head>
<body>
<form id="adduserform" name="adduserform">
<fieldset>
<input type="text" id="name" name="name" width="25px"/>
</fieldset>
</form>
Add User
</body>
</html>​
On the php side just code like you would if you were submitting a form via post.
I haven't had time to try it, but I hope it works :)
Like the others have suggested, look on the jquery site for more info.
You can do an Ajax call with JQuery that will send the name to the server. In your PHP code you will be able to create the Insert Query in your user table.
You can use JavaScript for that. Take a look at jQuery ajax: http://api.jquery.com/jQuery.ajax/
note: next time try googling, or at least provide what you have tried

Form auto submit ajax not working

I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/

Categories