How to take variable script and insert into a php database?

Asked

Viewed 62 times

0

I have a select field according to the code below:

<select id="teste">
    <option>oie</option>
    <option>tchau</option>

I have a knob to run an Insert in the database through the onclick function call:

<input type="button" value="ok" onclick="teste()">

And a Java Script Function to get the select value :

<script >

  jQuery("#teste").change(function(){
    var setor = jQuery(this).val();// pega o valor escolhido no select 
    var oi = setor;
    alert(oi);

  })

  function teste(){
    <?php
      $serverName = "servidor"; 
      $connectioninfo = array( "Database"=>"banco", "UID"=>"usuario", "PWD"=>"senha");
      $conn = sqlsrv_connect($serverName, $connectioninfo);
      $conteudo = "<script>document.write(setor)</script>";
      $oi =  " $conteudo";
      $query ="insert into teste(setor) values('$oi')";
      $output=sqlsrv_query($conn,$query) or die(print_r(sqlsrv_errors()));       
   ?>
}

</script>

However, the value entered in the database is thus : "Document.write(sector)" What is wrong?

The goal is not to use form action I will use ajax to make my query in real time but first I wanted to understand how to play the variable javascript within value in my PHP Insert

  • @Andersoncarloswoss is not duplicate, I know how to make the php connection and insert in the database however the information that is going there (javascript variable) is going incorrectly, in the literal form "<script>nomedavariavel</script>"

  • 1

    Exactly. The way you did it doesn’t make any sense and it’s an indication that you don’t master the basics to do the operation. I addressed everyone (or almost everyone) in my other answer, so I flagged it as duplicate. If you read my answer, you will see that it has 3 parts. You apparently know part 3, but I strongly recommend reading and studying the concepts of parts 1 and 2.

  • I believe you misunderstood my question @Andersoncarloswoss...

  • 1

    I understand perfectly. You’re trying to spin a script PHP inside a JS function. This makes no sense, because PHP runs on the server side, while JS runs on the client side. The only communication between them is an HTTP message. I believe that these are the missing concepts to solve the problem and they are all described in the other answer. Therefore I think it is duplicated.

  • With your edition saying that you will use AJAX changes the situation a little. The AJAX request will generate the HTTP message you need to communicate between JS and PHP. Try to do this directly now, because the code you have today, which you posted in the question, does not make sense for the reasons described in the previous comment. I already say that on the site there are also numerous questions about AJAX and PHP, so it will probably be duplicated some other.

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.