Access JavaScript variables value in php to store in mysql

前端 未结 3 536
盖世英雄少女心
盖世英雄少女心 2020-12-22 11:12

Just simple, I am trying to access the variable in javascript inside the php while working with elrte, bleow is my index.php file


<         


        
相关标签:
3条回答
  • 2020-12-22 11:18

    You need 2 pages, one which will send AJAX (this you have) and one wich will respond (below):

    <?php
    ///ajax.php
        if(isset($_POST['updabt']))
        {
            extract($_POST);
            $q1=mysql_query("update aw_about_us set abt_title='$atitle', abt_small_line='$atag', abt_content=''") or die(mysql_error());
            if($q1==true)
            {
            ?><script>alert("Page Updated Successfully!!");</script><?php
            }
            else
            {
            ?><script>alert("Page Not Updated!!");</script><?php
            }
        }
    ?>
    

    In javascript you create AJAX post

    data['updabt'] = '';
    
    $.ajax({
      type: "POST",
      url: 'ajax.php',
      data: data,
      success: function(html) { $('result').append(html); },
      dataType: 'html'
    });
    
    0 讨论(0)
  • 2020-12-22 11:33

    You'll need to submit the value to your PHP script using a POST request to your server. You can do this with Ajax requests, and I believe jQuery has built-in methods for Ajax which are cross-browser.

    0 讨论(0)
  • 2020-12-22 11:33

    You can use AJAX (easiest with a library such as jQuery) to submit the variables to another PHP script that will INSERT the values to your database.

    Start by reading the following...

    jQuery.ajax

    jQuery.post

    This is actually very simple once you get your head around the subtleties of AJAX.

    Here is a simple example to get you off and running. Suppose you wanted to log something to your PHP error log...

    This would be my JavaScript function:

    var log = function(val) {
        $.post("ajax.php", {"mode": 'log', "val": val}, function() {});
    }
    

    ajax.php would be a collection of functions, ideally a class...

    public function __construct() {
        $arrArgs = empty($_GET)?$_POST:$_GET;
    
        /**
         * using 'mode' I can send the AJAX request to the right method,
         * and therefore have any number of calls using the same class
         */
        if (array_key_exists('mode', $arrArgs)) {
        $strMethod = $arrArgs['mode'];
    
        unset($arrArgs['mode']);
        $this->$strMethod($arrArgs);
        }
    }
    
    protected function log($arrArgs) {
        error_log($arrArgs['val']);
    }
    

    The same idea can easily be adapted to write data to a database.

    0 讨论(0)
提交回复
热议问题