简体   繁体   中英

Unable to pass value using ajax to php

I'm completely new to ajax. I want to pass my html form value to php and then get the output from that php page back in the html page

Ajax code

 $("#submit1").click(function(){
 var formData = $("#add-cart-form").serialize();

 $.ajax({
    type: 'POST',
    url: 'test.php',
    dataType : 'json',
    data: {
        'total_load' : $('#total_load').val(),
        'hours' : $('#hours').val(),
    },
     success: function (data) {
       alert(data)
     },
  });
 var result = $.parseJSON(output);
 alert(result[0]);
});

Relevant php code

$connected_load = $_POST['total_load'];  $no_of_hours = $_POST['hours'];


 echo json_encode(array(
     $connected_load, 
     $selected_inverter["model"], 
     $selected_inverter["voltage"], 
     $selected_inverter["type"],
     $no_of_hours,$selected_battery));

Your output variable is not defined at this point. Try to parse response in the callback success function:

success: function (data) {
     var result = $.parseJSON(data);
     console.log(result[0]);
}

IMHO, code has some inaccuracies. First of all, you're writing:

var formData = $("#add-cart-form").serialize();

...but you're not sending formData via $.ajax. Instead, you're sending other post data, specifically

{ 'total_load' : $('#total_load').val(), 'hours' : $('#hours').val(),}

...and there is an error inside this object, you have a comma just before the closing curly brace.

Anyway, this is the right way to do it (js)

$("#submit1").click(function(event){
    // perhaps formData form embrace "total_load" and "hours" ?
    var formData = $("#add-cart-form").serialize();

    $.ajax({
        url: 'test.php',
        cache: false, // optional
        async: true, // optional, defaults to true. False value will make ajax synchronous, hanging the browser.
        data: formData,
        type: 'post',
        dataType : 'json'
    }).done(function(d){ // trying to simplify comprehension of the console.log output, below...
        console.log(d.d_connected_load);
        console.log(d.d_model);
        console.log(d.d_voltage);
        console.log(d.d_type);
        console.log(d.d_no_of_hours);
        console.log(d.d_selected_battery);
    }).fail(function(j,s,e){
        console.warn(j.responseText);
    });

});

and, PHP side:

<?php
    $connected_load = $_POST['total_load'];
    $no_of_hours = $_POST['hours'];

    # stuffs here for sanitizing $_POST and working on $selected_inverter["model"], $selected_inverter["voltage"], $selected_inverter["type"], $selected_battery

 echo json_encode(
    array(
        "d_connected_load" => $connected_load, 
        "d_model" => $selected_inverter["model"], 
        "d_voltage" => $selected_inverter["voltage"], 
        "d_type" => $selected_inverter["type"],
        "d_no_of_hours" => $no_of_hours,
        "d_selected_battery" => $selected_battery
        )
    );

You do not need to parse JSON. jQuery will do it for you when you make an ajax call specifying dataType:'json' in the ajaxcall options (and, obviously, the json echoed from php must be well-formed).

Note, in addition, the way the ajax call is written. In latest releases of jQuery the best is to use .done() and .fail() promise methods instead of success and fail . -> http://api.jquery.com/jquery.ajax/

UPDATE: STEP BY STEP EXAMPLE:

I'll try to make it more understandable. Initial steps:

  • create a file named form.php;
  • create a file named ajax_test.php;
  • create a file named test.js;

...in the same directory.

====== FILE FORM.PHP ======
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
    <form id="add-cart-form" method="post">
        <p>TOTAL LOAD: <input type="text" value="total load" name="total_load" /></p>
        <p>TOTAL LOAD: <input type="text" value="hours!" name="hours" /></p>
        <hr />
        <button type="submit" id="submit1">SUBMIT</button>
    </form>
</body>
<script type="text/javascript" src="js/test.js"></script>
</html>


====== FILE AJAX_TEST.PHP ======
<?php
    $connected_load = $_POST['total_load'];
    $no_of_hours = $_POST['hours'];

    # stuffs here for sanitizing $_POST and working on $selected_inverter["model"], $selected_inverter["voltage"], $selected_inverter["type"], $selected_battery

 echo json_encode(
    array(
        "d_connected_load" => $connected_load, 
        "d_model" => $selected_inverter["model"], 
        "d_voltage" => $selected_inverter["voltage"], 
        "d_type" => $selected_inverter["type"],
        "d_no_of_hours" => $no_of_hours,
        "d_selected_battery" => $selected_battery
        )
    );


====== FILE TEST.JS ======

$("#submit1").click(function(event){
   // perhaps formData form embrace "total_load" and "hours" ?
    var formData = $("#add-cart-form").serialize();

    $.ajax({
        url: 'ajax_test.php',
        cache: false, // optional
        async: true, // optional, defaults to true. False value will make ajax synchronous, hanging the browser.
        data: formData,
        type: 'post',
        dataType : 'json'
    }).done(function(d){ // trying to simplify comprehension of the console.log output, below...
        console.log(d.d_connected_load);
        console.log(d.d_model);
        console.log(d.d_voltage);
        console.log(d.d_type);
        console.log(d.d_no_of_hours);
        console.log(d.d_selected_battery);
    }).fail(function(j,s,e){
        console.warn(j.responseText);
    });

    event.preventDefault();
    event.stopImmediatePropagation();
    return false;

});

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