0

How can i use AJAX to do something like:

<input type="text" name="test">

<?php
$test = $_POST['test']; //need to set the var "on the fly" 
echo $test;
?>

I need that the php var $test is auto-updated with the text/numbers that users set on the input named "test"

LIVE EXAMPLE OF USE: test

8
  • can you post what you have tried so far? Commented Aug 1, 2013 at 19:55
  • Please elaborate, you question is not clear. Can you show what you've tried and what is it that you expect and what is not working? Commented Aug 1, 2013 at 19:55
  • What javascript/jquery have you tried? Commented Aug 1, 2013 at 19:56
  • What's the reason you need to update a server-side variable on the fly? This would involve making an AJAX request on each keypress, which will get very tedious. There's most likely a better way to approach this situation. Commented Aug 1, 2013 at 19:57
  • What's with the rash of "i need to set a PHP variable from JS" questions as of late? Commented Aug 1, 2013 at 20:01

3 Answers 3

2

Ideally you need to add more information to your question, but I'd start off by looking into jQuery Ajax.

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

As per your linked example is this what you mean? JSFIDDLE.

<input type="text" name="test" id="test" value="" />
<input type="submit" id="submit" />

Base: <span id="base"></span>

$( document ).ready(function() {
    $('#submit').click(function(){
        $('#base').html($('#test').val());
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

hmm, i'm reading the link you told, but i need to finish it before vacation (-2days)..can please make a working fast example? The result is like that: (codetuts.altervista.org/test.php) but instead of pressing ENTER button, need to calculate it with no page refresh
Theres no ajax in the example you posted? I'll make something like what I think you want and update my answer
Corrected with what you want
Thanks, but js fiddle don't work. BTW i'll work on this, thanks!
0

You could use AJAX method from Jquery library

$.ajax({
 type: "POST",
 url: "some.php",
 data: { test: "testData"}
 }).done(function( msg ) {
 alert( "Data Saved: " + msg );
});

Comments

0

I wouldn't use jQuery.. Just add an onkeypressed listener, this will update you data:

<input onkeypressed="updatestuff();" type="text">
<script type="text/javascript">
     function updatestuff(){
         //ajax here
     }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.