简体   繁体   中英

First script using $.ajax and it doesn't work

This would be my very first attempt with jQuery and Ajax (and Jacascript in general), so don't shoot me if it's rubbish!

What I want to achieve is: having a page product.php where a product is displayed with a nice img and a description. At the bottom putting one <select> menù: when an <option> is clicked, a jQuery code load the code into tester.php passing to it the value of the clicked option. The .php script will analyze the value and, based on its value, it will send a query to extract the relative price and img. Now, before doing this, I wrote a really simple code (following the official documentation and some answers here) that should pass a variable $return back to the HTML page but I guess the callback it doesn't work and I don't have enough experience in jQuery yet to find the problem and a relative solution.

Can anyone more pro explain me why this doesn't work? Thanks!

ajaxpost.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#menuSelect").on("click", function(){
        var str = $("#menuSelect").val();
        $.ajax({
            type: "POST",
            url: "tester.php",
            data: { value: str },
            success: function(data){
                console.log(data);
            }
        })
    })
});
</script>
</head>

<body>
<div id="txt" >
</div>

<select id="menuSelect">
  <option value="0"></option>
  <option value="1">OPT1</option>
  <option value="2">OPT2</option>
</select>

tester.php

<?php
    $value = $_POST["value"];
    function provaAJAX($value) {
        switch ($value) {
          case "0":
              $return = "First option selected";
              break;
          case "1":
              $return = "Second option selected";
              break;
          case "2":
              $return = "Third option selected";
              break;
        }
        return $return;
    }

    $return = provaAJAX($value);

You should print the variable to be passed back to the JS :

echo $return;

Hope this helps.

要传回JS,你应该打印变量试试这个:echo $ return;

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