tags:

views:

68

answers:

4

I am practicing on ajax. I don't know what, or how to do it. This is my first time to do this. Here is my code.

<?php
function save() {
  // mysql connection

  $text = $_POST['name'];

  // insert query
}
?>

<input type="text" name="name" onchange="<?php save() ?>" value="default">

What I'm trying to do is like this. The input type text has a default text inside. Then if I change that it will automatically save. How can I do that?

A: 

I don't know if you should be saving like that.

You probably want the event onblur(), or better still, add the event via JavaScript, do not use the inline attribute.

But the biggest problem is you are trying to call a PHP function from JavaScript. JavaScript can not interact with PHP like that. Think of the client/server relationship and where the code is ran.

You will need to call a JavaScript function that sends the input's value that PHP can then use to write to your database.

alex
+4  A: 

Short answer: You can’t call a PHP function from JavaScript, so the way you tried it doesn’t work.

Long answer: You will need to find an introduction to AJAX and learn it. In order to do what you describe, you will need to:

  • instantiate an XMLHttpRequest object in the JavaScript
  • tell it to contact the server at some URL where the server will invoke your PHP script
  • tell it to send all the necessary information (esp. the text the user typed in) via POST
  • write the PHP script in such a way that it will save the text and return something like true/false to indicate success/failure
  • back in JavaScript, handle the response when it comes in, e.g. by displaying a message saying “message saved” or “message could not be saved: (error message)”, depending on whether it succeeded or not.
Timwi
A: 

I think you need to understand the concept of AJAX first.

Try this. http://www.w3schools.com/ajax/ajax_intro.asp

To give you a simple idea; Imagine there is an imaginary <FORM> tag where in it has a method, action and data to submit. In your case, the onchange event of the input triggers the "SUBMIT" of this <FORM> assuming that you already set the values of the data to be submitted. When this happens, page doesn't refresh or redirect. Instead, javascript creates a "separate process thread" just like the <FORM> was submitted in a different "window". Thus, the term "Asynchronous".

AJAX is more of a Javascript thing.

sheeks06
A: 

There are various ways you can create AJAX call. The easiest is to use Javascript Framework like Mootools or JQuery. Ajax is simple this ways. Check http://demos111.mootools.net/Ajax.Form for Mootools demos and jquery here http://docs.jquery.com/Tutorials.

The logic is pretty simple. Add event to the text box to save the box once value changes. Your event function will generate Ajax request and send it to the server, receive response which you can use to let user know the status of save event, if you choose.

Here is quick thing I wrote for you, might help understand. Will need to include Mootools library. Might have bugs, but concept of Ajax call is there. page=index.php

<?php
//  PHP before anything else...
//
//  Check to see if task is specified and need to save changes
if (isset($_POST['task']) && $_POST['task'] == 'save') {
    // mysql connection
    $text = $_POST['name'];
    // insert query
    $isSuccess = 'Status of SAVING CHANGES';

    //  Output... output will be used by 'update' to set value of <div id="log">...</div>
    //  so user knows what is happening
    echo $isSuccess ? 'Successfully Saved' : 'Failed to Save';
    exit();
}
?>
<html>
    <head>
        <!--    NEED TO INCLUDE MOOTOOLS LIBRARY -->
        <script type="text/javascript">
            window.addEvent('domready', function(){
                $('name').addEvent('blur', saveChanges);

                /**
                 * Generates request and saves changes
                 */
                function saveChanges(){

                    //  URL which will be called
                    var url = "index.php";

                    //  New Ajex request. Note that it will be sent because of .request() at the end
                    new Ajax(url, {
                        //  Method : post/get
                        method: 'post',

                        //  Data to be passed 
                        data :{
                            name : $('name').value,
                            task : 'save'
                        },

                        //  Output of the AJAX will be set to this element
                        update: $('log')

                    }).request();
                }
            });
        </script>

    </head>
    <body>
        <form action="index.php" onsubmit="return false">
            <div id="log"></div>
            <!-- SOME CONTENT ... -->
            <input type="text" name="name" id="name" value="">
        </form>
    </body>
</html>
Alex