2

Hi i trying make form using ajax. But i get some problems to sending form vars to php file. I get error: Undefined index: name. I check chrome dev tools and i see variable is sending. But when made echo json_encode i see in php file i get empty array. So i dont have any idea where i made misstake.

file Main.js

var name = $('#user_name').val();
var lname = $('#user_lastname').val();

function formLogin(name, lname)
{
$.ajax({ url: 'database/register.php',
     data: {
         'name' : name,
         'lname' : lname
     },
     type: 'post',
     dataType:'json',
     success: function(data) {
                  alert(data);
              }
});
}

Html form:

<form class="circleForm" id="registerForm">
     Imię: <input type="text" id="user_name"><br>
     Nazwisko: <input type="text" id="user_lastname">
    <br>
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin(name, lname)">                    
 </form>

Php Code:

$dane = $_POST; echo json_encode($dane);

Chrome dev: enter image description here

I just want figure how can i echo this variables(name,lname) in php file register.php

Version with serialize:

function formLogin() {
        var dane = $('form').serialize();
    $.ajax({
        url: 'database/register.php',
        data: {'dane': dane},
        method: 'post',
        success: function(data) {
            console.log(data);
        }
    });
  
}

Then result console:

<pre class='xdebug-var-dump' dir='ltr'>
<small>D:\xampp\htdocs\szkola\database\register.php:8:</small>
<b>array</b> <i>(size=1)</i>
  'dane' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>''</font> <i>(length=0)</i>
</pre>
jquery-3.2.1.min.js:4 XHR finished loading: POST "http://localhost/szkola/database/register.php".

But when i go to http://localhost/szkola/database/register.php

i get this:

D:\xampp\htdocs\szkola\database\register.php:8: array (size=0) empty

Mariusz
  • 131
  • 3
  • 17
  • Can you provide exact code which you are using to retrieve data on server side? – Vishal Nov 07 '17 at 16:10
  • @VIshal i just learning ajax and make some forms etc. And now i trying make form using ajax and sending 2 inputs (name,lname) to php file and just echo it – Mariusz Nov 07 '17 at 16:21

2 Answers2

2

You need to change the way you define your variables in your Javascript and declare them inside your function, not outside :

function formLogin(){

    var name = $('#user_name').val();
    var lname = $('#user_lastname').val();

    $.ajax({ url: 'database/register.php',
         data: {
             'name' : name,
             'lname' : lname
         },
         type: 'post',
         dataType:'json',
         success: function(data) {
             alert(data);
         }
    });
}

And you need to update your HTML the same way (formLogin() instead of formLogin(...,...)) :

<form class="circleForm" id="registerForm">
     Imię: <input type="text" id="user_name"><br>
     Nazwisko: <input type="text" id="user_lastname">
    <br>
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin()">                    
 </form>
Zenoo
  • 12,670
  • 4
  • 45
  • 69
0

Try using method instead of type.

The HTML:

<form class="circleForm" id="registerForm">
    Imię:       <input type="text" id="user_name" name="name"><br />
    Nazwisko:   <input type="text" id="user_lastname" name="lname"><br />
    <input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin();">                    
</form>

The JavaScript:

function formLogin() {

    // Serialize the form
    var data = $('form').serialize();

    // Ajax call
    $.ajax({
        url: 'database/register.php',
        data: data,
        method: 'post',
        dataType: 'json',
        success: function(data) {
            console.log(data);
        }
    });

}

Also remember that you're requesting a JSON so you have to echo a json_encode($array) in your PHP file for a simple string will not be returned.

Vig
  • 342
  • 1
  • 7
  • I do like u write and i still get empty array. ` $dane = $_POST; echo json_encode($dane); ` and in console i get this object with name and lname – Mariusz Nov 07 '17 at 16:40
  • That is what you're supposed to get. The JSON response you get is an object. You can access its information with, let's say, `console.log(data.name)` & it'll return the value of `name`. – Vig Nov 07 '17 at 16:50
  • ye i know that but i dont know how send this 2 vars to register.php i really trying it on different way but still i dont know why i get empty array or error about undefine index. I am was reading a lot of post and watching tutorials about ajax and i think my code looks good event on img i see post working but really now i dont know where i made misstake. – Mariusz Nov 07 '17 at 16:56
  • Try running a `console.log` for those two variables before making the Ajax request. If they are displayed in the console, that step was done right. If they are not displayed in the console, maybe there's something wrong with the way you're getting the input values. – Vig Nov 07 '17 at 17:05
  • Also, you said that you're getting an object in the console after making the Ajax request. Are the object items empty? Because the problem is somewhere in between sending the wrong values in the Ajax request and encoding them to JSON in the PHP file. – Vig Nov 07 '17 at 17:06
  • ok i made console.log without ajax and its working. When i make ajax form i get normal object: {name: "sadasd", lname: "asdsa"}. Ye its showing object in consol when success in ajax. – Mariusz Nov 07 '17 at 17:08
  • That is right then, you're supposed to get that exact response from the PHP file. What are you having trouble with? – Vig Nov 07 '17 at 17:13
  • My problem is i trying get this object in php file. Next i want just make simply echo but when i do json_encode i get empty array and i dont know why even i trying print_r $_POST i get thats same empty array. When i go to http://localhost/szkola/database/register.php i just get [] – Mariusz Nov 07 '17 at 17:16
  • Well you're creating this object from the `$_POST` array you're encoding to JSON in the PHP file. You can mess with this array and generate your own JSON for the response. And the reason why you're not being able to display anything other than JSON is because you've set the `dataType` to `json` in the Ajax call. The `dataType` is what you're expecting as a response from the PHP file. If you remove that, you'll be able to get any type of content (strings, intergers and etc). – Vig Nov 07 '17 at 17:21
  • You can access each `$_POST` item inside the PHP file as `$_POST['name']` or so. – Vig Nov 07 '17 at 17:24
  • Ok so if i get type json i get object so when i use $dane = $_POST; echo json_encode($dane); Can i do like that? – Mariusz Nov 07 '17 at 17:26
  • If you remove the `dataType` setting you'll be able to run a `var_dump($_POST);` in your PHP file and it'll be displayed in the console. – Vig Nov 07 '17 at 17:26
  • No i cant use $_POST['name'] becouse i get error about undefine index and when i print_r $_POST i just get Array() i delete datatypa json from ajax. – Mariusz Nov 07 '17 at 17:28
  • If you set the `dataType` to `json` you'll only be able to echo json-encoded arrays, which will be turnet to JavaScript objects. `json_encode()` turns a PHP `array()` into a JavaScript object (`{}`). – Vig Nov 07 '17 at 17:29
  • When i var_dump($_POST); i get D:\xampp\htdocs\szkola\database\register.php:8: array (size=0) empty – Mariusz Nov 07 '17 at 17:30
  • Well then there's something wrong with your Ajax call. Try this: Add some `name` attributes to the inputs (name and lname, for example) and instead of declaring variables to these inputs in your JS, declare a single variable with `$('form').serialize();`. In your Ajax call, set the `data` value to this variable you just declared. That way it should work. – Vig Nov 07 '17 at 17:32
  • I updated the answer if that helps. – Vig Nov 07 '17 at 17:42
  • i do like u write and still when i go to http://localhost/szkola/database/register.php i see empty array i use json_encode – Mariusz Nov 07 '17 at 17:48
  • If you manually go to that PHP file you'll get an empty array. To test that, you have to submit the form with the inputs filled out, otherwise there is no information for the PHP to get. – Vig Nov 07 '17 at 17:51
  • Are u sure?? But when i just want make new record to database so i will be use $_POST['data'] but its will be error about undefine index. – Mariusz Nov 07 '17 at 18:10
  • 1
    Yes I am sure. & there is no `$_POST['data']`. The `data` variable you declare in your JS is the serialized form, not an actual `$_POST` item. This variable will bring every input along with their values. In your PHP file, you'll be able to access each input's value by its name, like this: `$_POST['name']`. The same for other inputs, e.g.: If you want to access a serialized form's input "``", you should go `$_POST['user_email']`. ––– `$_POST['data']` doesn't exist because `data` is just a variable containing every input. – Vig Nov 07 '17 at 18:17
  • OK really thx for explain it:D I was sure i could easy print this variable to check it to be sure its working. – Mariusz Nov 07 '17 at 18:22
  • No problem mate! :) – Vig Nov 07 '17 at 18:26