简体   繁体   中英

Passing variables between two ajax calls in PHP

I'm creating a personal website to help with task management in a project environment.

I've got a mySQL table (tblProjects) that contains the following fields; id, ownerID, projectName and createdDate. I've then got another table (tblToDos) that contains the following fields; id, projectId (links to id in tblProjects) toDoName, toDoDueDate, createdDate.

The idea being that many todos can belong to a project.

At present, when the site loads, i'm using ajax and jQuery to show a list of projects. When i click on one of the projects in the list, i want to be able to run another ajax Query to load the todos from that project into a separate div on the same page (similar to when you click on an email in gmail for example, the email content loads on the right)

The crux of my problem is that i don't know how to pass the ID of the project from my first Ajax request into the second one so that i can return the todos associated with the project that was clicked on.

You could associate each project with its ID, ie, say you got a button for each project:

<input type="button" value="Show TODOs for this project" onclick="showTodos(1)">

Where "1" is the ID of your project.

Then, in the showTodos() function, you could have something like this:

function showTodos(projectId) {
  $.ajax({
     type: "GET",
     url: "/todos.php?id=" + projectId,
     success: function (json) {
       // Construct the div here
     }
  });
}

why not store the tblProject.id in an attribute (data-id) for the element your using for the the click event, then access it via something like:

    var projectId = $(this).attr( "data-id" );

If your loading content via .load (lets assume you gave this div the class "box"), the second parameter accepts data array so you can pass via:

    $( ".box" ).load( 'myPHPscript.php',  { "projectId" : projectId } );

You will be able to access the passed variables in your php script using:

    if( isset( $_POST['projectId'] ) ){
        $project_id = $_POST['projectId'];
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM