0

In my ajax, the PHP side contains an array with 3 values. I'd like to put these 3 values into separate input fields. How can I do this? How do I access the array sent from PHP?

My code so far:

PHP

    $total['tot1'] = $numwelds + $numconwelds + $mpcountrys ;
    $total['tot2'] = $numwelds + $numconwelds + $fortot2 ;
    $total['tot3'] = $numwelds + $numconwelds + $fortot2 / $fortot3; 
    $response = json_encode($total);
    header("Content-Type: application/json");  
    echo $response;
    exit;

Jquery

 jQuery(document).ready( function($) {
        (function($) {
        $(document).ready(function(){
           $('#formsubmit').click(function(){
          $.post(
          PT_Ajax.ajaxurl,
                {
               action : 'ajax-inputtitleSubmit',
               numberofwelds : $('input[name=numberofwelds]').val(),
               numberofconwelds : $('input[name=numberofconwelds]').val(),
               nextNonce : PT_Ajax.nextNonce
                },
          function( response ) {
              $("#totalone").val(response);
               $("#totaltwo").val(response);
                $("#totalthree").val(response);
                }
                );
              return false;
        }); 

        });
        })(jQuery);
        });
2
  • 1
    Your jQuery is oddly nested. You're already in a document.ready, and you open another document.ready inside an IIFE? You should get rid of jQuery(document).ready( function($) { (function($) {, everything before $(document).ready. Commented Mar 25, 2014 at 18:32
  • possible duplicate of Accessing the Object values inside an array Commented Mar 25, 2014 at 18:36

2 Answers 2

0

You can use JSON.parse to convert json to object:

var obj = JSON.parse(response);
$("#totalone").val(obj.tot1);
$("#totaltwo").val(obj.tot2);
$("#totalthree").val(obj.tot3);

Or you can also use $.parseJSON() of jQuery.

Sign up to request clarification or add additional context in comments.

Comments

0

use like

$("#totalone").val(response["tot1"]);
$("#totaltwo").val(response["tot2"]);
$("#totalthree").val(response["tot3"]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.