Jump to content

Recommended Posts

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:

 

<?php


if(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();
    }    
}

?>

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>
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.