Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can remove last comma from json using javascript forloop

    $('#save').click(function() {
    var loopvalue = "<?php echo $count; ?>"
    var datajson = '[';
    //alert(loopvalue + "length of array")
    for (i = 1; i < loopvalue; i++) {
        var fetchid = '.A' + i;
        var fetchid_code = '.C' + i;
        datajson = datajson + "{" + "maincode :" + $('#company').val() + ",acode : " + $(fetchid_code).text() +
            " , Amount :" + $(fetchid).val() + ", periodfrom :" + $('#dFrom').val() +
            ", periodto : " + $('#dTo').val() + ", danounc : " + $('#dano').val() +
            ", period : " + $('#period').val() + ", fyear : " + $('#fyear').val() +
            ", frequency : " + $('#freq').val() + ", stype : " + $('#stype').val() +
            ", sseq : " + $('#sseq').val() + " }, "

    }
    datajson = datajson + ']'
        //console.log(datajson);

    $.ajax({
        type: 'POST',
        url: 'jsondecode.php',
        data: {
            datajson: JSON.stringify(datajson)
        },
        //data:postArray,
        dataType: "json",
        success: function(data) {
            console.log("success:", data);
        },
        failure: function(errMsg) {
            console.error("error:", errMsg);
        }
    });
});

first i remove last comma in json object and second when i am calling ajax page but it is displaying NULL value in jsonencode.php page how can I solve this problem any can suggest me this is my server site script now

 <?php
     header('Content-Type: application/json');    
    $data = json_decode($_POST["datajson"]);
// will echo the JSON.stringified - string:
echo $_POST["datajson"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
foreach ($data as $Object) {
    echo "maincode: " . $Object->maincode . ", Acode: " . $Object->acode . "<br/>";
}
?>
like image 856
Faizan Ahmed Avatar asked Feb 16 '26 08:02

Faizan Ahmed


1 Answers

Or maybe you should use actual object instead of string-concatenation

Try this

var datajson = [];
for (i = 1; i < loopvalue ; i++) 
{
    var fetchid = '.A' + i;
    var fetchid_code = '.C' + i;
    var obj = {
        maincode : $('#company').val(),
        acode   : $(fetchid_code).text(),
        Amount  : $(fetchid).val(),
        periodfrom : $('#dFrom').val(),
        periodto   : $('#dTo').val(),
        danounc    : $('#dano').val(),
        period    : $('#period').val(),
        fyear    : $('#fyear').val(),
        frequency    : $('#freq').val(),
        stype    : $('#stype').val(),
        sseq    : $('#sseq').val()
    }
    datajson.push( obj );
}
datajson = JSON.stringify( datajson ); //converting to string here
like image 189
gurvinder372 Avatar answered Feb 18 '26 21:02

gurvinder372



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!