简体   繁体   中英

Using AJAX to pass Javascript var to PHP on same page

I have a page that started with an empty PHP var. Then, when the user clicks on a link I want to pass the value of the name attribute to a JS var, and then pass that JS var to the same page and then update the PHP var with the JS var value. Here is a simple example of what I am trying to do:

// PHP
<?php
    // Starts empty, then when posted should update
    $jsVar = $_POST['jsVar'];
    echo $jsVar;
 ?>


<!-- HTML-->
<!-- Link to click with name vlue to pull-->
<a href="#" name="link">Click Me</a>


<!-- JAVASCRIPT -->
<!-- Import jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<script type="text/javascript">

    // On link click
    $('a').click(function(e){

        // Prevent link default behavior
        e.preventDefault();

        // Store name vale as jsVar
        jsVar = $(this).attr("name");

        
        $.ajax({
            type: "POST",
            // url: ""   <--------------- From what I read, if you want to post to the same page you just don't inclue the URL?
            data: {jsVar : jsVar}, // <--------- This was also something I found online that supposedly helps pass JS vars to PHP?
            success: function(data)
            {
                alert("success!");
            }
        });
    });

</script>

A lot of people say that I don't need AJAX for this. The example I provided is a much similar version of what I am trying to do, which is dynamically change an include file based on the user clicking a sidebar item. I don't want to use a form for this, do I?

Ah! As I continued to look, I found that jQuery has the .load() function which is EXACTLY what I wanted. Dang! I was able to build this and make it work:

// Store clicked page
var currentPage = $(this).attr("name");
// Build filepath
var currentPagePath = "pages/" + currentPage + ".php";

// Find the div I want to change the include for and update it
$("#pageContent").load(currentPagePath);

So easy. Dang. Thanks all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM