dougou8639 2015-09-19 19:26
浏览 65
已采纳

无法使用ajax传递值到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));
  • 写回答

2条回答 默认 最新

  • duandanbeng1829 2015-09-19 21:03
    关注

    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;
    
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败