6

This is my code and i want to pass javascript variable with ajax to php when i click submit button then the result doesn't show var_data variable from javascript What code is wrong? This is edit order one before everybody help me

 <!DOCTYPE html>
<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
        $(document).ready(function() {
            $('#sub').click(function() {
                var var_data = "Hello World";
                $.ajax({
                    url: 'http://localhost/ajax/PassVariable.php',
                    type: 'GET',
                     data: { var_PHP_data: var_data },
                     success: function(data) {
                         // do something;

                     }
                 });
             });
         });
 </script>

 </head>
 <body>

 <input type="submit" value="Submit" id="sub"/>

 <?php 
   $test = $_GET['var_PHP_data'];
     echo $test;
 ?>
 </body>
 </html>

and this is source code now

 <?php
     if (isset($_GET['var_PHP_data'])) {
       echo $_GET['var_PHP_data'];
     } else {
     ?>
     <!DOCTYPE html>
     <html>
       <head>
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
            <script src="http://malsup.github.com/jquery.form.js"></script> 
         <script>
             $(document).ready(function() {
                 $('#sub').click(function() {
                     var var_data = "Hello World";
                     $.ajax({
                         url: 'http://localhost/test.php',
                         type: 'GET',
                          data: { var_PHP_data: var_data },
                          success: function(data) {
                              // do something;
                             $('#result').html(data)
                          }
                      });
                  });
              });
         </script>
       </head>
       <body>
         <input type="submit" value="Submit" id="sub"/>
         <div id="result">
       </body>
     </html>
    <?php } ?>

this statement if(isset($_GET['var_PHP_data'])) output false and then show Hello World What should i do to do for isset($_GET['var_PHP_data']) is true?

5
  • Avoid using System defined keyword`s for variables names Commented May 8, 2013 at 6:57
  • where is your form tag ? use like this <form action='<?=$_SERVER['PHP_SELF']?>' method='post'> and enclose your submit button within it Commented May 8, 2013 at 7:00
  • Action can be "" if the form is posting to itself. I can't reproduce your error, I can see that $_GET['var_PHP_data'] shows Hello World. Commented May 8, 2013 at 7:01
  • try success: alert('success!'); does it work? Commented May 8, 2013 at 7:01
  • i try to alert('success!') and it work but $_GET['var_PHP_data'] still can't shows Hello World Commented May 8, 2013 at 7:07

5 Answers 5

4

Your solution has PHP issues: you don't check if the data exists, and also, you don't do anything with the result. I've modified the script to do the following:

  1. Check if the var_PHP_data var is set (in PHP, on the server).
  2. If yes, just send a blank text response containing that data.
  3. If no, then draw the form and everything else.
  4. In the form, I've created a #result div.
  5. Ajax response will be shown in this div.

Also make sure that you host the script at localhost and that it is called test.php. To make sure this is resilient, you can change the Ajax URL to <?php echo $_SERVER['PHP_SELF'];?> to make sure that you'll hit the correct script.

<?php
    if (isset($_GET['var_PHP_data'])) {
      echo $_GET['var_PHP_data'];
    } else {
    ?>
    <!DOCTYPE html>
    <html>
      <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
        <script>
            $(document).ready(function() {
                $('#sub').click(function() {
                    var var_data = "Hello World";
                    $.ajax({
                        url: 'http://localhost/test.php',
                        type: 'GET',
                         data: { var_PHP_data: var_data },
                         success: function(data) {
                             // do something;
                            $('#result').html(data)
                         }
                     });
                 });
             });
        </script>
      </head>
      <body>
        <input type="submit" value="Submit" id="sub"/>
        <div id="result">
      </body>
    </html>
    <?php } ?>
Sign up to request clarification or add additional context in comments.

5 Comments

I try follow with your code when i click submit it show same page and ajax doesn't response shown in this div.
Ok i change <script src="ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"> to <script src="ajax.googleapis.com/ajax/libs/jquery/1.7/…> and output show Hello World
what should i do for var_PHP_data var is set ?
That is the first part of <?php tag. It checks if there is data in the var, and only returns that data, no HTML code. If nothing, it means this is (probably) not the Ajax call, but the first browser visit, so it skips that and reloads the form. You could also dos omething else there. Ie. <?php if (isset($_GET['username']) && $_GET['username'] == "admin") { echo "Admin user";} else { echo "No privileges". } else ?> ...then the rest again.
Or you could do something with the var_PHP_data, like change it, reverse it, capitalize, check something in the database with it, whatever. That depends on your needs.
2

Try jQuery Form its this will help to solve many problems.

For you question: try url without domain name, add tags 'form', change event click to submit, add data type

1 Comment

And update jQuery to new version(1.9 or 2.0 for new browsers)
2

what are the contents of PassVariable.php ? if is the same where you have they jquery bit wont work coz php will print all the page again, if the file is different try

success: function(data) {
                     alert('databack = '+ data);

                 }

Comments

1

Try placing your input into a form and attaching the ajax call to the form onsubmit event. The way it happens in the provided happen is when you click in the field, in which case it submits before you can write anything really.

Comments

1
$(document).ready(function() {
        $('#brn').click(function() {
            var var_data = "Hello World";
            alert("click works");
            $.ajax({
                url: 'http://localhost/ajax/PassVariable.php',
                type: 'GET',
                 data: { x: var_data },
                 success: function(data) {
                     alert(data);

                 }
             });
         });
     });

change it to this code

then in PassVariable.php put

make button

<input type="button" id="btn"  value="click me" />

it should work because it is very basic example. If it doesn't work check your console if there are any JavaScript errors and remove them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.