-1

how to solve the undefined index error? see below for my code

on Products Class

public function add(){
    var_dump($_POST);
    $pname = $_POST['pname'];
    echo $pname;
}

ajax code:

$('#productsform').on('submit', function(event){
    event.preventDefault();
    var data = $('#productsform').serialize();
    $.ajax({ 
      url:'action.php',
      data: {'action': 'add', 'data': data},
      type: 'post',
      success: function(response) {
        console.log(response);
      }
    });
});

here is action.php

include_once('classes/Products.php');

$product = new Products();

if(isset($_POST['action'])){
    if($_POST['action'] == 'add'){
        $product->add();
        exit();
    }
}

now, the output in console log:

array(2) {
  ["action"]=>
  string(3) "add"
  ["data"]=>
  string(29) "pname=asdadsad&pprice=&pdesc="
}
<br />
<b>Notice</b>:  Undefined index: pname in <b>D:\xampp\htdocs\prince2\classes\Products.php</b> on line <b>25</b><br />

i already type "asdadsad" as input for named pname..

pls help

1 Answers1

0

Change like this:

$('#productsform').on('submit', function(event){
    event.preventDefault();
    var data = $('#productsform').serialize(); // pass action in hidden field 
    $.ajax({ 
      url:'action.php',
      data: data,
      type: 'post',
      success: function(response) {
        console.log(response);
      }
    });
});
Ahmed Ginani
  • 6,522
  • 2
  • 15
  • 33
  • thank you it works, the undefined index for all textboxes are gone .. but yet the undefined index for select option are still display on console log. my form consists of 3 texbox 2 selection option and 1 input type file. – John Advincula Apr 25 '17 at 12:20
  • That means you need to declare selection option variable in code – Ahmed Ginani Apr 25 '17 at 12:31
  • hi ahmed, i thought the .serialize() will get all the value of the tags in a form that has a name attribute, so i wonder that the .serialize() cant get the select option tag – John Advincula Apr 25 '17 at 13:26
  • You can add that data as.. $('#productsform').serialize() + "&moredata=" + morevalue – Ahmed Ginani Apr 28 '17 at 07:28