How to send json array value to php and save to database using javascript

23
November 20, 2018, at 08:00 AM

I finally managed to get the json value into an array. But now Im struggling how to send the array to my php file to be saved to my database. I've tried several methods but none worked. Please help me send these datalist values to my php and save to my database using javascript. How can I establish a connection between my php file and javascript where the data is being pushed?

<!DOCTYPE html> 
<html> 
<head> 
 
<script> 
window.onload = function() { 
      var ModelArray = { 
        "Mammals": { 
          "Dog": { 
            "Dog Food": ["Milk"] 
          }, 
          "Cat": { 
            "Cat food": ["Milk"] 
          }, 
          "Tiger": { 
            "Meat": ["Water"] 
          }, 
          "Monkey": { 
            "Banana": ["Water"] 
          } 
        }, 
        "Reptiles": { 
          "Snake": { 
            "Rat": ["None"] 
          }, 
          "Turtle": { 
            "Plant": ["Water"] 
          }, 
          "Lizard": { 
            "Insects": ["None"] 
          }, 
          "Crocodile": { 
            "Meat": ["Water"] 
          } 
        } 
      } 
 
 
      //Get html elements 
      var model = document.getElementById("MODEL"); 
      var destination = document.getElementById("destination"); 
      var criteria = document.getElementById("criteria"); 
      var material_form = document.getElementById("material_form"); 
 
      //load models 
      for (var model_value in ModelArray) { 
        model.options[model.options.length] = new Option(model_value, model_value); 
      } 
 
      //model changed -> destination value 
      model.onchange = function() { 
 
        destination.length = 1; 
        criteria.length = 1; 
        material_form.length = 1; 
 
        if (this.selectedIndex < 1) { 
          criteria.options[0].text = "" 
          return; 
        } 
        destination.options[0].text = "Select Animal..." 
        for (var destination_value in ModelArray[this.value]) { 
          destination.options[destination.options.length] = new Option(destination_value, destination_value); 
        } 
        if (destination.options.length == 2) { 
          destination.selectedIndex = 1; 
          destination.onchange(); 
        } 
      } 
 
      //destination changed -> criteria value 
      model.onchange(); 
      destination.onchange = function() { 
 
        criteria.length = 1; 
        material_form.length = 1; 
 
        if (this.selectedIndex < 1) { 
          criteria.options[0].text = "" 
          return; 
        } 
        criteria.options[0].text = "" 
        for (var criteria_value in ModelArray[model.value][this.value]) { 
          criteria.options[criteria.options.length] = new Option(criteria_value, criteria_value); 
        } 
        if (criteria.options.length == 2) { 
          criteria.selectedIndex = 1; 
          criteria.onchange(); 
        } 
      } 
 
      //criteria changed -> material form value 
      criteria.onchange = function() { 
        material_form.length = 1; 
 
        if (this.selectedIndex < 1) { 
          material_form.options[0].text = "" 
          return; 
        } 
        material_form.options[0].text = "" 
        var material_form_value = ModelArray[model.value][destination.value][this.value]; 
 
        for (var i = 0; i < material_form_value.length; i++) { 
          material_form.options[material_form.options.length] = new Option(material_form_value[i], material_form_value[i]); 
        } 
        if (material_form.options.length == 2) { 
          material_form.selectedIndex = 1; 
          // material_form.onchange(); 
        } 
      } 
    } 
 
      function SaveData(){ 
 
    var DataList=[]; 
    var table = document.getElementById("bod"); 
      var rowLength = table.rows.length; 
 
    //loops through rows     
    for (i = 0; i < rowLength; i++){ 
 
      //gets cells of current row   
       var oCells = table.rows.item(i).cells; 
 
       //gets amount of cells of current row 
       //var cellLength = oCells.length-2; 
 
       //loops through each cell in current row 
       var  item = []; 
        item["destination"] = oCells.item(0).innerHTML; 
        item["criteria"] = oCells.item(1).innerHTML; 
        item["material"] = oCells.item(2).innerHTML; 
         
        DataList.push(item) 
 
        request = new XMLHttpRequest() 
        request.open("POST", "DOM_SAVE.php", true) 
        request.setRequestHeader("Content-type", "application/json") 
        request.send(DataList) 
      } 
       console.log(DataList); 
    } 
	 
	 
    function addRow() { 
      var table = document.getElementById("bod"); 
      var rowCount = table.rows.length; 
      var row = table.insertRow(rowCount); 
 
 
      row.insertCell(0).innerHTML = destination.value; 
      row.insertCell(1).innerHTML = criteria.value; 
      row.insertCell(2).innerHTML = material_form.value; 
      row.insertCell(3).innerHTML = '<input type="button" value="Delete" onClick="Javacsript:deleteRow(this)">'; 
	    row.insertCell(4).innerHTML = rowCount; 
    } 
    function deleteRow(obj) { 
      var index = obj.parentNode.parentNode.rowIndex; 
      var table = document.getElementById("myTableData"); 
      table.deleteRow(index); 
    } 
   
</script> 
</head> 
<body> 
<form> 
<center> 
   <td><b>MODEL: </b></td> 
    <td> 
      <select id="MODEL" NAME="MODEL" size="1" required> 
        <option value="" selected="selected">Select Model...</option> 
      </select> 
    </td> 
    <b>DESTINATION: </b></td> 
    <tr> 
      <td> 
        <select ID="destination" NAME="destination[]" required> 
          <option value="" selected="selected">Select Model First...</option> 
        </select> 
        <select ID="criteria" NAME="criteria[]" contenteditable="true" required> 
        </select> 
        <select ID="material_form" NAME="material_form[]"  required> 
        </select> 
        <input type="button" id="add" value="Add Destination" onclick="Javascript:addRow()"> 
      </td> 
    </tr> 
	</center> 
    <div id="mydata" style="text-align: center"><center> 
      <table id="myTableData" border="1" style="text-align:center;" ><br> 
        <thead> 
          <tr> 
            <td style="padding: 0 10px 0 10px"><b>DESTINATION</b></td> 
            <td style="padding: 0 10px 0 10px"><b>CRITERIA</b></td> 
            <td style="padding: 0 10px 0 10px"><b>MATERIAL FORM</b></td> 
			<td style="padding: 0 10px 0 10px"><b>.............</b></td> 
			<td style="padding: 0 10px 0 10px"><b>Row Count</b></td> 
          </tr> 
		  </center> 
        </thead> 
        <tbody id="bod"> 
        </tbody> 
      </table> 
    </div><br><center> 
<input type="button" onclick="SaveData()" id="SaveBtn" value = "Submit"/></center> 
</form> 
</body> 
 
<?php 
 
    function SaveData(){ 
 
    //echo  $_POST['criteria']; 
	$DataList = file_get_contents('php://input'); 
    } 
?> 
 
</html>

Answer 1

Try it with this

$.post('My_URL', {data: JSON.stringify(ModelArray)}, function(data){
    // do something
}, 'json');

If you want the PHP to do the insert using loop,

Also you can use the loop and put the value inside post on jquery which will make it insert one by one using jquery

READ ALSO
Tensorflow not working right, not sure what is wrong

Tensorflow not working right, not sure what is wrong

I use Android Studio to code and in the tensorflowObjectDetection example, I commented out @Disable and added our Vuforia key, and when I run the program it just crashesI've narrowed it down to this code:

22
Apache Commons Configuration: read from classpath/JAR?

Apache Commons Configuration: read from classpath/JAR?

Does the Apache Commons Configuration library support reading properties/configuration files from the classpath or JAR? I didn't find an API where it can take an InputStream, that returned by getResourceAsStream

17
Spring Controller gives me 404 status error

Spring Controller gives me 404 status error

So I am attempting to write a basic Rest Controller in Spring Tool Suite with Spring annotations where I hit the endpoint "/health" and I receive the following message upon hitting the endpoint "Kafka Streaming App is healthy"

37
Writing dynamic checkbox list, How can I submit the checked boxes? [on hold]

Writing dynamic checkbox list, How can I submit the checked boxes? [on hold]

I am producing a list of students so a user can mark their absenceI want to have a form which has the checkbox and their name for each student on the users roster

12