如果值大于0,则使用AJAX或XMLHttprequest将数据保存到MySQL数据库中

时间:2022-09-27 16:28:46

I have a form separated in three parts. Each part is dynamic and populated by data from database. For example, every item saved in database can be shown in form as input only if its status is 1. Also, together with selected data my PHP script generates buttons with + and - javascript function as shown in this fiddle

我有一个分为三个部分的表格。每个部分都是动态的,并由来自数据库的数据填充。例如,保存在数据库中的每个项目只有在其状态为1时才能以表格形式显示。另外,与所选数据一起,我的PHP脚本生成带有+和 - javascript函数的按钮,如此小提琴所示

The problem that I don't know how to resolve is how to save name and value for each input where value is greater than 0. I was wandering if some of this two javasripts are usable for resolving my problem?

我不知道如何解决的问题是如何为值大于0的每个输入保存名称和值。如果这两个javasripts中的一些可用于解决我的问题,我就徘徊了?

Script 1, see this jsfiddle:

脚本1,看到这个jsfiddle:

$('forma').submit(function(){    
    $('.qty').each(function(){ 
        if($(this).val() != '0')
        {
            $('output').text($('output').text()+ ' ' + $(this).attr('name') + ' ' + $(this).val()+ ';' );
        }
    });
    return false;
});

Script 2:

var inputs = document.getElementById('forma').children;
var data = {};
for(var i in inputs ){
    if(inputs[i].value != 0)data[inputs[i].name] = inputs[i].value;
}

save.php file example:

save.php文件示例:

<?php

 mysql_connect("localhost", "root", "") or die(mysql_error()); 
 mysql_select_db("article_db") or die(mysql_error());


 $sql="INSERT INTO article (order)
 VALUES ('".$_POST['output']."')";

 $save = mysql_query($sql);

 mysql_close();

?>

Script 3:

$(document).ready(function() {
        $('#forma').submit(function(e){
        e.preventDefault();    
        $('.qty').each(function(){ 
           if($(this).val() != '0')
             {
                $('#output').text($('#output').text()+ ' ' + $(this).attr('name') + ' ' + $(this).val()+ ';' );
             }
          });
          var e=$(this);
          var output = document.getElementById('#output');
          var out = $(e).val();
                $.ajax({
                        type: "POST",
                        url: "save.php",
                        dataType: "json",                        
                        data: "out="+out,
                        success: function(response) {
                                if (response.ok){
                                        alert("Saved: " + response)

                                }else{
                                        alert(response.error);
                                }
                        },
                        error: function(){
                                alert("This won't gonna work like that!");
                        }
                });
        });
 });

and save.php:

<?php

 mysql_connect("localhost", "root", "") or die(mysql_error()); 
 mysql_select_db("caffe") or die(mysql_error());

 if(isset($_POST['forma'])){
 $sql="INSERT INTO narudzbe(narudzba) VALUES ('".$_POST['output']."')";

 $save = mysql_query($sql);
 }

 mysql_close();


?>

I am getting from first part of script 3 result on the page, but it won't save into database.

我从页面的第一部分脚本3得到结果,但它不会保存到数据库中。

If they are, how can I do that? I have never used AJAX or XMLHttprequest for saving data into database before, only pure PHP. I need to mention that I also use jquerymobile for this project. I know that mysql_connect and mysqli_connect are deprecated, but this is only for exercise.

如果是,我该怎么办?我之前从未使用AJAX或XMLHttprequest将数据保存到数据库中,只使用纯PHP。我需要提一下,我也在这个项目中使用jquerymobile。我知道不推荐使用mysql_connect和mysqli_connect,但这仅适用于练习。

Thank you in advance.

先感谢您。

2 个解决方案

#1


0  

This may help you a bit ...

这可能对你有所帮助......

$.ajax({
      url: '/path/to/file',
      type: 'default GET (Other values: POST)',
      dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
      data: {param1: 'value1'},
    })
    .done(function() {
      console.log("success");
    })
    .fail(function() {
      console.log("error");
    })
    .always(function() {
      console.log("complete");
    });

Now.. What i usaly do when i use Ajax i create a ajax.php and inside I use isset condition... like this

现在..当我使用Ajax的时候我会做什么我创建一个ajax.php并在里面我使用isset条件...像这样

if(isset($_POST['submitForm'])){
#php code
}

so in the $.ajax in data: you have to put your isset variable like so :

所以在数据的$ .ajax中:你必须像这样放置你的isset变量:

data: {submitForm: TRUE,otherdate:data}, //this is still javascript side

Then in the php side if you want to have access to the data used depending on the type you set you can get them as :

然后在php端如果你想根据你设置的类型访问所使用的数据,你可以得到它们:

$_GET['otherdate'] OR $_POST['otherdate']

Hope this help you!

希望这对你有所帮助!

#2


0  

I have managed solution to my problem thanks to Sebastiens hint by shown below:

由于Sebastiens的提示,我已经为我的问题提供了解决方案,如下所示:

javascript:

$(document).ready(function(e) {
$("#posalji").click(function() {

var dataType = document.getElementById("dataType").value;
var output = document.getElementById("output").value;
var status = document.getElementById("status").value;
$.ajax({
        type: "POST",
        url: "save.php",
        data: {dataType: dataType, output: output, status: status}
       })
    });
});    

and PHP file:

和PHP文件:

<?php

 $dataType = $_POST['dataType'];
 $output = $_POST['output'];
 $status = $_POST['status'];

 mysql_connect("localhost", "root", "") or die(mysql_error()); 
 mysql_select_db("caffe") or die(mysql_error());


 $sql="INSERT INTO narudzbe (sto, narudzba, status) VALUES ('$dataType', '$output', '$status')";

 $save = mysql_query($sql);


 mysql_close();

 header('Location: index.php');


?>

Thank you Sebastien, thank you again.

谢谢Sebastien,再次感谢你。

#1


0  

This may help you a bit ...

这可能对你有所帮助......

$.ajax({
      url: '/path/to/file',
      type: 'default GET (Other values: POST)',
      dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
      data: {param1: 'value1'},
    })
    .done(function() {
      console.log("success");
    })
    .fail(function() {
      console.log("error");
    })
    .always(function() {
      console.log("complete");
    });

Now.. What i usaly do when i use Ajax i create a ajax.php and inside I use isset condition... like this

现在..当我使用Ajax的时候我会做什么我创建一个ajax.php并在里面我使用isset条件...像这样

if(isset($_POST['submitForm'])){
#php code
}

so in the $.ajax in data: you have to put your isset variable like so :

所以在数据的$ .ajax中:你必须像这样放置你的isset变量:

data: {submitForm: TRUE,otherdate:data}, //this is still javascript side

Then in the php side if you want to have access to the data used depending on the type you set you can get them as :

然后在php端如果你想根据你设置的类型访问所使用的数据,你可以得到它们:

$_GET['otherdate'] OR $_POST['otherdate']

Hope this help you!

希望这对你有所帮助!

#2


0  

I have managed solution to my problem thanks to Sebastiens hint by shown below:

由于Sebastiens的提示,我已经为我的问题提供了解决方案,如下所示:

javascript:

$(document).ready(function(e) {
$("#posalji").click(function() {

var dataType = document.getElementById("dataType").value;
var output = document.getElementById("output").value;
var status = document.getElementById("status").value;
$.ajax({
        type: "POST",
        url: "save.php",
        data: {dataType: dataType, output: output, status: status}
       })
    });
});    

and PHP file:

和PHP文件:

<?php

 $dataType = $_POST['dataType'];
 $output = $_POST['output'];
 $status = $_POST['status'];

 mysql_connect("localhost", "root", "") or die(mysql_error()); 
 mysql_select_db("caffe") or die(mysql_error());


 $sql="INSERT INTO narudzbe (sto, narudzba, status) VALUES ('$dataType', '$output', '$status')";

 $save = mysql_query($sql);


 mysql_close();

 header('Location: index.php');


?>

Thank you Sebastien, thank you again.

谢谢Sebastien,再次感谢你。