change php variable with ajax

后端 未结 5 416
时光说笑
时光说笑 2020-12-06 08:55

I have an php variable like this:

PHP Code:

$php_value = \'Am from PHP\';  

And I want to be able to change this variable with jQue

5条回答
  •  有刺的猬
    2020-12-06 09:33

    If I understand your question correctly, AJAX cannot post data to PHP code on the same page. I've been told that it can, but it is not trivial - still, I cannot imagine how that is possible. At any rate, AJAX is easy if a secondary PHP file is used.

    Here is an example of what I mean. If you try this:

    
    
    
    
        
        
    
    
    
    
    
    
    

    The popup will contain the HTML for the page.


    However, if you use two files:

    file1.php

    
    

    file2.php

    
    
        
        
    
    
    
    

    The popup will contain only the word "Hello".

    To use ajax, you must call an external PHP file.


    After considering the above, note that Quentin's answer is important -- even if you use AJAX to set a PHP variable on the server, that variable disappears after the AJAX completes -- just like the PHP variables all disappear after your index.php has finished rendering the DOM and presenting it to the visitor's browser.

    So, what's to be done? Two options.

    (1) As Quentin points out, you can store values permanently in a database, or

    (2) You can use a PHP superglobal, such as a $_SESSION variable. For example:

    Client side: file2.php

    var storeme = "Hello there";
    $.ajax({
        type: 'POST',
        url: 'file1.php',
        data: 'stored_on_server=' +storeme,
        success: function(data) {
            alert(data);
        }
    });
    

    file1.php


    You can later retrieve that variable value thus:

    $.ajax({
        type: 'POST',
        url: 'file3.php',
        success: function(data) {
            alert(data); //a popup will display Hello There
        }
    });
    

    file3.php

提交回复
热议问题