开发者

Populate PHP variable with AJAX?

Im not sure if this is possible, but at the moment I have a form on my page where users can insert their interests, beneath that form are 3 PHP variables (Which dont currently show at first as there is no value assigned to them).

When a user enters an interest and clicks submit, my A开发者_开发技巧JAX takes over, populates the table and then reloads the page so the Variable now shows as it has a value.

Is it possible to not have to refresh the page, so I can say "if success $var = 'value';"?

I hope this doesnt sound too confusing, thanks


Since you're already using AJAX, why don't you just do the logic using Javascript? If you're using jQuery, have a success callback function execute the code you want.

The problem with sending data from AJAX to PHP is that PHP is a server side language, while AJAX is a client side one. By the time your browser sees the page, the PHP has been entirely executed and returned to you as HTML / CSS / Javascript etc.


No, you can't. By the time the HTML has rendered/displayed in the browser, PHP will most likely have long since finished generating the HTML in the first place. You could round-trip the values through an AJAX handler and then populate the places in your page where the values are displayed, but when why bother round-tripping? Just have the AJAX call fill in the values right then and there.


It is absolutely possible, and quite easy to do. Just make another php script and call it from your form page's javascript (I'm going to assume you're using jQuery):

$('#mysubmit').click(function() {
    $.getJSON(
        'form_ajax.php', // This is the php file that will be called
        { formVar1: $('#form-var-1').val() }, // Add all your form data here
        function(data) {
            // This is the function that is called after the php script is 
            // done executing. The 'data' variable will contain the $data
            // array you see in the following php file.
        }
    );
});

I prefer to use JSON, but other approaches are just as good. Check out the documentation for getJSON() and ajax(). Your php file would look something like this:

<?php
    $data = array();
    if ($_SERVER['REQUEST_METHOD'] == "POST") {
        $data['formVar1'] = $_POST['formVar1'];
    }
    echo json_encode($data);
?>

Of course, yours would probably do a lot more with the form data. Also, theres plenty of other approaches so go explore for the one the best suits your needs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜