简体   繁体   中英

How Can I change json array values in php and send them to proper html fields using ajax

I want to take oracle sql query result data and modify them in php and finally send them to output them in different form fields using JQuery, AJAX.

Here is my php code:

<?php

$loanid      = (isset($_POST['loanid'])) ? $_POST['loanid'] : "not";
$loan_name   = (isset($_POST['loan_name'])) ? $_POST['loan_name'] : "not";
$description = (isset($_POST['description'])) ? $_POST['description'] : "not";
$amount      = (isset($_POST['amount'])) ? $_POST['amount'] : "not";
$datestring  = (isset($_POST['textdatetimepicker1'])) ? $_POST['textdatetimepicker1'] : "not";
$rate        = (isset($_POST['rate'])) ? $_POST['rate'] : "not";

echo "-starts: ";
echo $loanid;
echo $loan_name;
echo $description;
echo $amount;

$date_arr = explode('/', $datestring);
$date     = date("Y/m/d", strtotime($date_arr[2] . $date_arr[1] . $date_arr[0]));
echo $datestring;
echo $rate;
echo " ends. ";

$conn = oci_connect('himadri', 'himadri', 'cse.du.ac.bd/duais_test');
if (!$conn) {
    trigger_error("Could not connect to database", E_USER_ERROR);
} else {
    echo "<br>";
    echo "Connection established.";
}

$stid = oci_parse($conn, " begin  
                               :result := PKG_PAYROLL.save_loan_type(
                                            '<loan_type>
                                            <loan_id>$loanid</loan_id>                                        
                                            <loan_name>$loan_name</loan_name>
                                            <description>$description</description>
                                            <amount>$amount</amount>    
                                            <date>$date</date>
                                            <rate>$rate</rate>        
                                            </loan_type>'
                                            );                      

                                end;");

oci_bind_by_name($stid, ':result', $ru, 5000);
$output = oci_execute($stid);
echo "<br>";
echo " \n SQL Query Result: \n ";
echo $ru;
$string = $ru;
$xml    = simplexml_load_string($string);
$json   = json_encode($xml);
$array  = json_decode($json, TRUE);
echo json_encode($array);
?>

For example, if above query results returns json output like given below:

{"status":"success","loan_type":{"loan_id":"123","loan_name":"Bank Loan","description":"FRB Bank Loan","amount":"1250000","date":"2016-01-26","rate":"5.257"}}

I want change their values such as:

  • change "loan_id":"123" into "loan_id":"456"
  • change "loan_name":"Bank Loan" into "loan_name":"Loan 1" etc.

This my HTML and AJAX JQuery code:

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Record Loan Type Information</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="css/bootstrap.min.css">
      <script src="js/jquery-2.1.4.min.js"></script>
      <script src="js/bootstrap.min.js"></script>  
   </head>
   <body >
      <div class="container"  >
         <div class="panel-group">
            <div class="panel panel-primary"  >
               <div class="panel-heading" >
                  <h3 class="panel-title" style="text-align: center;">Record Loan Type Information</h3>
               </div>
               <div class="panel-body">
                  <form class="form-horizontal" >
                     <div class="form-group">
                        <label class="control-label col-sm-3"  for="acode">Loan ID:</label>
                        <div class="col-sm-5">
                           <input type="text" class="form-control" id="textloanid" name="loanid"  placeholder="Enter Loan ID">             
                           <span id="errmsg1" class="errmsg"></span>
                        </div>
                     </div>
                     <div class="form-group">
                        <label class="control-label col-sm-3" style="text-align:right;" >Loan Name:</label>
                        <div class="col-sm-5">
                           <input type="text" id="textloan_name" name="loan_name" class="form-control" placeholder="Enter Loan Name" >        
                        </div>
                     </div>
                     <div class="form-group">
                        <label class="control-label col-sm-3"  for="dcode">Description:</label>
                        <div class="col-sm-5">
                           <input type="text" class="form-control" id="textdescription" name="description" placeholder="Enter Loan Description">               
                        </div>
                     </div>
                     <div class="form-group">
                        <label class="control-label col-sm-3" style="text-align:right;">Amount:</label>
                        <div class="col-sm-5">
                           <input type="text"  id="textamount" name="amount" class="form-control" placeholder="Enter Amount" >        
                           <span id="errmsg2" class="errmsg"></span>
                        </div>
                     </div>
                     <div class="form-group">
                        <label class="control-label col-sm-3" style="text-align:right;" >Sanction Date:</label>
                        <div class="col-sm-5">
                           <div class="input-group date">
                              <span class="input-group-addon">
                              <span class="glyphicon glyphicon-calendar"></span>
                              </span>   
                              <input type="text"  id='textdatetimepicker1' name="textdatetimepicker1" class="form-control" placeholder="DD/MM/YYYY">       
                           </div>
                        </div>
                     </div>
                     <div class="form-group">
                        <label class="control-label col-sm-3" style="text-align:right;">Interest Rate:</label>
                        <div class="col-sm-5">
                           <input type="text" id="textrate" name="rate" class="form-control" placeholder="Enter Rate" >       
                        </div>
                     </div>
                     <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                           <button type="submit" id="btnSubmit" class="btn btn-primary">Save</button>
                           <button type="submit" name="editbtn" class="btn btn-success editbtn">Edit</button>
                           <button type="button" class="btn btn-danger">Delete</button>
                           <button type="button" class="btn btn-info">Exit</button> 
                        </div>
                     </div>
                  </form>
                  <!-- The result Serialize Text Output inside this div -->
                  <div id="serialize">Serialize Text Output: </div>
                  <!-- The result of the search will be rendered inside this div -->
                  <div id="result">Text Output: </div>
               </div>
            </div>
         </div>
      </div>
      <script type="text/javascript">
         var values = $("form").serialize();

         var i=0;
         $("form").on("submit", function( event ) {
            event.preventDefault();
            var values = $( this ).serialize();      
            $('#serialize').append(values);  
            $.ajax({
                url: "loan_type_info.php",
                type: "post",
                async:true,
                data: values,
                dataType: 'html',
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                success: function(data) {

                    $('#result').append('Response Data:');
                    $('#result').append(data);
                    $('#result').append('<br>');
                    $('#result').prop('loan_id', data.loan_id);
                },

                error: function(jqXHR, textStatus, errorThrown) {
                   console.log(textStatus, errorThrown);
                }
            });

         });            

      </script>
   </body>
</html>

In the above code, i want to paste json data into proper input fields such as:

  • on element with id="textloanid" paste data.loan_id [ is 456 comes from "loan_id":"456" ]
  • on element with id="textloan_name" paste data.loan_name [ is "Loan 1" comes from "loan_name":"Loan 1"]

Updates :

$('#result').append('Response Data:');
$('#result').append(data);
I got :Response Data:123 Bank Loan FRB Bank Loan 1250000 26/01/2016 12.25

$('#result').append('Response JSON parse:');
data=JSON.parse(data);
$('#result').append(data);  
I got :Response JSON parse: (nothing)

How i can do it.please help me on this code.Thanks

A follow up from the comments. After parsing the data from the server you can now access the values inside data and put them wherever you want.

success: function(data) {
    $('#result').append('Response Data:');
    $('#result').append(data);
    $('#result').append('<br>');
    data=JSON.parse(data); 
    $('#textloanid').val(data.loan_type.load_id);
    $('#textloan_name').val(data.loan_type.loan_name);
    $('#result').prop('loan_id', data.loan_type.loan_id);
}

Changing <input> tags without ajax using jQuery:

$('#textloanid').val("YOUR_DESIRED_OUTPUT");

Once you have your data after the query, create a new array and make a copy of each associative element in the original using a loop and once you see the element you wish to modify simply code the condition into the loop. When the loop is done, you have a fresh array that meets your specs. Also might want to unset the original after the copy is made to keep mem usage to a minimum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM