Hi I am trying to make a page which will use the $.post method in Javascript to post the data from a live text field through to another script when the space bar is pressed. I want the data from a the page known as index.php to be posted through another file called save.php. I want to the value of txt_a textfield to to be the value of the post varible text. How would I do this? Below is my code so far...
<html>
<head>
<script type="text/javascript">
function event_a() {
if (event.keyCode == 13) {
$(document).ready(function(){
txt=$document.getElementsByName('txt_a')[0].value;
$.post("save.php",{text:txt});
};
};
}
</script>
</head>
<body>
<form method="POST" name="" action="">
<input name="txt_a" type="text" id="txt_a" onkeypress="event_a()"/>
</form>
</body>
</html>
Thanks
This should get you started:
$(function(){
$('#txt_a').keyup(function(e){
if(e.which === 13) {
$.post('save.php',{text: $(this).val()}, function(data){
//do something with the response
});
}
});
});
And in save.php:
$text = isset($_POST['text']) ? $_POST['text'] : null;
Your javascript function should look more like this:
function event_a(event) { // event needs to be defined as arg to use.
if (event.keyCode == 13) { // ready is used to trigger code when the page is ready, not needed here
var txt=$('txt_a').val(); // assuming you are using jQuery, you can access the value like this
$.post("save.php",{text:txt});
}
}
Why are you passing variable from one file to the another? Use $_SESSION to save and retrieve the set data/variable in multiple pages .
Related
I have some problems with understanding of ajax use.
Let's say I have file like this (this is just a pseudo code, dont look at the basic mistakes right now please) I have read so many articles, but i find them so hard to understand
///////////////// file 1 /////////////////
<?php
x = 1;
<button onclick=somefunction(x)></button>
?>
<script>
//here goes some ajax code sending this x variable to another php file
</script>
Lets say it looks like this
////////////// file 2 ////////////////
<?php
/get x variable + sendint it back
return x=2
?>
Now what i want to do is to make this x value come back to the first script and make x=2. How do i do this?
Here is an example using JQuery with some notes to try to describe what happens.
<html>
<!--file: ajax_basic.php-->
<head>
<title>Ajax Basic Example</title>
</head>
<body>
<input type="text" id="example_input" value="1">
<button id="example_button">Example</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// .click(function() executes an anonymous function when the button is clicked
$('#example_button').click(function() {
// get the current value from the input
test_value = $('#example_input').val();
// $.get is the AJAX method.
// It sends the object {'sent_value': test_value} to test.php
// function(response) is the the function that will be executed when
// a response is returned from the test.php
$.get('test.php', {'sent_value': test_value}, function(response) {
// here, x is taken from the response of the php script.
// You can do whatever you like with this value.
x = response.returned_value;
// for this example, it updates the value of the text input
$('#example_input').val(x);
}, 'json');
});
});
</script>
</body>
</html>
This is the PHP file that will handle the request. All it does for this example is increment the value it receives and return the new value.
<?php
// file: test.php
$response = array('returned_value' => $_GET['sent_value'] + 1);
echo json_encode($response);
If you are using jQuery, you should switch from onclick=somefunction(x) to a jQuery binding, ie. .on()/.click()/etc. see https://stackoverflow.com/a/826697/689579
Using jQuery you could do something like-
<?php $x=1;>
<button id="mybutton">MyButton</button>
<script>
var x = <?php echo $x; ?>; // set initial x value to php value
$(function(){
$('#mybutton').click(somefunction);
});
function somefunction(){
$.ajax({
url: 'phppage.php',
data: {number:x}, // send current x value
...
success: function(result){
x = result; // when php file returns 2 (or other value increase x
}
});
}
</script>
I'm trying to submit a little contact form.
Here is my jquery to POST:
<script>
$(document).ready(function(){
function submit_contact()
{
$.post("http://www.domain.com/wp-content/themes/toronto/handlers/contact.php", {
contact_text: $("[name='contact_text']").val(),
contact_email: $("[name='contact_email']").val(),
}, function(data){
console.log( data );
});
}
});
</script>
Here is my html that handles the form:
<form method="post" >
<textarea id="contact_me_text" name="contact_text">Ask me anything!</textarea>
<div>
<input type="text" name="contact_email" value="Email"/><br/><br/>
<a id="contact_submit" href="javascript:submit_contact()">Submit</a>
</div>
</form>
Everything seems to look ok but the form is not submitting. I've run the .php file through a regular submit and it works fine.
Any thoughts?
You need to declare your function outside of $(document).ready() and then call it using anything.
Why can't I ?
As Local Variables cannot be accessed from outside, similarly local functions cannot also be accessed.
Try this:
<script>
$(document).ready(function(){
function submit_contact()
{
$.post("http://www.domain.com/wp-content/themes/toronto/handlers/contact.php", {
contact_text: $("[name='contact_text']").val(),
contact_email: $("[name='contact_email']").val(),
}, function(data){
console.log( data );
});
}
$('#contact_submit').on('click', function(){
submit_contact();
return false;
});
});
</script>
and then remove the JS inside HREF attribute.
You need to declare the function outside ready function of jQuery. Moreover you can use serializeArray to determine data to send. By using this you will not need to mention every control name. On server side you can receive the input with same names you have mentioned in your form.
function submit_contact()
{
var params = $("#formId").serializeArray();
$.post("http://www.domain.com/wp-content/themes/toronto/handlers/contact.php", params, function(data){
console.log( data );
});
}
I would like to submit a <form> automatically if:
if(isset($_POST['action']) && ($_POST['action'] =='confirmado')){
submit form.
I donĀ“t know if I should use a javascript script.
I try doing this but it is not working.
<script>
if(isset($_POST['action']) && ($_POST['action'] =='confirmado')){
$("#form").submit(function(){
document.form.submit();
return false;
}
</script>
You are trying to mix up PHP, which is a server-side language, with Javascript, which is a client-side language. So, that won't work.
Moreover, the submission of a <form> is NOT captured in its $_POST array as $POST['action']. The method of submission is POST and the $_POST array contains data submitted via the form's html elements.
Try this:
$( '#form' ).submit(function () {
if ( this.action !== 'confirmado' ) return false;
});
First of all, I agree with coder1984: you are mixing PHP with Javascript, and you are trying to access POST data in the client side, which is not possible. If I can guess what you are trying to do, maybe this code will help you:
<script type="text/javascript">
if (<?php echo (isset($_POST['action']) && ($_POST['action'] =='confirmado')) ? '1' : '0'; ?>) {
document.form.submit();
}
</script>
If i understand your code right, you would like to only submit the form if the field "action" equals "confirmando". Since you are allready using jQuery let's keep at it.
JavaScript:
<script>
$('document').ready(function() {
$('input[name=action]').change(function() {
if($(this).val() == 'confirmando') {
$('form').submit(); // If you would like to do a normal sumbit
$.post('my_php_file.php', $('form').serialize(), function(data)) { // or use AJAX
/* var data now contains the output of the PHP file */
}
}
});
});
</script>
It still makes sense to check the submited form in PHP when you receive the data from the form.
The PHP:
<?php
$mainView = "views/dashboardView.php";
?>
The HTML:
<div class="mainContent">
<?php include($mainView); ?>
</div>
I would like the click event of a button to change what view .mainContent shows and I believe AJAX can accomplish this but as yet have not been able to get it to work.
Any advice?
You would have to modify your PHP script to allow for this.
For example:
PHP:
if (isset($_POST['change']))
{
$mainView = $_POST['change'];
echo $mainView;
}
HTML & jQuery:
<button id="change">Change the var</button>
<script>
$("#change").click(function() {
$.post("file.php", {change: $(this).val()},
function (data)
{
$("#mainContent").html(data);
});
});
</script>
<script type="text/javascript>
function changePage(pageDest){
var xmlobject = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlobject.onreadystatechange = function (){
if(xmlobject.readyState == 4 && xmlobject.status == 200){
document.getElementById("mainContent").innerHTML = xmlobject.responseText;
}
else{
document.getElementById("mainContent").innerHTML = 'Loading...';
}
}
xmlobject.open("GET",pageDest,true);
xmlobject.send();
}
</script>
<div class="mainContent" id="mainContent">
Change this HTML
</div>
<div onmouseup="changePage('views/dashboardView.php')">Get dashboard view</div>
The parameter in the changePage function is the location of the page that you would like to place in your mainContent <div>
Does this help?
You cannot change the value of a PHP variable, as PHP is Server Side (done first), and JS is Client Side (done after Server Side).
Typically AJAX is used to repopulate an area of a web page, but that would suit your purpose. In the example below, ajax/test.php is the new file you want to include. Obviously change the path/name as you wish, and create that file.
I will add though, if you are repopulating a large chunk of your page, it will probably be just as quick to fully reload it.
$(function(){
$('.your-button-class').on('click', function(){
$.post('ajax/test.php', function(data) {
$('.mainContent').html(data);
});
});
});
Storing the View in the session, will keep the site displaying this view until the user closes the browser and ends the session, the session expires or they change the view again.
The include that sets mainView
<?php
session_start();
$mainView = "views/dashboardView.php"; // default
if(isset($_SESSION['mainView']))
{
$mainView =$_SESSION['mainView'];
}
?>
// the ajax script that sets the mainView
<?php
session_start();
$_SESSION['mainView']='views/'.$_GET['mainView'].'.php';
?>
the javascript link for ajax
ajaxURL='ajax.php?mainView=otherDasboard';
you may also want to check for empty session variable and that the file exists before setting it
I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.