使用AJAX和PHP收集复选框值时出现问题

时间:2018-11-09 07:14:55

标签: php ajax checkbox

我正在处理具有复选框输入的表单。表单具有复选框输入字段,通过该字段,我可以根据是否选中复选框来动态更改值。当用户单击复选框时,值应更改为1,而当未单击时,该值应为零。我正在通过AJAX收集值并将其提交到后端(在PHP Laravel中构建),当我dd()的值我得到复选框的空值时,请提供帮助

包含复选框字段的布局

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LayoutPractice extends JFrame implements ActionListener {

    //Set up variables
    private JPanel graphic;
    private JPanel under;
    private JButton button;
    private JLabel text;
    private int clicks;

    /**
     * Constructor, sets up GUI
     * 
     */
    public LayoutPractice(){
        //Default JFrame setup
        super("Layout Practice");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Set up the graphic panel
        this.graphic = new JPanel();
        graphic.setPreferredSize(new Dimension(500, 500));

        //Set up the components that go under the graphic
        this.clicks = 0;
        this.button = new JButton("Click for dialog");
        this.text = new JLabel("No Clicks");

        //Set up the under panel, add in the button and label
        this.under = new JPanel();
        under.setLayout(new FlowLayout());
        under.add(button);
        under.add(text);

        //Tell it to react to the button being pressed
        button.addActionListener(this);

        //Set the panels onto the JFrame
        getContentPane().add(graphic, BorderLayout.CENTER);
        getContentPane().add(under, BorderLayout.PAGE_END);

        //Pack and set the JFrame to visible
        pack();
        setVisible(true);
    }

    /**
     * Paints the image displayed on graphic
     * 
     * @param A Graphics object to be worked on
     * 
     */
    public void paint(Graphics g) {
        //Assigns which panel to paint
        graphic.paint(g);
        //Set a color to pains
        g.setColor(Color.BLUE);
        //Use variables for a pattern
        int x = 0;
        int y = 0;
        //Loop for a pattern
        while (x <= 230) {
            //Generates a filled rectangle of the correct size
            g.fillRect(x, y, (500-(2 * x)), (500-(2 * y)));
            //Alternates color
            if (g.getColor() == Color.BLUE) {
                g.setColor(Color.ORANGE.darker());
            }
            else {
                g.setColor(Color.BLUE);
            }
            //Increase variables to reduce rectangle size
            x += 20;
            y += 20;
        }
    }

    /**
     * Tells the GUI what to do when the button is pressed
     * 
     * @param An ActionEvent, specifically the buton being pressed
     */
    public void actionPerformed(ActionEvent event) {
        //Increase the clicks variable
        clicks++;
        //Change/update the JLabel
        text.setText("Clicks: " + clicks);
        //Open a dialog using available tools
        JOptionPane.showMessageDialog(new JFrame(),
                ("Clicks: " + clicks),
                "Click Count",
                JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * Very simple main, makes a new LayoutPractice
     * 
     * @param args
     */
    public static void main(String[] args) {
        new LayoutPractice();
    }


}

更改复选框值的功能

 <div class="check-now {{ $errors->has('spouse') ? ' has-error' : '' }}" style="width: 100%;">
        <h1 class="cover-travel">I am travelling with</h1>
        <label class="spouse-me">
            <h1 class="pumba">Spouse</h1>
            <input type="checkbox" id="spouse" value="" class="spouse"  onClick="checkMark()">
        </label>
        @if ($errors->has('spouse'))
            <span class="help-block">
                <strong>{{ $errors->first('spouse') }}</strong>
            </span>
        @endif
    </div>

AJAX将数据提交到后端

 function checkMark() {
      var checkBox = document.getElementById("spouse");
      var text = document.getElementById("spouseDetail");

      // If the checkbox is checked, display the output text
      if (checkBox.checked == true){
        checkBox.value = '1';
      } else {
        checkBox.value = 'O';
      }
    }

处理AJAX调用的控制器

// Get the form via its id
    var form = $('#travel_form');

    $( "form" ).submit(function( event ) {
        event.preventDefault();
        //alert('clicked');


        //Fetch the value of spouse
        var spouse = $('#spouse').val();

        //Log in console tab am getting an empty value
        console.log(spouse);

        //Add in a JS object
        var type = {
            'spouse' : spouse 
        }

        $.ajax({
            type: "POST",
            url: "getplans",
            data:JSON.stringify(type),
            contentType: 'application/json',
            dataType: "json",
            success: function(response){
                window.location.href="getp" ;
            },
            //Alert errors from backend
            error: function(data) {
                var errors = '';
                for(datos in data.responseJSON){
                    errors += data.responseJSON[datos] + '\n';
                }
                alert(errors);
            }
        });
    });

1 个答案:

答案 0 :(得分:0)

您可以简化代码很多。如果只想通过复选框的状态,则只需要:

代替您的checkMark()函数,只需在Submit回调中进行检查即可。

// This will set the value 1 if it is checked and 0 if it isn't.
var checkBox = document.getElementById("spouse");
var type = {
    'spouse' : checkBox.checked ? 1 : 0 
}

// Don't stringify the object, just pass it as is. jQuery will take care if it.
$.ajax({
    ...
    data: type,
    ...