1 Replies - 427 Views - Last Post: 20 August 2016 - 07:18 AM Rate Topic: -----

#1 sunayana1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 31-January 16

How to append html values to json array

Posted 20 August 2016 - 05:59 AM

I have genearted json values from html forum using jquery. Now i need to append that json strigifyied data to json array and check whether value exists before appending to json array.
I have tried some code

My html code

<!DOCTYPE html>
<html>
    <head>
        <title>Add Academic year</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <!--<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" />-->
        <script type="text/javascript" src="jfiles/jquery-1.8.3.js"></script>
        <script type="text/javascript"  src="jfiles/academicscript.js"></script>
        <!--<script type="text/javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>-->
    </head>

    <body>
        <div class="one">
            <fieldset style="width:30%;">
                <div class="whole_medium">
                    <label>Academic Year</label>
                    <input type="text" name="acdyr1" size="5" />-<input type="text" name="acdyr2" size="5" />
                    <select name="medium"></select>
                    <select name="academic_syllabus"></select>
                </div>
                <div class="academic_sec">
                    <select id="standard" name="standard"></select>
                    A<input type="checkbox" name="sec" value="A" />
                    B<input type="checkbox" name="sec" value="B" />
                    C<input type="checkbox" name="sec" value="C" />
                    D<input type="checkbox" name="sec" value="D" />
                    E<input type="checkbox" name="sec" value="E" />
                    <button name="add_class" id="add_class">+</button>
                </div>
            </fieldset>
        </div>
        <button name="save_academic_yr">Save</button>
        <div ></div>

        <table id="display_academic_year" class="display"></table>
    </body>

</html>

// my javascript file
// Code goes here

var med = {
    "": "Medium",
    "KAN": "kannada",
    "ENG": "English",
    "HINDI": "Hindi",
    "URDU": "Urdu",
    "TELGU": "Telgu",
    "TAMIL": "Tamil",
    "MARATI": "Marati"
};
var stand = {
    "": "class",
    "LKG": "LKG",
    "UKG": "UKG",
    "C1": "First",
    "C2": "second",
    "C3": "third",
    "C4": "fourth",
    "C5": "Fivth",
    "C6": "sixth",
    "C7": "seventh",
    "C8": "eighth",
    "C9": "ninth",
    "C10": "tenth"
};
var sec = {
    "": "Sec",
    "A": "A",
    "B": "B",
    "C": "C",
    "D": "D",
    "E": "E",
    "F": "F",
    "G": "G",
    "H": "H"

};
var syllabus_type = {
    "": "syllabus",
    "STATE": "STATE",
    "CBSE": "CBSE",
    "ICSE": "ICSE"
};

$(document).ready(function () {

//
//
//    ////// show in grid
//    academic_tbl = $('#display_academic_year').DataTable({
//        columns: [{
//                title: "Academic Year"
//            }, {
//                title: "Medium"
//            }, {
//                title: "School Syllabus"
//            }, {
//                title: "Class"
//            }]
//    });
//    $.ajax({
//        url: 'json/academic_year.json',
//        dataType: 'json',
//        success: function (json) {
//            $.each(json, function (i, v) {
//                standard = "";
//                sec = "";
//                t_class = "";
//                $.each(v.class_section, function (ack, acv) {
//                    standard += acv.standard + "<br/>";
//                    sec += acv.sec + "<br/>";
//                    t_class += acv.standard + "   " + "[" + acv.sec + "]" + "<br/>";
//                });
//                academic_tbl.row.add(["<div field='academic_year'>" + v.acdyr1 + "-" + v.acdyr2 + "</div>",
//                    "<div field='academic_medium'>" + v.medium + "</div>",
//                    "<div field='academic_syllabus'>" + v.academic_syllabus + "</div>", t_class]).draw();
//
//
//            });
//        }
//
//    });
    $.each(stand, function (k, v) {
        $('select[name="standard"]').append($("<option>").text(v).val(k));
    });
    $.each(med, function (k, v) {
        $('select[name="medium"]').append($('<option>').text(v).val(k));
    });
    $.each(sec, function (k, v) {
        $('select[name="add_section"]').append($('<option>').text(v).val(k));
    });
    $.each(syllabus_type, function (k, v) {
        $('select[name="academic_syllabus"]').append($('<option>').text(v).val(k));
    });
    $('#add_class').click(function () {
        if ($(this).text().indexOf('-') > -1) {
            $(this).parent().remove();
            return;
        } else {

            var new_comm = $(this).closest('.academic_sec').clone(true).insertAfter($('.academic_sec').last());
            if (new_comm.find('.academic_sec').length > 1) {
                console.info('There are more than one.');
                $(new_comm).find('.academic_sec').slice(1).remove();
            }
            new_comm.find('select').val('');
            new_comm.find(':checkbox').prop('checked', false);
            new_comm.find('#add_class').text('-');

        }
    });
    var sm_academic_var = 0;
    /////////////////////// save data
    $('button[name="save_academic_yr"]').click(function () {

//
//
//        $.ajax({
//            url: "json/academic_year.json",
//            dataType: "json",
//            success: function (academicdata) {
//                //  var smtgdata = false;
//                $.each(academicdata, function (akey, avalue) {
//                    var ac1 = $('input[name="acdyr1"]').val();
//                    var ac2 = $('input[name="acdyr2"]').val();
//                    var ac_med = $('select[name="medium"] option:selected').val();
//                    var ac_syllabus = $('select[name="academic_syllabus"] option:selected').val();
//                    var classs = [];
//
//
////                    var ac_class = $('select[name="standard"] option:selected').val();
////
////                    var ac_sec = $('input[name="sec"]:checked').map(function () {
////                        return $(this).val();
////                    }).get();
//
//
//                    if (avalue.acdyr1 == ac1 && avalue.acdyr2 == ac2 && avalue.medium == ac_med && avalue.academic_syllabus == ac_syllabus) {
//                        alert(true);
//
//                        $.each(avalue.class_section, function (clsk, clsv) {
//
//                            console.log("jsonclass" + clsv.standard);
//                            console.log("jsonsec" + clsv.sec);
//                            var json_class;
//                            var json_sec;
//                            $('.academic_sec').each(function (i, v) {
//                                json_class = $(this).find('[name="standard"] option:selected').val();
//
//                                json_sec = $(this).find('[name="sec"]:checked').map(function () {
//                                    return $(this).val();
//                                }).get();
//                                console.log(json_class);
//                                console.log(json_sec);
//
//                                if (clsv.standard == json_class) {
//                                    alert(clsv.standard + " " + "Class already exist");
//
//                                    for (i = 0; i < (clsv.sec).length; i++) {
//
//                                        for (j = 0; j < (json_sec).length; j++) {
//                                            if (clsv.sec[i] == json_sec[j]) {
//                                                alert(json_class + " " + "class" + " " + clsv.sec[i] + "sec" + " " + "already exist");
//                                                sm_academic_var = 1;
//                                                alert(sm_academic_var);
//                                            }
//
//                                        }
//
//                                    }
//
//                                }
//                            });
//
//                        });
//
//                    }
//
//
//                });
//                return false;
//            }
//
//        });


//
//        alert(sm_academic_var);
//        if (sm_academic_var == 0) {

            alert("data is Saving");
            var data = {};
            var clssec = [];
            var medium_syllabus = [];
        

            $('.one input')
                    .not('[name=sec]').each(function (i, v) {
                data[v.name] = v.value;
            });


            $('.one').each(function (i, v) {
                var bunch_fields = {
                    medium: $(this).find('[name="medium"]').val(),
                    academic_syllabus: $(this).find('[name="academic_syllabus"]').val(),
                };
                medium_syllabus.push(bunch_fields);
            });
       data['parameters'] = medium_syllabus;
 

            $('.academic_sec').each(function (i, v) {
                var bunch_fields = {
                    standard: $(this).find('[name="standard"]').val(),
                    'sec[]': $(this).find('[name="sec"]:checked').map(function () {
                        return $(this).val();
                    }).get()

                };
                clssec.push(bunch_fields);
               // console.log(clssec);
            });
            medium_syllabus[0]['class_section'] = clssec;
//            data['class_section'] = clssec;



            var academic_res = JSON.stringify(data);
            
            //console.log(JSON.stringify(data));
            //var academic_res1="["+academic_res+"]";
            // console.log(academic_res1);

            //console.log((acedamic_res));

//            $.ajax({
//                url: 'save_acd_yr_1_1.php?x1=' + encodeURIComponent(academic_res),
//                success: function (data) {
//                    console.log(data);
//                }
//            });


//        }

    });
});


<?php
$acd_yr=$_GET['x1'].",";
//echo "<pre>";print_r(json_decode($_GET['x1']));
$user_input = json_decode($_GET['x1']);

$fstructure=file_get_contents('json/acdy123.json');
//echo "<Pre>";print_r(json_decode($fstructure));
$existing_json = $updated_json = json_decode($fstructure);
if (count($existing_json)) {
	$yearfound = 0;
	$mediumfound = 0;
        echo $mediumfound;
	foreach ($existing_json as $index => $value) {
		//print_r($value);
		if ($user_input->acdyr1 == $value->acdyr1 && $user_input->acdyr2 == $value->acdyr2) {
			$yearfound = 1;
			break;
		}		
	}
	if ($yearfound == 1) {
		foreach ($existing_json[$index]->parameters  as $ind => $val) {
			if ($val->medium == $user_input->medium) {
				$mediumfound = 1;
			}		   
		}
		if ($mediumfound == 0) {
                    echo "dg";
                    echo $user_input->medium;
			$updated_json[$index]->parameters[]= array('medium' => $user_input->medium, 'academic_syllabus' =>  "MATRIC");
		}
	} else {
		$newindex = $index + 1;
		$updated_json[$newindex] =  array('acdyr1' => $user_input->acdyr1, 'acdyr2' => $user_input->acdyr2);
		if (isset($updated_json[$newindex]['parameters'])) 
			$last_index = count($updated_json[$newindex]['parameters']) + 1;
		else
			$last_index = 0;
		$updated_json[$newindex]['parameters'][$last_index]['medium'] =  $user_input->medium;
		$updated_json[$newindex]['parameters'][$last_index]['academic_syllabus'] = "MATRIC";
	}
} else {
	//New file / empty file  
	$index = 0;
	$newindex = 0;
        echo $user_input->acdyr1;
	$updated_json[$index] = array('acdyr1' => $user_input->acdyr1, 'acdyr2' => $user_input->acdyr2);
	$updated_json[$index]['parameters'][$newindex]['medium'] =  $user_input->medium;
	$updated_json[$index]['parameters'][$newindex]['academic_syllabus'] = "MATRIC";
	
}
print_r($updated_json);
//$fstruct=  file_put_contents('acdyr.json', $updated_json,FILE_APPEND);
$fstruct=  file_put_contents('json/acdy123.json', json_encode($updated_json));

exit;

//$fstruct=  file_put_contents('json/acdyr.json', $acd_yr,FILE_APPEND);
//$fstructure=file_get_contents('json/acdyr.json');
//       $fstructure=  "[".rtrim($fstructure,",")."]";
//     
//       echo $fstructure;
//        file_put_contents('json/academic_year.json', $fstructure);
?>

This post has been edited by Atli: 20 August 2016 - 06:36 AM
Reason for edit:: Fixed the [code] tags.


Is This A Good Question/Topic? 0
  • +

Replies To: How to append html values to json array

#2 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3717
  • View blog
  • Posts: 13,491
  • Joined: 08-August 08

Re: How to append html values to json array

Posted 20 August 2016 - 07:18 AM

To simplify your code, look into using
http://php.net/manua...on.in-array.php
or
http://php.net/manua...-key-exists.php
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1