Roopavathy Posted October 15, 2015 Share Posted October 15, 2015 Hello there I want to assign javascript variable value to a php variable so that I can use that php variable in mysql query.I dont know how to do it. I am receiving a value from a prompt box(using javascript) and i want that value to be entered into the database. Kindly help me. Here is my code: <?phpif(isset($_GET['comp_no'])){ $complaint_no=$_GET['comp_no']; ?> <script> function myFunction() { var person = prompt("Enter your name","John Smith"); } </script> <?php if(isset($_POST['prog'])) { $prog_name=$_POST['prog']; } $query2="update sys_complaints set checked='yes', programmer='$prog_name' where sno='$complaint_no'"; $run_query2=mysql_query($query2); if($run_query2) { echo "<script>alert('Complaint is attended!');</script>"; header("location:view_complaints.php"); } else { echo "Query failed!".mysql_error(); } }?> Quote Link to comment https://forums.phpfreaks.com/topic/298610-store-javascript-variable-value-to-a-php-variable/ Share on other sites More sharing options...
Ch0cu3r Posted October 15, 2015 Share Posted October 15, 2015 You cant mix PHP and Javascript code together. PHP and Javascript are two completely different languages, they both run a different times. PHP runs on the server. JavaScript runs in the browser. The only way to send the value returned by the prompt box to PHP would be to to redirect the user to your php script and have value pass a querystring value. Example // get value form javascript prompt var person = prompt('Enter your name', 'John Smith'); // submit the value to php by redirecting the user to submit.php // and passing the name as a querystring value document.location = 'submit.php?name=' + person; Your PHP code for inserting the name into the database goes in submit.php. The variable $_GET['name'] will contain the value from the prompt box. If you dont want the user to be redirected/page to be refreshed then you can use ajax. (Example code using Jquery's ajax api) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script> var person = prompt('Enter your name', 'John Smith'); $.ajax({ url: "submit.php", data: { person: person } }) .done(function( msg ) { alert( "Name has been submitted"); }); </script> Quote Link to comment https://forums.phpfreaks.com/topic/298610-store-javascript-variable-value-to-a-php-variable/#findComment-1523327 Share on other sites More sharing options...
Roopavathy Posted October 16, 2015 Author Share Posted October 16, 2015 Thank you very much for your kind reply.Very nice explanation.Thanks a lot. :happy-04: Quote Link to comment https://forums.phpfreaks.com/topic/298610-store-javascript-variable-value-to-a-php-variable/#findComment-1523432 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.