jquery - Accessing a variable written in Java Script in a php file

515

I'm getting a value of a variable using a JQuery function.

<script>
$( "#DivisionIDdetails3" ).change(function() {
var A=$( "#DivisionIDdetails3" ).val();

var ajax = ajaxObj("POST", "XXXXXX.php");
    ajax.onreadystatechange = function() {
        if(ajaxReturn(ajax)== true) {
            if(ajax.responseText != "The User Type was added successfully"){
                status.innerHTML = ajax.responseText;
                 alert (ajax.responseText);


            } else {

                //window.scrollTo(0,0);
                form.innerHTML = "OK "
            }
        }
    }

    ajax.send("A="+A+"&B="+B);

});
</script>

Then I need to sent this value A, to a php file which is written inside the same html page. This is the place where I need to send it.

<html>
<body>
<select id="DivisionIDdetails4" name="DivisionText4" >

<?php
  $result = mysqli_query($con,"SELECT Division_Name FROM Division_Details WHERE Division_Type=''");
  while($row = mysqli_fetch_array($result)){
  echo "<option>$row[Division_Name]</option>";

  }
?>
</select>

<html>
<body>

These are the questions I faced.

1) I suppose I need to use an Ajax function to send it to the PHP code. But how can I name the piece of the PHP file. How can I give a name to it?

2) Could someone please help me in using the ajax function to sent the variable value to the code.

3) I used code of an AJAX as above. But how can I access the PHP file I should use.

865

Answer

Solution:

This will not work like you expect.

Javascript is clientside, which means it is executed once the entire page is loaded. PHP is serverside.

When you visit your site, a request is made from your computer to the server. Here PHP returns its response and the content is then sent to the browser where the Javascript is executed.

This means that it is not possible to mix PHP and Javascript like you are trying to do. They are executed at difference phases of the request.

You should research how Ajax works. jQuery has a great module which makes Ajax-calls very, very easy.

People are also looking for solutions to the problem: php - Is it possible to select only repeated values from a single column using eloquent?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.