I have a JavaScript function (which users on this forum graciously helped me construct) that passes variables via POST to a PHP file with a query for inserting the data to a MySQL database.
The function is invoked "onchange" for a series of 2000+ rows that are spit out from a MySQL database. I use the ID of the row to give each form field a unique name/id, like this:
echo "=<select name='$AdvertisersSQLResult[id]geolocation' id='$AdvertisersSQLResult[id]geolocation' onchange = 'insertAdvertiser()'>";
The JavaScript function looks like this:
function insertAdvertiser() {
var data = $('#<?php echo $AdvertisersSQLResult[id]?>dataid,#<?php echo $AdvertisersSQLResult[id]?>industry,#<?php echo $AdvertisersSQLResult[id]?>geolocation').serialize();
$.post('/database/InsertAdvertiserRelationship2.php', data);
return false;
}
As you can see, I'm attempting to pass PHP variables as part of the form id values. However, this doesn't work, as the function is written to the page once (in the section) without any variables yet populated.
In other words, I'd like to have this JavaScript function utilize whatever PHP variable is being passed to it dynamically. I've looked at other threads about passing a PHP variable to a JavaScript function, but I can't find any reference to how this can be done dynamically, such that the JavaScript function changes to use a different PHP variable each time (if that makes sense).
Thanks for any help...
Well yes because you'd need a seperate insertAdvertiser() method for every advertiser on the system.
A better way to do it would be to do this:
Javascript:
// This line turns your PHP array into a Javascript object
var advertisers = <?php echo json_encode($AdvertiserSQLResult); ?>;
function insertAdvertiser(id) {
$.post('/database/InsertAdvertiserRelationship2.php', advertisers[id]);
}
// Try not to use attributes to bind events, use handlers like this instead.
$(document).ready(function() {
$('select').on('change', function() {
// Reads the advertiser id from the data attribute
insertAdvertiser($(this).data('advertiserid'));
});
});
HTML:
<select data-advertiserid="<?php echo $AdvertiserSQLResult['id']; ?> class="advertiser-select">...</select>
I wrote this as I went along so apologies if I've overlooked something.
See:
jQuery Data
jQuery .on()
You can make a global JavaScript variable and use it in your scripts.
<script type="text/javascript">
myVariable = <?php echo $x; ?>;
</script>
You can store your variables someplace and then access them via JavaScript.
<input type="hidden" class="myVariable" value="<?php echo $x; ?>"
<script type="text/javascript">
var myVar = $('.myVariable').val();
</script>
After you have your data in JavaScript you can do what ever you want to do with it.
Related
I am trying to utilize a javascript variable as the key of a PHP array to echo out. Notice the javascript variable id is want I want to use as the key of the PHP array $allNames[].
Is this possible? Without JSON/AJAX? If so please help.
<script type="text/javascript" language="javascript">
$('*[class^="spec"]').mouseover(function(){
var the_class = $(this).attr("class");
var id = the_class.replace("spec", "");
$('#here').html('<?php echo $allNames[id]; ?>'); // here
});
</script>
Many thanks.
You could use AJAX, but it may be wasteful to do so in this case. Try this:
var allNames = <?php echo json_encode($allNames); ?>;
$('[class^="spec"]').mouseover(function() {
var id = this.className.substr(4); // more efficient than previous code
document.getElementById('here').innerHTML = allNames[id];
});
Alternatively, try refactoring your approach. Instead of having this (example)
<div class="spec1">Hover here</div>
Try this:
<div class="spec" data-hover="<?php echo htmlspecialchars($allNames[1]); ?>">Hover here</div>
Then your script could be as simple as:
$(".spec").mouseover(function() {
document.getElementById('here').innerHTML = this.getAttribute("data-hover");
});
You are doing it wrong. in client-side javascript the php has to already contain all of the variables already.
PHP is rendered before the javascript so you cannot create echo statements by javascript
If you want to dynamically generate HTML from the ajax, this can still be possible as the whole point of many javascript libraries such as jQuery is to dynamically modify elements in the Document Object by using selectors.
Yes you can do it with JSON. Just call the PHP file like this
file.php?id=JAVASCRIPT_ID_HERE
Then in that PHP file, just use $_GET['id'] to grab the ID
This javascript function is being triggered correctly when the variable's value is declared in the php within the same document and then passed to the php, but I'm having trouble doing this when the value is passed from a separate php document.
var session = '<?php echo $t; ?>';
if (session == "login_failed") {
loginFailed();
}
It works when I declare the value in the same document like this:
<?php
$t="login_failed";
?>
But it doesn't work when I declare the value in the 2nd document (login-exec.php) like this:
<?php
$t="login_failed";
echo $t;
?>
EDIT -
This is for the log in form, which is posted with login-exec.php (action="login-exec.php" method="post"). If the query on that page is successful then they are redirected to their account page, but if the query fails I want to trigger this function (instead of what I'm currently doing, which is to redirect them to another page with an error message)
I usually put something like this in my main document
<script>
function get_your_data() {
var yourvalue = "<?php echo $your variable ?>";
return your_data
}
</script>
Then call the function in another document by calling, get_your_data(), it will be available in your external js document.
You can also use classes, and constants.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a php file that generates a variable and I would like the variable to be put into a JavaScript function which is called by onclick on the main page. Is this possible to send from PHP to JavaScript?
You can do the following:
<script type='text/javascript'>
document.body.onclick(function(){
var myVariable = <?php echo(json_encode($myVariable)); ?>;
};
</script>
Just write:
<script>
var my_variable_name = <?php echo(json_encode($php_string)); ?>;
</script>
Now it's available as a JavaScript variable by the name of my_variable_name at any point below the above code.
Your JavaScript would have to be defined within a PHP-parsed file.
For example, in index.php you could place
<?php
$time = time();
?>
<script>
document.write(<?php echo $time; ?>);
</script>
If I understand you correctly, you should be able to do something along the lines of the following:
function clicked() {
var someVariable="<?php echo $phpVariable; ?>";
}
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username and password:
data: 'username='+username+'&password='+password,
In the FILE2.php example, you would retrieve those values like this:
$uname = $_POST['username'];
$pword = $_POST['password'];
Then do your MySQL lookup and return the values thus:
echo 'You are logged in';
This would deliver the message You are logged in to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data); line in the success function would alert that message. Of course, you can echo anything that you like, even large amounts of HTML, such as entire table structures.
Here is another good example to review.
The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.
The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).
The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script> tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?> at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.
In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.
You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.
<script type="text/javascript">
// Do something in JavaScript
var x = <?php echo $calculatedValue; ?>;
// etc..
</script>
Preapring for a Facebook competition while I have spare time, the Publish function with facebook has a once posted javascript function that you can define.
What I am looking to do is call a function to write a value unto a php form which will then be posted and submitting data into a database. I have tested to the extent that I know the idea is sound just calling a basic alert, I am just not sure how to get from calling the function to writing the value into the form.
This value I need to be able to call on in the page that the data is being posted to, to base an "if function" off, basically if "True/Yes" then I need it to process another php script in addition to the data its posting to the database
What I have now is:
<script type="text/javascript">
function isShared()
{
alert("Yes");
}
</script>
<input class="fieldbox" name='shared' type='hidden' value="value of 'display_alert()'"/>
I know it cannot be an alert, but this is pretty much where my current javascript skills leave me stranded.
<script type="text/javascript">
function isShared()
{
document.getElementById('xshared').value = 'Yes';
}
</script>
<input class="fieldbox" id="xshared" name="shared" type="hidden" value="" />
This will add the value Yes To the hidden field once isShared is called.
Are you looking to have the form automatically posted without the user clicking anything but the share button? The only reason I ask is that it sounds like what you are looking for is AJAX, to post data to the database silently without the need of the user to navigate away from their current page.
I'm still not 100% clear on what you're asking, but are you just looking to emit a server-side PHP variable into client-side JavaScript code? Something like this?:
<?php
// some code, etc.
$myVariable = "foo"; // some value
// more code, etc.
?>
<script type="text/javascript">
var myVariable = '<?php echo $myVariable; ?>';
// more JavaScript code, etc.
</script>
This would emit to the page as:
<script type="text/javascript">
var myVariable = 'foo';
// more JavaScript code, etc.
</script>
Basically anywhere that you need the literal value from the PHP variable, you'd write:
<?php echo $myVariable; ?>
I am not clear how exactly you are aiming to post the form data but you can set the input value using jquery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
$('#input1').val($('#input1').val() + 'more text');
<input id="input1" class="fieldbox" name='shared' type='hidden' value=""/>
I have a function:
$("button.btn-info").click(function() {
var id=this.id;
});
So, and I have to get item from PHP array $records with 'id' number. I need to insert this item into 'alert' function, but I don't know how I can pass variable from JS to PHP.
Please, tell me.
Use for example json_encode($records) and output it in a <script> tag in your html file like this:
<script type="text/javascript">
var records = <?php echo json_encode($records); ?>;
</script>
this should usually stand before your other js code that depends on the records-var.
or else you could use ajax (jQuery.get) if you want to load this var dynamically.
Not entirely sure I understand your question. It appears you just wish to write your PHP variable out to the javascript:
$("button.btn-info").click(function() {
var id=<?php echo $records->id?>;
});
Just remember that the Web page that hosts the JavaScript is static. If you want it to interact with PHP, you need to utilize AJAX or something else more advanced.