brigo brigo - 6 days ago 5
jQuery Question

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

Answer

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

echo $return;

Hope this helps.

Comments