Error passing data from ajax to php (Notice: Undefined index: id)

0

This is the ajax code: clicking on a button opens that function and saves the id of that button in a variable called id. Then it is assumed that with ajax that id is sent to form.php but I get the following error:

  

Notice: Undefined index: id

$("button").click(function(){
        var id = $(this).attr("id");
        $.ajax({
          url: 'form.php',
          method: "POST",
          data: {id : id},
          success: function() {
            $("#form").load("form.php");
          }
        });
      });

Here the PHP code of form.php

<?php
// Initialize the session
session_start();

// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;
}


$id = $_POST['id'];
echo $id;

 ?>

Thanks

    
asked by Gabriel 07.11.2018 в 23:10
source

2 answers

1

You could try sending the data in a text string, something like this:

$("button").click(function(){
    var id = $(this).attr("id");
    var cadena = "id=" + id;
    $.ajax({
      url: 'form.php',
      method: "POST",
      data: cadena,
      success: function() {
        $("#form").load("form.php");
      }
    });

});

I have always worked like this and it works for me.

    
answered by 08.11.2018 в 00:47
0

The problem is in the Ajax call. More specifically when creating the key or key id.

You must replace data: {id : id} with data: {'id' : id} . Assuming that in id you really have a value. The jQuery code should look like this:

$("button").click(function(){
        var id = $(this).attr("id");
        $.ajax({
          url: 'form.php',
          method: "POST",
          data: {'id' : id},
          success: function() {
            $("#form").load("form.php");
          }
        });
  });

On the other hand you should add a validation in your PHP code to determine if you are really receiving the value before trying to display it. For this you can use the isset function. The code should look like this:

<?php
// Initialize the session
session_start();

// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;
}

if(isset($_POST['id'])){
   $id = $_POST['id'];
   echo $id;
}else{
   echo "No llegó el valor id";
 }
 ?>

Greetings!

    
answered by 07.11.2018 в 23:23