0

With an AJAX call I insert a record in a MySQL database.

MAIN.PHP
-------------
  $.ajax({
    url:'pages/insert.php',
    method:'POST',
    data:{
        kind:kind,
        title:title,
    },
    error: function() {
        alert('Bericht toevoegen is fout gegaan!');
    },
    success:function(data){
                alert(data.id);
    }
  });

In insert.php the content will be inserted in the datebase. In the table there is a autonumber field 'id'. This field would I like to receive back, so I call directly after the insert: mysqli_insert_id($conn) and echo the result.

INSERT.PHP
------------
$actie = mysqli_query($conn, "INSERT INTO tbCont (User, SoortBericht, Teaser) VALUES ('$user', '$kind', '$title');") or die(mysqli_error($conn));

$last_id = mysqli_insert_id($conn);
echo json_encode(['id'=>$last_id]);

In the main file I would use the id, but I don't receive it back. Alert(data.id) shows me 'undefinded'.

Alert(data) shows me {"id":34133}, thats better. But what is the right syntax to use the id? And what when I will give more results back?

Nico van Wijk
  • 241
  • 1
  • 9
  • 2
    Parse json data i.e :`$.parseJSON(data);` and then get it like -> `data.id` or give `dataType : 'json'` to your ajax – Swati Aug 23 '20 at 12:17
  • @Swati I suppose you should answer. Maybe there's a duplicate for this but I can't find) – u_mulder Aug 23 '20 at 12:19
  • 1
    @u_mulder i found similar answer here - > https://stackoverflow.com/a/8649657/10606400 – Swati Aug 23 '20 at 12:24
  • Setting `dataType : 'json'` is all you would need to have jquery auto-parse it. Its the preferred way to handle json returns (since it means you are expecting valid json and nothing else). As for "*And what when I will give more results back?*", you just add more to your array that you `json_encode`. There is really no limit. – IncredibleHat Aug 23 '20 at 12:25
  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Aug 23 '20 at 13:23
  • It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Aug 23 '20 at 13:23

0 Answers0