Emmanuel Paz
Emmanuel Paz

Reputation: 1

How to convert javascript variable into php variable?

Im new in programming and Im trying to make a program that would register a selected space in my database. I want to convert js variable str into $phpvar php variable. Please help me

$('#btnShowNew').click(function () {
            var str = [], item;
            $.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
                item = $(this).attr('title');                   
                str.push(item);                   
            });
            <?php 
            include "accounts/config.php";
            $phpvar='"+str+"';
            mysql_query("INSERT INTO sample (sample) VALUES ('".$phpvar."')"); 
            //echo $phpvar;

                  ?>; 
        })
    });

Upvotes: 0

Views: 6714

Answers (5)

Andrei Puf
Andrei Puf

Reputation: 81

This is not possible because the js code is client side and php is server side. What you would need to do is to make an ajax request to a php script in order to send the data for the variable. Here is an example:

Client(browser):

 $.ajax({url:"http://domain.com/accounts/config.php?variableToSend=variableValue",success:function(result){
      alert("Variable was successfully sent.");
    }});

Server(Apache) config.php

<?php
$varToSend = $_GET["variableToSend"]
//Do whatever you want with the variable
?>

Upvotes: 0

Sebastian S
Sebastian S

Reputation: 4712

As the previous speakers already explained, you need to think in terms of client-side running code and server-side running code.

Whenever you want to share a state between those two parts of your application you need some communication mechanism.

Client -> Server

For this you need to make a HTTP request. This can either be a post or a AJAX call. For the latter one just have a look at jquery.ajax as you're obviously already using jQuery anyway.

$.post({
  "savesample.php",
  {myPostVar: str}
}).done(function() {
    alert("sample saved.");
});

Of course you need a serverside script to handle this request:

<?php
  $yourVar = $_POST["myPostVar"];
  // TODO use mysqli::escape_string or similar!!
  mysql_query("INSERT INTO sample (sample) VALUES ('".$yourVar."')");
?>

Server -> Client

This is a lot easier. You can of course use ajax again (GET requests on your php file, which generates a nice javascript-compliant output like JSON).

Or just write your variable to an inline-script-tag:

<script>
<![CDATA[
  var yourJsvar = '<?= $yourPhpVar ?>';
]]>
</script>

Further Reading

As your php file is an open gate for all kinds of misuse you should secure it using one-time authorization tokens. Once you are used to the basic concepts, go on with the following topics:

  • CORS
  • SQL injection
  • Authenticated AJAX calls

Upvotes: 2

alquist42
alquist42

Reputation: 749

JS

$('#btnShowNew').click(function () {

        var str = [], item;
        $.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {

             item = $(this).attr('title');                   
             str.push(item);     

        });

        $.ajax({

            type: "POST",
            url: "save.php",
            data: {items: str},
            success: function(responce) {

                  alert(responce);

            }

        });

});

Create save.php file

<?php 

      include "accounts/config.php";

      $items = $_POST['items']; // Validation HERE!!!

      foreach ($items as $item) { 

          // Insert to DB

      }


      echo 'Saved';

?>
  1. Separate languages = separate files. (if you can...)
  2. In PHP always check user input.
  3. Use PDO.

Upvotes: 0

Twister1002
Twister1002

Reputation: 557

The order in which languages run is PHP -> HTML -> CSS -> Javascript. You can NOT go backwards from that order.

On the other hand, you can send Javascript information through an AJAX call. AJAX is an Asynchronous Javascript call which can communicate with PHP!

So for instance (using JQuery)

$.ajax({
      url:"someurl",
      type:"POST or GET",
      data:{query:"SELECT * FROM table"}, //Any data to pass along? Like strings or data?
      datatype:"JSON", //This is the return type of the information you want if any
      success: successfulHandlerfunction()
      error: errorHandlerfunction()
});

That is just some basic grounds. You can find more information on AJAX calls through http://www.w3schools.com/ajax/

I hope this helps!

Upvotes: 0

Mike_K
Mike_K

Reputation: 9574

You'll want to POST to a PHP listener. You don't want PHP tags inside of a JS function in this way. The only reason for PHP tags inside of a JS function would be if you were getting data from PHP to JS, not the other way around.

Look up Jquery post for more information.

Upvotes: 1

Related Questions