Reputation: 101
I am trying to store a value of an argument of a function to a variable.
var store;
function load_event(page_id){
store = page_id;
alert(page_id); //Works fine
}
alert(store); //Undefined???
The page_id is the argument got from another PHP file (so that PHP file is calling the function).
I do not understand why this store variable returns undefined?
PHP CODE!
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php
$post = $wp_query -> post;
$post_id = $post->ID;
echo $post_id; //Get the post_id of the current post.
?>
<script>
loadEvent("<?php echo json_encode($post_id); ?>");
</script>
</div><!-- #content -->
</div><!-- #primary -->
Upvotes: 1
Views: 114
Reputation: 174
If you call load_event()
before alert(store)
. The reason is that you are using alert(store)
before the function load_event()
has been called. At this point, the value in store
is undefined. That is because the load_event()
function is not executed until you call it so alert(store)
is executed first and which evaluates store
to undefined
and then load_event()
is executed that sets the value of store
to page_id
. Move the load_event()
before alert(store)
will solve the problem.
Upvotes: 2
Reputation: 889
You need to call the function to execute the function
var store;
function load_event(page_id){
store = page_id;
alert(page_id); //Works fine
}
load_event(2);
alert(store); //2
Upvotes: 2