PHP value inside JavaScript - php

The following code works fine, the function load() sends the selected radio button info to the PHP page and display the returned:
<head>
<script>
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
<input type="radio" name="category" value="30" />ButtonC
</div>
<div id="myDiv">Click the button to load results</div>
</body>
myPHPfile.php
<?php
if( $_REQUEST["selectedButtonValue"] )
{
$buttonPHP = $_REQUEST['selectedButtonValue'];
echo "Value button is ". $buttonPHP;
}
?>
I need an alert box message of the returned PHP value, inside the script, as follows:
;
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue});
alert(<?php $buttonPHP ?>);
;
Would it be possible to write the PHP value inside JavaScript?

You can just add a callback function in .load(), like this:
$("#myDiv").load('myPHPfile.php',
{selectedButtonValue : buttonValue},
function(data){
alert(data);
});
If you only want the value of the $buttonPHP to be displayed in the alert, change your echo to
echo $buttonPHP;
instead of
echo "Value button is ". $buttonPHP;
*Note: There is an issue with .load() function. It will not work if you access your html page locally/directly, you need to put it on a server. Or you can use xampp, wampserver, etc. *
Hope it helps.

Yes, almost had it:
alert('<?php echo $buttonPHP; ?>');

Your doing it right now, but you need to output the value:
alert(<?php echo $buttonPHP ?>);
On a sidenote, it seems like you don't have it really clear to you what happens.
HTML, css and javascript runs on the clients(the visitors) computer and the PHP code runs on the server, that means that the you can always combine php output with client-side code, and this is done regularly, just as you have done.
This is also one of the reasons why PHP is so flamed as a language, because of it low threshold to get started with, it is way to easy to create code that works, but that is a hell to maintain.
This is not a comment to your code, but a general reflection on php.

Either, you have to put the alert in the PHP generated code:
echo "<script type=\"text/javascript\">alert('Value button is ". $buttonPHP . "');</script>";
Or you have to use $.get function:
$.get('myPHPfile.php', {selectedButtonValue : buttonValue}, function(data) {
alert(data);
});

Related

Simple jquery ajax post php not working

Hi iam learning jquery with php. I created very small php and jquery code to getting value but it's not working. I check console but not giving any information i have referred jquery api documentation same process i followed but no use. How can i solve this.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var term= $("#sterm").val();
$.post('oopsdata.php', {nwterm: term}, function(data){
("#container").html(data);
});
});
});
</script>
<body>
<form class="" action="" method="post">
<input type="text" name="" value="" id="sterm">
<input type="submit" name="" value="Search term" id="submit">
</form>
<div id="container">olddata</div>
PHP Code
<?php
$newterm = $_POST['nwterm'];
if($newterm == 'bio'){
echo "Request received This is the new data"
} else {
echo "no data received;"
}
?>
There are few issues with your code, such as:
You need to prevent your form from being submitted in the first place. Use jQuery's .preventDefault()
Missing $ before ("#container").html(data);
Based on the above two points, your jQuery code should be like this:
$(document).ready(function(){
$("#submit").click(function(event){
event.preventDefault();
var term= $("#sterm").val();
$.post('oopsdata.php', {nwterm: term}, function(data){
$("#container").html(data);
});
});
});
There are two syntax errors in your PHP code. Missing ; in both your echo statements.
So based on the above point, your PHP code should be like this:
<?php
$newterm = $_POST['nwterm'];
if($newterm == 'bio'){
echo "Request recieved This is the new data";
}else{
echo "no data recieved";
}
?>

How to get result from php to html use ajax?

Updated: It still not work after I add "#".
I am new to ajax. I am practicing to send value to php script ,and get result back.
Right now, I met one issue which I can not show my result in my html page.
I tried serves answers online, but I still can not fix this issue.
My index.html take value from the form and send form information to getResult.php.
My getResult.php will do calculation and echo result.
How do I display result into index.html?
Hers is html code
index.html
<html>
<body>
<form name="simIntCal" id="simIntCal" method="post"
>
<p id="Amount" >Amount(USD)</p>
<input id="amount_value" type="text" name="amount_value">
<p id="annual_rate" >Annual Rate of Interest
(%)</p>
<input id="rate_value" type="text" name="rate_value">
<p id="time_years" >Time (years)</p>
<input id="time_value" type="text" name="time">
<input id="calculate" type="submit" value="Calculate">
</form>
<p id="amount_inteCal" >The Amount (Acount
+ Interest) is</p>
<input id="result" type="text">
</body>
</html>
ajax script :
<script>
$('#simIntCal').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'getResult.php',
data: $('#simIntCal').serialize(),
success: function (result) {
$("#result").text(result);// display result from getResult.php
alert('success');
}
});
});
</script>
getResult.php
<?php
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
//do some calculation
$result=10;//set result to 10 for testing
echo $result;
}
?>
You are missing the '#' in front of your css selector for result.
$("result").text(result);// display result from cal.php
Should be
$("#result").text(result);// display result from cal.php
index.php
----php start---------
if(isset($_POST['name'])){
echo 'Thank you, '.$_POST['name']; exit();
}
----php end ---------
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function test(){
var formDATA = {'name': $('#input_name').val()}
$.ajax({
type: 'POST',
url: 'index.php',
data: formDATA,
success: function(response){
$('#result').html();
}
});
}
</script>
<input id="input_name" type="text" value="">
<button onclick="test();">Test Ajax</button>
<div id="result"></div>
Try something simple, this is a very basic version of ajax and php all in one page. Since the button triggers the function you don't even need a form (doesn't mean you shouldn't use one). But i left it simple so you could follow everything.
Sorry when i added php open and closing tags it didn't show up as code.
Also don't forget to include your jquery resources.
In your html file where you want the result to display, you probably want to be using a div.
Currently your code is using an input field:
<input id="result" type="text">
And what you probably want is something like this:
<div id="result"></div>
Unless you were intending to have the result show up in an input field inside your form, and in that case, the input field isn't actually inside your form code.

Php vars within javascript

I have a bit of code to record a certain action
$('#record').click(function(){
$.get("../confirm.php", { "id": '<?php echo $record; ?>' }, function(data){});
});
Which works fine, but i don't want the page to be full of javascript and such as i have other things like this on it too, so i am trying to move it to a js file.
In the php file
<script type="text/javascript">var record = "<?= $record ?>";</script>
<script type="text/javascript" src="jsfile.js"></script>
In the js file
$('#record').click(function(){
$.get("../confirm.php", { id: record}, function(data){});
});
But it doesnt want to play ball, any ideas how to do this?
Make 'record' as class of div and assign php variable $record as its id.Use event.target.id to get variable $record from div.
<div class="record" id="<?php echo $record;?>">
Your code here
</div>
And Use this
$('.record').click(function(event){
var record=event.target.id;
//your code here
});
If I may a suggestion to you. Set in the view on the element the ID. Then when the action is clicked, get the id for the data.
Example:
<input type="text" name="inputName" id="<?php echo $record; ?>" class="btnToRecord" />
$('.btnToRecord').click(function(){
var clickedElement = $(this);
$.get("../confirm.php", { id: clickedElement.attr("id") }, function(data){});
});
Edit: Correction for $(this) was pointing to the get instead to the element, putting in a var will fix the problem

Codeigniter, getting ajax to run on button press

My original goal was to get a php file to execute on a button press. I used ajax. When the javascript was in the view, it worked.
However, I tried to switch the javascript to its own .js file and include it in the header. It doesn't work anymore. I am confused.
the model code:
public function insert_build($user_id)
{
$query = "INSERT INTO user_structure (str_id, user_id) VALUES ('7', '$user_id')";
mysql_query($query) or die ('Error updating database');
}
Something interesting to note here is that when I include $user_id as a value, it completely negates my headertemplate. As in, it simply doesnt load. When I replace $user_id with a static value (i.e. '7') it works no problem.
This is my view code :
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<select name="buildID" class="buildClass">
<option value="0" selected="selected" data-skip="1">Build a Structure</option>
<?php foreach ($structures as $structure_info): ?>
<option name='<?php echo $structure_info['str_name'] ?>' value='<?php echo $structure_info['str_id'] ?>' data-icon='<?php echo $structure_info['str_imageloc'] ?>' data-html-text='<?php echo $structure_info['str_name'] ?><i>
<?php echo $structure_info['timebuildmins'] ?> minutes<br><?php echo $structure_info['buy_gold'] ?> gold</i>'><?php echo $structure_info['str_name'] ?></option>
<?php endforeach ?>
</select>
<div id="buildSubmit">
<input id ="btnSubmit" class="button" type="submit" value="Submit"/>
</div>
</form>
</div>
Heres my .js file :
$(".button").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php $this->structure_model->insert_build($user_id) ?>", //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});
I am almost sure I know the problem: That structure_model->insert_build($user_id) ?> doesn't work when its outside the view. Though, I dont know the alternative.
I excluded the header file. I confirmed that the .js file is indeed being directed to the correct path.
Could someone please explain the correct way to do this? Thank you!
Did you move your javascript to a .js that is being directly accessed by the browser? I.E: If you view source, so you see the <?php ... ?> in the javascript code?
To me, it sounds as though the PHP is not getting parsed. If this is not the case, then can you please clarify.
If you need to include PHP variables in your javascript, you should use CI to generate the JS page for inclusion. You can even create a View that is purely JS and call it like a normal page.
Otherwise, if you want to seperate the JS from CI, you should reference JS variables instead of PHP. Then in your CI page somewhere, define them with a <script>var jsVar = <?php echo phpvar(); ?></script> tag.
When you move the js file to it's own file, php variables will not be accessible anymore. You can either move the js code back to your view file, or fetch the url through javascript. See below for example.
HTML:
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<input type="hidden" name="url" value="<?php $this->structure_model->insert_build($user_id) ?>" />
<!-- Rest of your code -->
</form>
</div>
Javascript:
$(".button").click(function(e){
var form_url = $(this).closest('form').find('input[name=url]').val();
e.preventDefault();
$.ajax({
type: "POST",
url: form_url, //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});

Calling a PHP function by onclick event

I am trying to call a function by "onclick" event of the button.
When I do that it shows error message.
Can anybody help me out on this so that when I click on the button it should call the function and execute it.
My PHP code is:
<?php
function hello() {
echo "Hello";
}
echo "<input type='button' name='Release' onclick= hello(); value='Click to Release'>";
?>
What is wrong with this code?
The onClick attribute of html tags only takes Javascript but not PHP code. However, you can easily call a PHP function from within the Javascript code by using the JS document.write() function - effectively calling the PHP function by "writing" its call to the browser window: Eg.
onclick="document.write('<?php //call a PHP function here ?>');"
Your example:
<?php
function hello(){
echo "Hello";
}
?>
<input type="button" name="Release" onclick="document.write('<?php hello() ?>');" value="Click to Release">
First quote your JavaScript:
onclick="hello();"
Also you can't call a PHP function from JavaScript;
you need:
<script type="text/javascript">
function hello()
{
alert ("hello");
}
</script>
Executing PHP functions by the onclick event is a cumbersome task and near impossible.
Instead you can redirect to another PHP page.
Say you are currently on a page one.php and you want to fetch some data from this php script process the data and show it in another page i.e. two.php you can do it by writing the following code
<button onclick="window.location.href='two.php'">Click me</button>
onclick event to call a function
<strike> <input type="button" value="NEXT" onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" /> </strike>
it will surely help you
it take a little more time than normal but wait it will work
In Your HTML
<input type="button" name="Release" onclick="hello();" value="Click to Release" />
In Your JavaScript
<script type="text/javascript">
function hello(){
alert('Your message here');
}
</script>
If you need to run PHP in JavaScript You need to use JQuery Ajax Function
<script type="text/javascript">
function hello(){
$.ajax(
{
type: 'post',
url: 'folder/my_php_file.php',
data: '&id=' + $('#id').val() + '&name=' + $('#name').val(),
dataType: 'json',
//alert(data);
success: function(data)
{
//alert(data);
}
});
}
</script>
Now in your my_php_file.php file
<?php
echo 'hello';
?>
Good Luck !!!!!
probably the onclick handler should read onclick='hello();' instead of onclick=hello();
Use this html code it will surely help you
<input type="button" value="NEXT" onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" />
one limitation is that it is taking more time to run so wait for few seconds it will work
Try this
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<?php
function runMyFunction() {
echo 'I just ran a php function';
}
if (isset($_GET['hello'])) {
runMyFunction();
}
?>
Hello there!
<a href='index.php?hello=true'>Run PHP Function</a>
</body>
</html>
You cannot execute PHP functions from JavaScript.
PHP runs on the server before the browser sees it. PHP outputs HTML and JavaScript.
When the browser reads the HTML and JavaScript it executes it.

Categories