How to get value from PHP array in jQuery? - php
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.
Related
Is it possible to use a javascript variable as a PHP array key?
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
Send PHP variable to JavaScript function [duplicate]
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>
pass variable from input box to php
Hi all i know this question has been posted but being a total noob i couldnt get what answers meant. Please help. I want to pass inputbox value dynamically to a php variable . i am using javascript here please suggest if there's another way without using form submission , _GET or _POST. i want it done dynamically without any submission. function showHint(str) { document.getElementById('TK').innerHTML = str; var str = str } </script> <html> <head>Inputbox</head> <title>TEST PAGE </TITLE> <body> <input type='text' id='TK' name='TK' onkeyup='showHint(this.value)'/> <?php $str = var str ; echo "<a href = 'newpage.php?S=$str'/>" ; ?> </body> </html>
No. You can't. PHP is NOT a dynamic language, and it does NOT run client side. PHP runs once, and only once, and that's when the page is loaded. It runs its script and it stops. What you can do is get javascript to do an AJAX call. AJAX is basically a way of passing information to another page and getting the data, all in JavaScript. Do some research on it, but in short, you can't make PHP run once it's already been run
<script type="text/javascript" > function process(){ var field1 = 'whatever'; var field2 = 'more whatever'; $.post("go.php",{field:field1,bext_field:field2},function(result){ alert(result); }); }; </script> This will alert out whatever you ECHO from GO.PHP. You will also need a handler like: onClick="process();" on a div, button, image, just about anything you want to "initiate" your post
I would imagine the other answers you found probably would have said the following: PHP executes before the user has a chance to see the page. JS let you control what happens after. Therefore, your problem is that you are trying to use PHP to do something it simply cannot. Use those points to help guide your decisions when developing your applications. In this case, if you're trying to build a link based on what a user types in a box, your solution to the problem isn't PHP at all (the page is already loaded, you're too late!) -- your solution is JS. Think about it like this: /* assumes you already have an <a> on the page. if not, you'll have to create a new <a> element dynamically. (google "mdn createElement" for help) */ function showHint (str) { document.getElementById('TK').innerHTML = str; var link = document.getElementById('your-a-link'); link.setAttribute('href', 'newpage.php?S=' + str); }
Pass a PHP variable dynamically to an AJAX JavaScript function
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.
Passing javascript variable into php code without using GET parameters?
is there any way to get js variable in php, i try something funny like this: <script> var x = "random text"; alert("aaa<?php echo md5(;?>"+x+"<?php); ?>"); </script> Of course it gives me error. Parse error: parse error, expecting `')'' in X:XXX\index.php on line XXX If there is a way without refreshing the page or using GET parameters, please let me know. Thanks EDIT: What I am trying to do is: hash(md5 inside php) the javascript variable.
PHP runs at the server, JavaScript runs at the client (browser). The only way you can pass a variable from JavaScript to PHP is sending it via an AJAX request. There are several MD5 solutions out there for JavaScript, but it's not the same if you want the variable hashed before it reaches the user.
You can't do it like that because PHP builds the page before javascript is initialized. You'll have to do an AJAX request. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> var x = "random text" $.post('md5.php', {md5:x}, function(data) { alert(data); }); </script> <?php echo md5($_POST['md5']); ?> Or.. function md5(e){function k(h,i){var g=[h&2147483648,i&2147483648,h&1073741824,i&1073741824,(h&1073741823)+(i&1073741823)];if(g[2]&g[3])return g[4]^2147483648^g[0]^g[1];return g[2]|g[3]?g[4]&1073741824?g[4]^3221225472^g[0]^g[1]:g[4]^1073741824^g[0]^g[1]:g[4]^g[0]^g[1]}function n(h,i,g,j,s,m,o){h=k(h,k(k(i&g|~i&j,s),o));return k(h<<m|h>>>32-m,i)}function p(h,i,g,j,s,m,o){h=k(h,k(k(i&j|g&~j,s),o));return k(h<<m|h>>>32-m,i)}function q(h,i,g,j,s,m,o){h=k(h,k(k(i^g^j,s),o));return k(h<<m|h>>>32-m,i)}function r(h,i,g,j,s,m,o){h=k(h,k(k(g^(i|~j),s),o));return k(h<<m|h>>>32-m,i)}function t(h){var i="",g,j;for(j=0;j<=3;j++){g="0"+(h>>>j*8&255).toString(16);i+=g.substr(g.length-2,2)}return i}var f=[],v,w,x,y,a,b,c,d;e=function(h){var i=h.length,g=0,j=0,s="",m;for(m=0;m<i;m++){var o=h.charCodeAt(m),u=null;if(o<128)j++;else u=o>127&&o<2048?String.fromCharCode(o>>6|192,o&63|128):String.fromCharCode(o>>12|224,o>>6&63|128,o&63|128);if(u!==null){if(j>g)s+=h.substring(g,j);s+=u;g=j=m+1}}if(j>g)s+=h.substring(g,h.length);return s}(e);f=function(h){var i=h.length,g=i+8;g=((g-g%64)/64+1)*16;var j=Array(g-1);for(l=0;l<i;l++)j[(l-l%4)/4]|=h.charCodeAt(l)<<l%4*8;j[(l-l%4)/4]|=128<<l%4*8;j[g-2]=i<<3;j[g-1]=i>>>29;return j}(e);d=271733878;a=1732584193;b=4023233417;c=2562383102;for(e=0;e<f.length;e+=16){v=a;w=b;x=c;y=d;a=n(a,b,c,d,f[e+0],7,3614090360);d=n(d,a,b,c,f[e+1],12,3905402710);c=n(c,d,a,b,f[e+2],17,606105819);b=n(b,c,d,a,f[e+3],22,3250441966);a=n(a,b,c,d,f[e+4],7,4118548399);d=n(d,a,b,c,f[e+5],12,1200080426);c=n(c,d,a,b,f[e+6],17,2821735955);b=n(b,c,d,a,f[e+7],22,4249261313);a=n(a,b,c,d,f[e+8],7,1770035416);d=n(d,a,b,c,f[e+9],12,2336552879);c=n(c,d,a,b,f[e+10],17,4294925233);b=n(b,c,d,a,f[e+11],22,2304563134);a=n(a,b,c,d,f[e+12],7,1804603682);d=n(d,a,b,c,f[e+13],12,4254626195);c=n(c,d,a,b,f[e+14],17,2792965006);b=n(b,c,d,a,f[e+15],22,1236535329);a=p(a,b,c,d,f[e+1],5,4129170786);d=p(d,a,b,c,f[e+6],9,3225465664);c=p(c,d,a,b,f[e+11],14,643717713);b=p(b,c,d,a,f[e+0],20,3921069994);a=p(a,b,c,d,f[e+5],5,3593408605);d=p(d,a,b,c,f[e+10],9,38016083);c=p(c,d,a,b,f[e+15],14,3634488961);b=p(b,c,d,a,f[e+4],20,3889429448);a=p(a,b,c,d,f[e+9],5,568446438);d=p(d,a,b,c,f[e+14],9,3275163606);c=p(c,d,a,b,f[e+3],14,4107603335);b=p(b,c,d,a,f[e+8],20,1163531501);a=p(a,b,c,d,f[e+13],5,2850285829);d=p(d,a,b,c,f[e+2],9,4243563512);c=p(c,d,a,b,f[e+7],14,1735328473);b=p(b,c,d,a,f[e+12],20,2368359562);a=q(a,b,c,d,f[e+5],4,4294588738);d=q(d,a,b,c,f[e+8],11,2272392833);c=q(c,d,a,b,f[e+11],16,1839030562);b=q(b,c,d,a,f[e+14],23,4259657740);a=q(a,b,c,d,f[e+1],4,2763975236);d=q(d,a,b,c,f[e+4],11,1272893353);c=q(c,d,a,b,f[e+7],16,4139469664);b=q(b,c,d,a,f[e+10],23,3200236656);a=q(a,b,c,d,f[e+13],4,681279174);d=q(d,a,b,c,f[e+0],11,3936430074);c=q(c,d,a,b,f[e+3],16,3572445317);b=q(b,c,d,a,f[e+6],23,76029189);a=q(a,b,c,d,f[e+9],4,3654602809);d=q(d,a,b,c,f[e+12],11,3873151461);c=q(c,d,a,b,f[e+15],16,530742520);b=q(b,c,d,a,f[e+2],23,3299628645);a=r(a,b,c,d,f[e+0],6,4096336452);d=r(d,a,b,c,f[e+7],10,1126891415);c=r(c,d,a,b,f[e+14],15,2878612391);b=r(b,c,d,a,f[e+5],21,4237533241);a=r(a,b,c,d,f[e+12],6,1700485571);d=r(d,a,b,c,f[e+3],10,2399980690);c=r(c,d,a,b,f[e+10],15,4293915773);b=r(b,c,d,a,f[e+1],21,2240044497);a=r(a,b,c,d,f[e+8],6,1873313359);d=r(d,a,b,c,f[e+15],10,4264355552);c=r(c,d,a,b,f[e+6],15,2734768916);b=r(b,c,d,a,f[e+13],21,1309151649);a=r(a,b,c,d,f[e+4],6,4149444226);d=r(d,a,b,c,f[e+11],10,3174756917);c=r(c,d,a,b,f[e+2],15,718787259);b=r(b,c,d,a,f[e+9],21,3951481745);a=k(a,v);b=k(b,w);c=k(c,x);d=k(d,y)}return(t(a)+t(b)+t(c)+t(d)).toLowerCase()}; var x = "random text"; alert(md5(x));
You could use an ajax call to your server and have a webservice on the php side returning the information you need. Besides that? I don't think there is a way expect for refreshing.