添加到数据库后停留在同一页面而不刷新它 [英] Staying in the same page without refreshing it after adding to database

查看:42
本文介绍了添加到数据库后停留在同一页面而不刷新它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有PHP网页,需要在其中插入一些信息到数据库中.插入完成后,它将刷新同一页面.但是有人告诉我,此过程不切实际,因为您每次都加载页面的所有 HTML CSS JS .我应该 AJAX 来做到这一点.

我搜索它,并尝试了以下代码:

  $(#insert").click(function(){//获取表单值var selectType = $('#selectW').val();var selectcom = $('#select_at').val();var pay = $('#pay').val();var facture = $('#facture').val();var selectcur = $('#select').val();//制作postdata//var postData ='username ='+ username +'& name ='+ name +'& brand ='+ brand;//在后台调用您的input.php脚本,当它返回时,如果请求成功,则调用成功函数;如果出现问题,则调用错误函数(例如404、500或任何其他错误状态)$ .ajax({网址:"insert.php",输入:"POST",数据:postData,成功:功能(数据,状态,xhr){//如果成功,则将文本输出到状态div,然后清除表单输入以准备新数据$(#section2").html(data);$('#pay').val('');$('#selectcur').val('');},错误:功能(jqXHR,状态,errorThrown){//如果失败则显示错误和服务器状态$(#section2").html('存在错误'+ errorThrown +',状态为'+ textStatus);}});//JavaScript文件 

这是我的 PHP-PDO 代码,在其中删除了 header 行,并用 echo("something"):

  if(isset($ _ POST ['insert'])){$ selectOpt1 = $ _POST ['currency'];if($ selectOpt1 =="9"){$ type = $ _POST ['type'];$ provider = $ _POST ['alfa_touch'];$ pay = $ _POST ['pay'];$ facture = $ _POST ['facture'];尝试{$ query =将销售插入(类型,提供者,工资,工厂,date_now,time_now)价值(:type,:provider,:pay,:facture,:date,now());$ stmt = $ conn-> prepare($ query);$ stmt-> bindValue(:type",$ type);$ stmt-> bindValue(:provider",$ provider);$ stmt-> bindValue(:pay",$ pay);$ stmt-> bindValue(:facture",$ facture);$ stmt-> bindValue(:date",date("y-m-d"));$ count = $ stmt-> execute();//header("location:home.php");回声(完成");}catch(PDOException $ e){echo $ e-> getMessage();//header("location:../pages/insert_false.php?id=".$projid);print_r($ conn-> errorInfo());}}} 

现在,当我单击插入按钮时,数据已正确添加到MySQL数据库,但是应用程序保留在insert.php中并回显 Done .我需要留在同一页面上.感谢您的帮助.

编辑

  $(#insert").click(function(){//获取表单值var selectType = $('#selectW').val();var selectcom = $('#select_at').val();var pay = $('#pay').val();var facture = $('#facture').val();var selectcur = $('#select').val();//制作postdatavar postData ='username ='+ username +'& name ='+ name +'& brand ='+ brand;//在后台调用您的input.php脚本,当它返回时,如果请求成功,则调用成功函数;如果出现问题,则调用错误函数(例如404、500或任何其他错误状态)$ .ajax({网址:"insert.php",输入:"POST",数据:postData,成功:功能(数据,状态,xhr){//如果成功,则将文本输出到状态div,然后清除表单输入以准备新数据$(#section2").html(data);$('#pay').val('');$('#selectcur').val('');},错误:功能(jqXHR,状态,errorThrown){//如果失败则显示错误和服务器状态$(#section2").html('存在错误'+ errorThrown +',状态为'+ textStatus);}});返回false;});//JavaScript文件 

还是同样的问题.这是我的HTML表单:

 < form name ="insertForm" action ="insert.php" method ="post">< tr>< td align ="center">< select id ="selectW" name ="type">< option value ="Choose"> Choose</option>< option value ="Dollars"> Dollars</option>< option value ="D& D"> D&D</option>< option value =卡片">卡片</option>< option value =电话">电话</option>< option value ="Acc"> Acc</option>< option value ="Bills"> Bills</option></select><!-< select><?php foreach($ result5 as $ rows){?>< option value =<?php echo $ rows ['item_name']?>"><?php echo $ rows ['item_name']?></option><?php}?></select>-></td>< td align ="center">< select id ="select_at" name ="alfa_touch">< option value =未定义">不需要</option>< option value ="Alfa"> Alfa</option>< option value ="Touch"> Touch</option></select></td>< td align ="center"><输入类型="text" id ="pay" name ="pay"/></td>< td align ="center"><输入类型="text" id ="facture" name ="facture"占位符=فيحالدفعالفواتيرعبرomt"/></td>< td align ="center">< select id ="select" name ="currency">< option value ="9"> LBP</option>< option value ="10">美元</option></select></td>< td align ="center"><输入类型="submit" id =插入" name =插入" value =插入"/></td></tr></form> 

解决方案

在您的 HTML 文件中,在<中具有 action ='insert.php'.form> 标记,并且您还要在具有 id insert button click 上调用一个函数./p>

两者都在做相同的事情-将值从 HTML 页面发送到 insert.php .如果< form> ,页面会刷新,因此请使用 ajax .保留 click 事件的脚本.

  1. < form> 标记中删除 action ="insert.php" method ="post" .
  2. < button> 标签中
  3. 更改 type ="button" .

希望这会有所帮助.

I have PHP web page where I need to insert some information to my database. When insert is done, it refresh the same page. But I've been told that this process is not practical because you are loading all HTML, CSS, and JS of your page every time. And I should you AJAX to do that.

I search for it, and tried this code:

$("#insert").click(function(){
 //get the form values
 var selectType = $('#selectW').val();
 var selectcom = $('#select_at').val();
 var pay = $('#pay').val();     
 var facture = $('#facture').val();     
 var selectcur = $('#select').val(); 

 //make the postdata
 //var postData = 'username='+username+'&name='+name+'&brand='+brand;

 //call your input.php script in the background, when it returns it will call the success function if the request was successful or the error one if there was an issue (like a 404, 500 or any other error status)

     $.ajax({
        url : "insert.php",
        type: "POST",
        data : postData,
        success: function(data,status, xhr)
        {
            //if success then just output the text to the status div then clear the form inputs to prepare for new data
            $("#section2").html(data);
            $('#pay').val('');
            $('#selectcur').val('');
        },
        error: function (jqXHR, status, errorThrown)
        {
            //if fail show error and server status
            $("#section2").html('there was an error ' + errorThrown + ' with status ' + textStatus);
        }
    });// JavaScript Document

And here is my PHP-PDO code where I removed the header lines and replaced them with echo("something"):

if(isset($_POST['insert'])){
    $selectOpt1 = $_POST['currency'];
    if($selectOpt1=="9"){
        $type = $_POST['type'];
        $provider = $_POST['alfa_touch'];
        $pay = $_POST['pay'];
        $facture = $_POST['facture'];
        try{
            $query = "INSERT INTO sales
            (type, provider, pay, facture, date_now, time_now) 
            VALUES
            (:type, :provider, :pay, :facture, :date, now())";
            $stmt = $conn->prepare($query);
            $stmt->bindValue(":type", $type);
            $stmt->bindValue(":provider", $provider);
            $stmt->bindValue(":pay", $pay);  
            $stmt->bindValue(":facture", $facture);
            $stmt->bindValue(":date", date("y-m-d"));
            $count = $stmt->execute();
            //header("location: home.php");
            echo ("Done");
        }
        catch(PDOException $e) {
            echo $e->getMessage();
            //header("location: ../pages/insert_false.php?id=".$projid);
            print_r($conn->errorInfo());

        }


    }
}

Now, when I click on insert button, the data are added correctly to MySQL database, but, the app stay in insert.php and echo Done. What I need is to stay in the same page. Any help is appreciated.

EDIT

$("#insert").click(function(){
 //get the form values
 var selectType = $('#selectW').val();
 var selectcom = $('#select_at').val();
 var pay = $('#pay').val();     
 var facture = $('#facture').val();     
 var selectcur = $('#select').val(); 

 //make the postdata
 var postData = 'username='+username+'&name='+name+'&brand='+brand;

 //call your input.php script in the background, when it returns it will call the success function if the request was successful or the error one if there was an issue (like a 404, 500 or any other error status)

 $.ajax({
    url : "insert.php",
    type: "POST",
    data : postData,
    success: function(data,status, xhr)
    {
        //if success then just output the text to the status div then clear the form inputs to prepare for new data
        $("#section2").html(data);
        $('#pay').val('');
        $('#selectcur').val('');
    },
    error: function (jqXHR, status, errorThrown)
    {
        //if fail show error and server status
        $("#section2").html('there was an error ' + errorThrown + ' with status ' + textStatus);
    }

});
return false;
});// JavaScript Document

Still the same problem. And here is my HTML form:

<form name="insertForm" action="insert.php" method="post">

    <tr>
        <td align="center">
          <select id="selectW" name="type">
            <option value="Choose">Choose</option>
            <option value="Dollars">Dollars</option>
            <option value="D & D">D & D</option>
            <option value="Cards">Cards</option>
            <option value="Phones">Phones</option>
            <option value="Acc">Acc</option>
            <option value="Bills">Bills</option>
          </select>
          <!--<select>
          <?php foreach($result5 as $rows){ ?>
            <option value="<?php echo $rows['item_name'] ?>"><?php echo $rows['item_name'] ?></option>
            <?php } ?>
          </select>-->
          </td>
        <td align="center"><select id="select_at" name="alfa_touch">
            <option value="Undefined">Not Required</option>
            <option value="Alfa">Alfa</option>
            <option value="Touch">Touch</option></select></td>
        <td align="center"><input type="text" id="pay" name="pay"/></td>
        <td align="center"><input type="text" id="facture" name="facture" placeholder="في حال دفع الفواتير عبر omt"/></td>
        <td align="center"><select id="select" name="currency">
            <option value="9">LBP</option>
            <option value="10">Dollars</option>
            </select></td>

        <td align="center"><input type="submit" id="insert" name="insert" value="insert" />

      </td>

      </tr>
      </form>   

解决方案

In your HTML file you have action = 'insert.php' in <form> tag and you are also calling a function on button click having id insert.

Both are doing the same thing - sending values from HTML page to insert.php. In case <form>, page gets refreshed so go for ajax. Keep the script for click event.

  1. Remove action="insert.php" and method="post" from <form> tag.
  2. Change type = "button" in <button> tag.

Hope this will help.

这篇关于添加到数据库后停留在同一页面而不刷新它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆