简体   繁体   English

我需要帮助,无需使用表单即可使用Ajax,PHP和mySQL将信息发送到服务器

[英]I need help sending information to my server using Ajax, PHP, and mySQL without using a form

All of the tutorials I've looked up only show how to everything works using forms. 我查找的所有教程仅展示了如何使用表单进行所有工作。 I want to avoid using a form. 我想避免使用表格。 Right now i have the code for Javascript to map my answering based on what's clicked and make array thats shown in a alert. 现在,我有了Javascript代码,可以根据单击的内容映射我的答案,并在警报中显示数组。 (in the end i don't want it to be in a alert but im keeping it in there until i know everythings working) but I think i have the ajax sending the info to the server but i'm not sure if its working. (最后,我不希望它处于警报状态,而是将其保持在该状态,直到我知道一切正常为止),但是我认为我已经将ajax发送信息到服务器,但是我不确定它是否在工作。 Or how to have php take the ajax information and send it to the server. 或如何让php获取Ajax信息并将其发送到服务器。 My server is also connected fine. 我的服务器也连接正常。 I'm posting all of my current code. 我正在发布所有当前代码。 Any help is appreciated. 任何帮助表示赞赏。 Even if you just send me a link or point me in the right direction that would be great. 即使您只是给我发送了一个链接或为我指明了正确的方向,那也很棒。

I think my biggest question is how to take the array generated in Javascript then call in in Ajax, then Php. 我认为我最大的问题是如何使用Javascript中生成的数组,然后在Ajax中调用,然后在Php中调用。 since i already made the array what do i call in the Ajax. 因为我已经制作了数组,所以我在Ajax中称之为什么。 then how to treat it with a PDO 那么如何用PDO治疗

current jsfiddle 当前的jsfiddle

<?php
    include_once('database.php');
    $name = $_POST['name'];
    $choices = $_POST['answers'];
    if(mysql_query("INSERT INTO answers VALUES('$name', '$choices')"))
     echo "Successfully Inserted";
    else
    echo "Insertion Failed";?>

jQuery jQuery的

 $(document).ready(function() {


   $(function() {
     //catch this values, because you will use these for more than one time
     var answers = [];

     function getAnswers() {
         answers = []; //empty old answers so you can update it
         $.map($('.on'), function(item) {
           answers.push($(item).data('value'));
         });
       }
       //init the answers in case you use it before click
     getAnswers();


     $(document).on('click', 'img', function(e) {
       e.preventDefault();
       $(this).toggleClass('on');

       //trigger the state change when you click on an image
       $(document).trigger('state-change');
     });

     //get answers when event was triggered
     $(document).on('state-change', function(e) {
       getAnswers();
     });

     $('#btn-show').click(function() {
       alert(answers.join(',') || 'nothing was selected');
     });

   });
 });

CSS 的CSS

#seasoning {
  margin: 8px;
  font-size: 16px;
  height: 100px;
  width: 100px;
}
/* this shows the user which item has been selecting along with making a searchable class for the program */

.on {
  padding: 10px;
  background-color: red;
}

HTML 的HTML

<html>

<head>
  <LINK REL=StyleSheet HREF="code.css" TYPE="text/css">
  <script type="text/javascript" src="javascript.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>
  <form>
    Name:
    <input type="text" name="name">
  </form>
  <img src="https://i.imgur.com/7HyU4yh.jpg" id="seasoning" data-value="0">
  <br>
  <img src="https://i.imgur.com/OEHCjCK.jpg" id="seasoning" data-value="1">
  <br>

  <button id="btn-show">Submit</button>
</body>

</html>

Absolutely: 绝对:

//    $(document).on("eventOfYourChoice", function() {
// you probably actually want to do:
 $('#btn-show').click(function() {
    $.ajax({
        type: "POST",
        url: "/path/to/script.php",
        data: { 
            "name" : $('input[name="name"]').val(),
            "answers" : answers
        },
        success: function(response){
            alert(response);
    }
    }); 

}); 

the response variable contains whatever your PHP echoes out -- response变量包含您的PHP回显的所有内容-

However, there are a couple of things to note in the code you posted - 但是,您发布的代码中有两点需要注意-

1). 1)。 Filter & Validate your input: 过滤并验证您的输入:

if (is_string($_POST['name']){

$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);

} else { die("That input is not valid"); }

2). 2)。 Use mysqli_* functions or PDO --- or, you could use an ORM/DBA like idiorm 使用mysqli_ *函数或PDO ---或者,你可以使用像一个ORM / DBA idiorm

3). 3)。 In your JS - $(document).ready(function(){... and $(function() are the same thing. you only really need one. 在您的JS中- $(document).ready(function(){...$(function()是同一件事,您只需要一个。

4). 4)。 You almost ALWAYS want to include jQuery before any other scripts-- but you don't have to unless your javascript.js contains jQuery code (ie anything that begins 你几乎总是需要的任何其他scripts--之前,包括jQuery的,但你没有 ,除非你的javascript.js包含jQuery代码(即任何开始

---edit---- - -编辑 - -

I missed the "answer" value, earlier - but, since you have images, I'm assuming you want to do something along these lines: 我早些时候错过了“ answer”值-但是,由于您有图片,因此我假设您想按照以下步骤进行操作:

Hope this helps -! 希望这可以帮助 -!

You can just use ajax without using a form . 您可以只使用ajax而不使用form。 suppose your index.php is as below 假设您的index.php如下

  <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>

        <input type="text" id="name">
        <input type="submit" id="submit" value="submit">

      <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script type="text/javascript">

       $(document).ready(function(){

        var name = $('#name').val();

        $('#submit').click(function(){

         $.post('validate.php', {name:name}, function(data){

           alert(data);
        });

       });  

      });

    </script>

    </body>
    </html>

Now create the validate.php file, code there will be something like 现在创建validate.php文件,代码将类似于

if(isset($_POST['name'])){
  //do things with database

   if(//success){

     echo "success";
   }else{
     echo "failure";
   }

}

The output of this page will be alerted in index.php 该页面的输出将在index.php中发出警报

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Ajax将信息发送到PHP脚本 - Sending Information to a PHP Script using Ajax 需要有关使用PDO在PHP中更新表单的帮助 - Need an help for Updating a form in PHP using PDO 需要使用帮助将表单数据发送到电子邮件地址 - Need help sending form data to an e-mail address using 需要帮助发送数据并在服务器中访问它。 我想用JavaScript(nodejs)做到这一点 - Need help sending data and accessing it in the server. I want to do this using JavaScript(nodejs) 如何使用ajax获取文本区域数据(文本区域中的Html文件)我需要将数据发送到Php? Ajax没有发送我的文本区域数据? - How To get Text Area Data (Html File in Text area) using ajax And i need to send data to Php ? Ajax not sending my Text area data? 使用Ajax,PHP,MYSQL更新表单 - Update form using Ajax, PHP, MYSQL 需要帮助使用php,ajax,javascript将数据插入数据库 - Need help inserting data to database using php,ajax,javascript 使用ajax将表单发布到php而不刷新 - Using ajax to post a form to php without refresh 如何让我的 html 电子邮件表单在发送到 php 脚本进行发送之前使用 javascript 进行验证 - How to I get my html email form to validate using javascript before sending it to the php script for sending 使用POST方法将json发送到php服务器时需要帮助 - Help required in sending json to php server using POST method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM