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.
-
1Have a look at jQuery.get()Teun Zengerink– Teun Zengerink2012年07月21日 11:47:55 +00:00Commented Jul 21, 2012 at 11:47
-
2What's the use of increasing a value like that? You need to store the value using for example like MySQL!Alvin Wong– Alvin Wong2012年07月21日 11:49:42 +00:00Commented Jul 21, 2012 at 11:49
-
1What do you mean by increasing it like that, the php script i have written is very long, too long to post here that involves mysql and all that, i just made it simple to show the fact, that i need to get the currentValue into the php script and get the result value out and back to the main pageAl Hennessey– Al Hennessey2012年07月21日 11:51:46 +00:00Commented Jul 21, 2012 at 11:51
-
look at this example I wrote .. you can download the files devpazzi.com/how-to-get-data-from-php-script-with-ajax-jquerySkecci Dev– Skecci Dev2015年05月08日 04:54:41 +00:00Commented May 8, 2015 at 4:54
2 Answers 2
// 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));
?>
7 Comments
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
}