Brigo
Brigo

Reputation: 1112

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);

Upvotes: 3

Views: 68

Answers (2)

user777
user777

Reputation: 87

To pass back to JS you should print the variable try this: echo $return;

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

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

echo $return;

Hope this helps.

Upvotes: 3

Related Questions