I have spent all morning trying to figure out how I can call a PHP script from my JavaScript function and then return a value to output. I am not sure whether I can do this with just JavaScript or whether I have to include some Ajax aswell?
Here is the main page
<script>
$("document").ready(function (){
$("select").change(function(){
var currentValue = parseInt($(this).find("option:selected").val());
//Call Script script.php here
$("#output").html(result);
})
});
</script>
</head>
<body>
<select name="select">
<option value='1' >1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
<div id="output"><!---OUTPUT HERE----></div>
And here is the script I want to call (I have simplified it all down to make it easier to understand)
<?php
$result = $currentValue + 1;
?>
Basically I want it to read in the currentValue
variable and output the result variable back to the webpage, to be outputted again.
// Javascript:
$.ajax({
type: "GET",
url: "example.com/script.php?currentValue="+currentValue ,
dataType: "json",
statusCode: {
200: function (result)
{
$("#output").html(result.value);
}
}
});
// PHP
<?php
$result = $_GET["currentValue"] + 1;
echo json_encode(array("value" => $result));
?>
$.post('<url>', {currentValue : currentValue}, function(){}, 'json');
< url> example ajax/phpScript
Here ajax is controller and phpScript is the method in that controller
public function phpScript()
{
$phpScript = $_POST['phpScript'];
//add your code
}