van_folmert
van_folmert

Reputation: 4517

How to make a dynamic SQL insert via xhr?

I'm loading my DB to tables and my idea was to enable dynamic edit on the fly, like it is in phpMyAdmin. It wasn't that hard. From the front-end side, at least. Creating remove function for records was also easy, but I can't come with any idea how to make a dynamic insert. Particularly, how to phrase a query that would access the values from the newly edited table row which is meant to be a new record.

As for removing records I use:

var xhr;
xhr=new XMLHttpRequest();

xhr.onreadystatechange=function()
{
  if (xhr.readyState==4 && xhr.status==200)
  {
    document.getElementById("output").innerHTML=xhr.responseText;
  }
}

$.fn.delClick = function() {

  var table = $(this).parent().parent().parent();
  var row = $(this).parent()

  if(confirm("Are you sure?"))
  {

    var tableName = table.find('.add').data('tablename');
    var idName = table.find('.add').data('idname');
    var rowId = row.children('td.id').html();

    xhr.open("POST","scripts/delete?tableName="+tableName+"&idName="+idName+"&rowId="+rowId,true);
    xhr.send(); 

    row.remove();


  }
}

and in scripts/delete.php :

$this->ci =& get_instance(); 

$remove = $this->ci->db->query("DELETE FROM ".$_GET['tableName']." WHERE ".$_GET['idName']." = '".$_GET['rowId']."'");

I hope to make something similar about inserting records, but I'm stuck.
The main problem with inserting records is that I can't pass variables via POST, because amount of columns vary for each table, so that the amount of variables I would need to pass to my scripts/insert.php would also vary. Or maybe there is a way?

Upvotes: 0

Views: 106

Answers (1)

max
max

Reputation: 3736

use object

var inputs = {};
$('.formInput').each(function(){

    var id = $(this).attr('id');
    var val = $(this).val();
    inputs[id] = val ;
});

$.post( insert_url , {inputs:inputs});

also you can analyze some simpler crud systems like

https://github.com/maxxxir/mz-codeigniter-crud

Upvotes: 1

Related Questions