jquery + php - Call Function From Another Javascript Wrapper - javascript

How could I call function in different jQuery wrapper like this:
<?php
if($trigger != ""){
?>
<script type="text/javascript">
jQuery(document).ready(function($){
var delay = 5000;
setTimeout(rmv, delay); // call the function here
});
</script>
<?php
}
if($triggered != ""){
?>
<script type="text/javascript">
jQuery(document).ready(function($){
function rmv(){ // function to be called
$(".adt_front_wrapper<?php echo $id; ?>").remove();
}
});
</script>
<?php
}
?>
I am trying to call a function which should be separated from the caller like the rmv function in the example code above. How could it be done?

You would need to put that function into a higher (shared) scope. For this example, you could use the window object itself.
window.rmv = function() {
$(".adt_front_wrapper<?php echo $id; ?>").remove();
};
In order to make that work, the declaration and definition of rmv needs to happen beforehand of course.

Related

Uncaught ReferenceError not defined at HTMLAnchorElement.onclick

I am getting error in console:
Uncaught ReferenceError: check is not defined
at HTMLAnchorElement.onclick
<a onclick="check();">Payment</a>
In JS I am getting error due to this line, whats wrong in this ?
<script type="text/javascript">
function check() {
{
var label<?php echo $k; ?> = "<?php echo $View; ?>";
}
}
</script>
I just noticed that you have extra set of {} remove the duplicate {}, so your code looks like:
<script type="text/javascript">
function check() {
var label<?php echo $k; ?> = "<?php echo $View; ?>";
}
If the problem is still persistent, would be worth checking if you have defined the function before or after the onclick call, because sometimes the js might not have fully loaded up (should not be the case, but is worth the check).
Hope this helps!
function check() {
var label<?php echo $k; ?> = "<?php echo $View; ?>";
}
Remove double time used {} brackets inside Check() function.
And Check again
You can debug and find solution anyways. But recommended way of attaching an event to a DOM element is using addEventListener
That way you'll not be worried about to declare function before or after the HTML element.
document.querySelector('.foo').addEventListener('click', function(ev){
/*
* ev.preventDefault();
* as we are doing someething "unusual", preventing
* default behaviour might be right option
*/
this.innerHTML = 'Checked';
});
<a class="foo">Foo</a>

PHP: echo as condition of if statament?

I need to put echo as condition of if statement. So, for example:
<html>
...
...
<body>
<form onsubmit"<?php $c=false; if(echo "<script>example();</script>";){ $c=true; } echo "\""; if($c){ echo "action=\"./\"";} method="post">
...
</form>
...
...
<script>
function example()
{
alert("This is only an example");
if(..) return true;
return false;
}
</script>
</body>
</html>
So I need to create a function in JavaScript (this top is only an example, but, in realty, it is more complicated) and call it in the if statement.
Update
The code should be execute "action" of the form only if the Javascript function is true.
PHP runs in the server. JavaScript runs in the client. So php can't use a js variable or its function to server side action. What u can do is , u can call JS function from PHP like
echo "<script> myFunction() </script>";
But in the same same case, u can use php values for JS actions,
eg
<script>
var x = <?php echo $myVar ?>
if(x == true){
alert("yahooo");
}
</script>

Multiple Delete using JQuery Ajax and Code Igniter

I am currently working on a program that uses php jquery and bootstrap, I want to delete multiple data using checkbox. I search and found out that it must use AJAX to passing the paramater from view to controller. The Jquery work find and can get the value from checkbox. But when I use Ajax, the button not working. Nothing change. Please help me to find the problem on my code. Thank you
My Controller
public function hapusbeberapa()
{
$this->model_security->getsecurity();
$this->load->model('model_barang');
$arr = $this->input->post('data');
//$arrcode= json_encode($arr);
foreach($arr as $id)
{
$query = $this->model_barang->getID($id);
if($query->num_rows()>0)
{
$this->model_barang->getdelete($id);
//$this->session->set_flashdata('info',"Data Berhasil Dihapus");
}
}
}
My Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_barang extends CI_model {
public function getdelete($key)
{
$this->db->where('IDBarang',$key);
$this->db->delete('tBarang');
}
public function getID($key)
{
$this->db->where('IDBarang',$key);
$query = $this->db->get('tbarang');
return $query;
}
}
My View
<script src="<?php echo base_url();?>http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btnhapus").click(function(){
var favorite = [];
$.each($("input[name='checkboxlist']:checked"), function(){
favorite.push($(this).val());
});
$.post("<?php echo site_url(barang/hapusbeberapa) ?>"+actMult, {data:favorite}););
});
});
</script>
</script>
use your script as:
<script type="text/javascript">
$(document).ready(function() {
$("#btnhapus").click(function(){
var favorite = [];
$.each($("input[name=checkboxlist]:checked"), function(){
favorite.push($(this).val());
});
$.post("<?php echo site_url(/barang/hapusbeberapa) ?>", {data:favorite}, function(returnData){
console.log(returnData);
});
});
});
</script>
it will work for sure,
the result will be same as you echo in controller's function, and check console log for check result, you can also check it by using alert(returnData) instead of console.log(returnData).
hope it helps
Try something like that:
var favorite = [];
$.each($("input[name='checkboxlist']:checked"), function(){
favorite.push($(this).val());
});
favorite = favorite.join();
$.post
...
In Controller
$arr = $this->input->post('data');
$arr = explode(',', $arr);

How to trigger js function inside php?

if (!$errors) {
//Call Js function without any events
}
I want to call js function once inside if came,How to call js function inside if condition?Is it possible to call js fucntion without any events inside php tag?
with jquery
if (!$errors) {
echo "<script type='text/javascript'>
$(document).ready(function(){
myfunction();
});
</script>";
}
without jquery and wait unlit whole page is loaded
if (!$errors) {
echo "<script type='text/javascript'>
window.onload = function() {
myfunction();
};
</script>";
}
and without Onload
if (!$errors) {
echo "<script type='text/javascript'>myfunction();</script>";
}
You can also use this way :
<?php
// php code
if(condition){
?>
<script type="text/javascript">
jsFunction();
</script>
<?php
}
// php code
?>
You can also use jquery:
if (!$errors) {
echo "<script type='text/javascript'>
$(document).ready(function(){
myfunction();
});
</script>";
}
You could just make an echo and call it between two script tags.
Like :
if (!$errors) {
echo "<script> myfunction(); </script>";
}

Why I cannot send php variable to javascript variable using jQuery?

I have javascript function using javascript variable from php variable using jQuery. The code is shown below:
jQuery:
$(document).ready(function(){
var v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>;
});
javascript function
function abc(){
alert(v1);
}
I cannot print out the value of v1, but when I do not use jquery to send php variable to javascript variable, I use the below code after $v1 in php
<script type="text/javascript">
var v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>;
</script>
And the function can print out value of v1.
But, I want to see which variables I have already used and see them at the top instead of at the bottom. So, I decide to use jquery but it fails. Where does it go wrong?
the second way which works for me is shown below:
<!DOCTYPE html>
<html>
<head>
<script>
function abc(){
alert(v1);
}
</script>
</head>
<body>
<?php
$sql = "SELECT r_ID,r_cname,address FROM rest ORDER BY count2+count3 DESC";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_array()){
array_push($name,$row["r_cname"]);
}
}
?>
<script>
var v1 = <?php echo json_encode($name); ?>;
</script>
</body>
</html>
Why there are no encapsulation problems?
Your alert(v1) needs to be inside the same function the var v1 = ... is in. And the JSON needs to be valid to print out a valid object.
A PHP printed variable often need not to be in jQuery. It almost certainly not need to be inside a jQuery function, trust me, because it is often just a piece of data.
I always use this method/practice:
<?php
//My businesses
?>
<!DOCTYPE html>
<html>
...
<head>
<script>
//By the way, HTML5 don't require you to state the type of script, it is defaulted to JavaScript.
var x = <?php echo json_encode($x, JSON_UNESCAPED_UNICODE);?>
</script>
<script>
//Rest of my code
$(function(){
//My jQuery here
})
</script>
</head>
<body>
...
</body>
</html>
Why declaring the variable inside jQuery "doesn't" work
It does, but outside the scope of $(function(){}), no one can access variables defined inside. It is a basic mechanism of JS. On the other hand, the function(){} inside $() is an argument, that is the second reason it doesn't work getting the value outside.
Example:
var a = 3;
function(){
var b = 4;
a; //<-- 3
};
b; //<-- undefined
Why the second script worked
Let's assume your code looks like this:
...
<script>
var v1 = <?php echo json_encode($v1, JSON_UNESCAPED_UNICODE);?>
</script>
...
<script>
$(function(){
v1; //There is a value
})
</script>
...
Because your new v1 variable is defined just under <script>, it is a global variable. A global variable can be accessed anywhere on the webpage.
In contrast, a local variable cannot be accessed outside the scope it is in. Look at this tree diagram:
window
|- v1
`- function x
|- v2
`- function y
`- v3
Basically, a variable can only be accessed by its children and never its parents. So:
v1 can be accessed inside inside and outside of function x and function y but v2 can only be accessed inside of function x and function y and v3 can only be accessed inside function y
Here is a table of what variables can be accessed where:
globally | function x | function y
------------|------------|-----------
v1 ✓ | ✓ | ✓
------------|------------------------
v2 | ✓ | ✓
------------|------------------------
v3 | | ✓
Final answer
You just need to do this: <script>var v1 = <?php echo json_encode($v1);?></script> before you use the variable on your webpage.
Your issue lays in timing and/or scope.
This code will run after the page is done loading and all the variables declared in it are encapsulated and exist only within it:
$(document).ready(function(){...})
Try this:
// Declaring variable in global scope.
var v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>;
$(document).ready(function(){
// Open console to view result
console.log(v1);
});
Its working, follow the sequence
<?php
$v1 = ["a","b","c"];
?>
<script type="text/javascript">
v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>;
abc();
function abc(){
alert(v1);
}
</script>
------------------- Updated code if js is before php code ----------------------
<script type="text/javascript">
$( document ).ready(function() {
v1 = $("#v1").val();
abc();
function abc(){
alert(v1);
}
});
</script>
<?php
$v1 = ["a"=>"aa","b"=>"bb","c"=>"cc"];
$v1_json = json_encode($v1,JSON_NUMERIC_CHECK);
?>
<input type="hidden" value='<?php echo $v1_json; ?>' id="v1">

Categories