Viewed   96 times

I'm trying to pass a JavaScript variable to PHP with AJAX. It's not working and I cannot understand what I am doing wrong. I am always getting the following errors:

1) Notice: Undefined variable: id in ...movies.php on line 174

2) Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in ...movies.php on line 176.

I use chrome dev tools and I can see that the AJAX call is successful.

 <?php
session_start();
include_once 'dbconnect.php';

if(isset($_POST['id'])){
    $id = $_POST["id"];
    echo $id;                            
}   
?>

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport" >
    <!--Insert sidebar CSS-->
    <link rel="stylesheet" href="css/sidebar.css" type="text/css" />
    <!--Insert Custom CSS-->
    <link rel="stylesheet" href="css/style.css" type="text/css"/>
</head>
<body>

<!-- Start of navbar -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="index.php"></a>
        </div>
        <div class="collapse navbar-collapse" id="navbar1">
            <ul class="nav navbar-nav navbar-right">
                <?php if (isset($_SESSION['usr_id'])) { ?>
                <li><h4 class="navbar-text"></h4></li>
                <li><a href="store.php">Store</a></li>
                <li><a href="settings.php"><i class="fa fa-cog" aria-hidden="true"></i>
 Account</a></li>
                <li><a href="logout.php"><i class="fa fa-power-off"></i> Log Out</a></li>             
                <?php } else { ?>
                <li><a href="login.php"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
                <li><a href="register.php"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
                <?php } ?>
            </ul>
        </div>
    </div>
 </nav>


    <div id="wrapper">

        <!-- Sidebar -->
        <div id="sidebar-wrapper">
            <ul class="sidebar-nav">
                <li class="sidebar-brand">
                    <a href="#">
                        Welcome <?php echo $_SESSION['usr_name'];?>!
                    </a>
                </li>

                <li>
                    <a href="store.php" class="active">Edit Movies</a>
                </li>
                <li>
                    <a href="users.php" class="active">Edit Users</a>
                </li>

                <li>
                      <a href="movies.php">Movies Gallery</a>
                </li>
                <li>
                    <a href="#">My Rents</a>
                </li>
                <li>
                    <a href="#">All Rents</a>
                </li>
                <li>
                    <a href="#">Account</a>
                </li>
                <li>
                    <a href="#">Contact</a>
                <li>
                    <a href="#">Log out</a>
                </li>
            </ul>
        </div>
        <!-- /#sidebar-wrapper -->

        <!-- Page Content -->
        <div id="page-content-wrapper">
            <div class="container-fluid" id="movie-catalog">
                <div class="row">

                    <?php 
                        $result = mysqli_query($con, "SELECT * FROM movies");

                        while($row = mysqli_fetch_array($result)){
                            echo ' 
                            <div class="col-md-3 portfolio-item">
                                <a href="#">
                                    <img class="img-responsive img-center cover" src='.$row['cover_path'].' style="width:150px;height:200px;" alt="">
                                </a>
                                <h3 class="text text-center">
                                    <a href="#">'.$row['title'].'</a>
                                </h3>
                                <div class="centered">
                                    <input class="btn btn-info text-center info-button" type="submit" data-id="'.$row['id'].'" data-toggle="modal" name="id" value="Info" />
                                    <button type="button" class="btn btn-warning center">Rent</button> 
                                </div><br>
                            </div>';
                        }

                    ?>

                </div>
        <!-- /.row -->

                <!-- Pagination -->
        <div class="row text-center">
            <div class="col-lg-12">
                <ul class="pagination">
                    <li>
                        <a href="#">&laquo;</a>
                    </li>
                    <li class="active">
                        <a href="#">1</a>
                    </li>
                    <li>
                        <a href="#">2</a>
                    </li>
                    <li>
                        <a href="#">3</a>
                    </li>
                    <li>
                        <a href="#">4</a>
                    </li>
                    <li>
                        <a href="#">5</a>
                    </li>
                    <li>
                        <a href="#">&raquo;</a>
                    </li>
                </ul>
            </div>
        </div>
        <!-- /.row -->

            </div>
        </div>
        <!-- /#page-content-wrapper -->
    </div>
    <!-- /#wrapper -->


    <!-- Modal -->
      <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog modal-md">
          <div class="modal-content">

            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal">&times;</button>
              <h4 class="modal-title">Movie Info</h4>
            </div>

            <div class="modal-body">
                <div class="row">
                    <p class="modal-text"></p>
                    <?php 


                        $movie = mysqli_query($con, "SELECT * FROM movies WHERE id=".$id);

                        $row = mysqli_fetch_array($movie);

                        echo '  
                        <div class="col-md-4">
                            <div class="info-image">
                            <img class="img-responsive" src="'.$row['cover_path'].'" style="width:150px;height:200px;"> 
                        </div>
                        </div>   

                        <div class="col-md-4">
                            <h4>Title: '.$row['title'].'</h4>
                            <h4>Director: '.$row['director'].'</h4>
                            <h4>Year: '.$row['d'].'</h4>
                            <h4>Description: '.$row['description'].'</h4>
                            <a href=""><img class="imdb-img" src="images/IMDb-Icon.png" style="width:80px;height:80px;"></a>
                            <a href=""><img class="imdb-img" src="images/youtube_logo.png" style="width:60px;height:40px;"></a>
                        </div>
                    '; ?>
                </div>
            </div>

            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>

          </div>
        </div>
      </div>

    <!-- Modal end -->

    </body>

    <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>

    <!-- Menu Toggle Script -->
    <script> 
    $(document).on("click", ".info-button", function () {

        var myBookId = $(this).data('id');
        $(".modal-body .modal-text").text(myBookId);

        var id = myBookId.toString();
        //alert(variableToSend);

        $.ajax({
        url : "movies.php",
        type: "POST",
        data : {"id" : id},
        success: function(data)
        {
            //data - response from server
            alert(data);
            $('#myModal').modal('show');
        }

    });


    });         
    </script>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

    <!-- Insert Font-Awesome -->
    <script src="https://use.fontawesome.com/2ce34ad1b9.js"></script>

</html>

 Answers

4

You have to create another php file to call with ajax.
This file will only produce your #myModal div's inner content.
This div should be empty here : <div class="modal fade" id="myModal" role="dialog"></div>

// This retreives the data-id
var myBookId = $(this).attr('data-id');

$.ajax({
    url : "movies-modal.php",   // The other php filename here
    type: "POST",
    data : {"id" : myBookId},
    success: function(html)
    {
        $('#myModal').html(html);
        $('#myModal').modal('show');
    }
});
Friday, November 11, 2022
 
3

This answer provides the necessary modifications to your code.

DISCLAIMER: Without seeing the exact install, be aware there may be a variety of factors that cause this to not work "as-is" in your installation. I do not know how your routes are set up, or if you are using Firebug or some other console to watch the ajax calls, but this should give you the building blocks:

First, change your php to output the array as a json-encoded string:

public function getCars(){
        $this->load->model('car_model');

        $this->form_validation->set_rules('carId', 'carId', 'trim|xss_clean');

        if($this->form_validation->run()){
            $carId = $this->input->post('carId');
            $carModels = $this->user_management_model->getCarModels($carId);
            // Add below to output the json for your javascript to pick up.
            echo json_encode($carModels);
            // a die here helps ensure a clean ajax call
            die();
        } else {
            echo "error";
        }   
}

Then, modify your script ajax call to have a success callback that gets the data and adds it to your dropdown:

function myFunction(obj)
  {
    $('#emptyDropdown').empty()
    var dropDown = document.getElementById("carId");
    var carId = dropDown.options[dropDown.selectedIndex].value;
    $.ajax({
            type: "POST",
            url: "/project/main/getcars",
            data: { 'carId': carId  },
            success: function(data){
                // Parse the returned json data
                var opts = $.parseJSON(data);
                // Use jQuery's each to iterate over the opts value
                $.each(opts, function(i, d) {
                    // You will need to alter the below to get the right values from your json object.  Guessing that d.id / d.modelName are columns in your carModels data
                    $('#emptyDropdown').append('<option value="' + d.ModelID + '">' + d.ModelName + '</option>');
                });
            }
        });
  }

Again - these are the building blocks. Use your browser console or a tool such as Firebug to watch the AJAX request, and the returned data, so you can modify as appropriate. Good luck!

Sunday, November 27, 2022
5

Your code works if you remove dataType: 'json', just tested it.

$('#save').click(function() {
  var tmp = JSON.stringify($('.dd').nestable('serialize'));
  // tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
  $.ajax({
    type: 'POST',
    url: 'save_categories.php',
    data: {'categories': tmp},
    success: function(msg) {
      alert(msg);
    }
  });
});
Wednesday, August 3, 2022
3

There are few things wrong in your code, such as:

  • Even through you defined send_ajax() function, you didn't call it anywhere in the code.
  • With POST request you need to send an HTTP header setRequestHeader() along with the request, like this:

    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
  • echo $_POST['name']; in test.php page won't work because name is undefined here. Your send() method call should be like this:

    request.send("name="+valueToSend);
    

So the complete JavaScript code would be like this:

var valueToSend = Math.random(); 

var request = false;
if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
    request = new ActiveXObject('Microsoft.XMLHTTP');
}

function send_ajax() {
    if (request) {
        request.open('POST', 'test.php', true);
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                console.log(request.responseText);
            }
        }
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.send("name="+valueToSend);
    }
}

send_ajax();
Tuesday, October 18, 2022
 
hcheung
 
3

You need to include a success handler in your AJAX call:

$("#text-id").on( 'click', function () {
    $.ajax({
        type: 'post',
        url: 'text.php',
        data: {
            source1: "some text",
            source2: "some text 2"
        },
        success: function( data ) {
            console.log( data );
        }
    });
});

and in your console, you'll receive:

some textsome text 2

Do make sure that both the test.php and your html source files are in same directory.

Sunday, November 13, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :