How to properly call a PHP function? - javascript

I currently have a PHP function which I need to call from a different file to populate a Javascript variable. I can populate the Javascript variable just fine. However when calling the PHP function I get an error message stating that
Use of undefined constant getEstGrid - assumed 'getEstGrid' in
phpcom/db/estimatesCom.php</b> on line 29.
Here is my include file which has the function:
<?php include 'phpcom/db/estimatesCom.php';?>
Here is where I'm calling the function:
<?php echo getEstGrid($resultsE); ?>
Function code:
function getEstGrid($resultsE){//<--This is the variable passed to the function
if ($resultsE->num_rows > 0) { //<--- Check to see if the variable is greater than zero
$rows = array(); //<--- Create an empty array calls "rows"
while ($r = $resultsE->fetch_assoc()){//<--- While the database records are being returned create a variable called "r" and assign DB record.
$rows[] = $r; //<-- assign each DB record row to the array.
}
$data = array('Estimates' => $rows);//<--- Create a variable an assing the array to it.
}
//header("Content-Type: application/json;charset=utf-8");
echo json_encode($data, true);//<--- Endode the "data" variable to a JSON format.
return getEstGrid;//<--- Return the created fucntion.
}
If anyone can help with this I would really appreciate it.

I would change this:
echo json_encode($data, true);//<--- Endode the "data" variable to a JSON format.
return getEstGrid;//<--- Return the created fucntion.
By this:
return json_encode($data, true);
This way, the function just returns the data, and you can choose whether echo it o do any other thing with it out of the box.

Just remove this return statement from your function:
return getEstGrid;//<--- Return the created fucntion.
Why have you used that? Not needed.
Also, if you are using echo in your function you don't need to use echo while calling your function to print the output.

You dont have to return the function in order to use it in another file.
Instead, just return the value you need from the function:
return json_encode(...
When you try to return "getEstGrid", php is looking for a constant with that name, which doesnt exist.

Related

Cannot modify the value of a node in a onclick called function

I set the arguments of my function called on onclick event with PHP and I also pass "this" ( the button ) as an argument so that in my function I access the closest <td> node and change its value.
However, I can't change the value of the node.
I get
is not a function
error each time I try to modify it.
PHP code :
echo "<tr><td>";
echo "<button onclick='updateValue($index,$byte,this)'></button>";
echo "<td>".$byte."</td>";
echo "<td>".$comment."</td>";
echo "</tr>";
And my JS function there :
function updateValue(index,byte,button){
$.ajax({
url : 'commentrefresh.php',
type : 'GET',
data : 'bytenumber=' + byte +"&byte_id=" +index,
datatype : 'text',
success : function(data){
button.closest('tr').lastChild.val(data)
}
})
}
Check this fiddler and the way I get the lastChild td node.
https://jsfiddle.net/aqmtjs8k/
$(button).closest('tr').find('td:last-child')
And if you want to write inside the last td you should use .html() and not .val()
.val() is only for inputs
Correct way: $(button).closest('tr').find('td:last-child').html(data)
As the error message says, closest isn't a function on DOM nodes.
You've tagged this question jquery, and jQuery objects do have a closest method, but you haven't wrapped the DOM node in a jQuery object.

Any script to ignore undefined variable?

In my template view file have code below:
<script>
// When the document is ready
$(function() {
var treedata = <?php (($treedata=="" ? "":$treedata)); ?>;
$('#treeview').treeview({data: treedata});
});
</script>
but I am not using this treeview in every page, so whenever no treedata being send the output will be like this
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: treedata
Filename: views/admin.php
Line Number: 355
How can I leave it blank when no treedata being send by controller?
You could use this approach.
var treedata = <?php echo isset($treedata) ? '"'.$treedata.'"' : "''" ; ?>;
echo to display the result.
isset() to determine if variable exists
wrap the result to avoid ReferenceError: a is not defined in javascript.
You've multiple options here. My preferred stance is generally to engineer your code so that you never have undefined variables. In the absence of that code structure, you might ensure it's set:
$treedata = isset( $treedata ) ? $treedata : "";
Or, you might consider disabling the NOTICE warning altogether. How you do this is situation dependent, but you might try something like:
ini_set('error_reporting', E_ALL & ~E_NOTICE);
Additionally, do you also have Javascript errors when $treenode is empty? I believe when $treenode is empty, your Javascript line turns into:
var treedata = ;
Which is an error. Suggest you wrap the quotes in PHP instead:
var treedata = <?php (($treedata=="" ? '""':$treedata)); ?>;
You should use isset() function for checking variable existance.
So, you should replace:
$treedata==""
To
isset($treedata)
isset() — Determine if a variable is set and is not NULL

Undefined JS alert

I've got an a-tag which reads as this: (and there are number of a-tags being dynamically populated as this stays inside a PHP loop.)
echo "<a onclick='trygettheid();' class='mainList' id='main' href='index.php?idd=".$reK['catid']."'><div class='AS1'>".$reK['catdescriptor']."</div></a>";
and the JS function looks like below.
function trygettheid()
{
var myvariable = $(this).attr('id');
alert(myvariable);
}
The issue is when a click is triggered, the alert says 'undefined' instead of the desired output of 'main'
Am I missing anything here?
Inside the function this does not refer to the clicked element it may be window object. To fix it pass the reference as an argument to the function. Although there is no need to use jQuery since id can be get from element id property.
PHP :
echo "<a onclick='trygettheid(this);' class='mainList' id='main' href='index.php?idd=".$reK['catid']."'><div class='AS1'>".$reK['catdescriptor']."</div></a>";
// ------^------
JS :
function trygettheid(ele){
// -----^-----
var myvariable = ele.id;
// ---^--^----
alert(myvariable);
}

Why doesn't this function modify the global version of the array?

I have defined a variable in what I think is global scope. I want to modify the same variable inside a function that lives in a class, then use it later to export as json data.
The function is called by the xataface api, so I'm not sure I can mess with the function signature to do something like passing by reference. I've thought I might access the instance of this action class in the javascript embedded php, but I don't know how to ask the api for it, nor am I confident of its lifetime. It seems like a global variable may be the way to go. In any case, I want to know:
Why is not the global instance of $dataset1 the one being modified inside the function?
Why doesn't the call to array_push put anything on either array?
<?php
//non-dynamic data delcared in global scope. This is picked up later
//in a php block embedded into javascript
$dataset1 = array(array("label"=>"c120","data"=>"1"),
array("label"=>"c150","data"=>"10"),
array("label"=>"camp","data"=>"7"));
class actions_time_in_type
{
function handle(&$params)
{
$this->app =& Dataface_Application::getInstance();
//The Query
$result = mysql_query("SELECT typeDes, total
FROM myTable", $this->app->db());
//reserch leads me to believe that this *should* make all subsequent
//references to $dataset1 use the global instance
global $dataset1;
//experimenting with appending more non-dynamic data
//for some reason, this syntax does not seem to touch $dataset1
array_push($dataset1, array("label"=>"dv20","data"=>"1"));
//This syntax is working, but $dataset1 is not the same as the global
//$dataset1. Prepending "global" here seems to crash the script
$dataset1[] = array("label"=>"pa18","data"=>"5");
while($row = mysql_fetch_assoc($result))
{
//append data to the array, again, this is not hitting
//the global instance of $dataset1
$dataset1[] = array("label"=>$row['typedes'],"data"=>$row['total']);
}
mysql_free_result($result); //Frees the result after finished using it
//diagnostic dump to see what we've got
//This shows that we've constructed the dynamic data set, but it
//seems to be scoped only to this function and does not make it into
//javascript.
var_dump($dataset1);
}
}
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
<script type="text/javascript">
$(function () {
//This is getting only what was done original init of $dataset1, nothing that
//happened in the function made a difference
var dataset1 = <?php echo json_encode($dataset1); ?>;
});
</script>
It appears this is indeed a problem with execution order. Since the manipulation of the data happens within a class definition which in turn is called by the api, there appears to be no assurance that the global definition of the data will be in scope when it is time to manipulate the data, or that it will have been manipulated when the data is re-used further down.
For the interested reader, I was able to get the api developer to demonstrate the proper way of integrating javascript with the api calling the in-class function:
https://groups.google.com/forum/#!topic/xataface/l6qBzxF1vrc

Pass value from php to javascript

Hello Im trying to pass value stored in php to javascript code.
I try to pass the value in $_SESSION[user]
If I have this script in my header:
<script>
var user = ? //How to pass the value?
</script>
In my buttons I do something like this:
onclick="foo('<?php session_start(); echo $_SESSION[user];?>')
But how do I pass it without the user click?
Thanks for helping
EDIT
My JS function located in other file and I reference them by this code in my header:
<script src="class_functions"></script>
How do I pass the same parameter to the other file?
Just echo the PHP value out like you would any content:
<script>
var user = '<?php echo $_SESSION[user]; ?>';
</script>
JavaScript is just client-side code like HTML is.
If you're PHP script is rendering the page, I would go with the script tag approach.
<head>
<script type="text/javascript">
var user = '<?php echo $_SESSION["user"]; ?>';
</script>
</head>
<body>
</body>
Now that you have added an additional factor to your question, it is a little bit more interesting. If you need to set a variable when the functions that use this variable are located in a different file, then you need to decide the scope of the variable you are passing. There are several options; I will just list two:
Global scope. That is, the variable will be "known" to the other functions because of where it it located. You want to be careful of this, but if that's your approach you can use any of the answers given, e.g.
<script>
var x = '<?= $_SESSION["user"];>';
</script>
Local scope. Now you will need to include a function in class_functions that sets the variable. You might end up with something like
<script>
set_user('<?= $_SESSION["user"];>');
</script>
Where the set_user() function is defined in your other file, and ensures that the variable is available to the other functions with the correct scope.
I would prefer using method 2 - it is much cleaner.
I think this is better:
<script>
var user = '<?php echo htmlentities($_SESSION["user"]); ?>';
</script>
Because if there are quotes $_SESSION['user'], you will get an error.
For example if you have:
$_SESSION['user'] = "something with 'quotes'";
the js would like so:
var user = 'something with 'quotes'';
Which is incorrect.
You Can use Jquery ,if you want it to happen automatically.
just Use the following code inside your tags
$(document).ready(function()
{
var user= <? echo $_SESSION['user']?>;
//Code Goes here......
});
Hope that solves Your Problem
Note:This can be one of the many possible solutions

Categories