使用ajax从Javascript函数调用Php函数

Hello everyone I am new to php. I have been trying out this thing when a user enter a product name need to validate that the product is valid or not. For that purpose I have used onchange event when the text is entered.The onchange function will call the javascript function.From javascript function I am calling the php which is in the same file.So when I am entering the product name somehow the php function is not working.

Here is my code :

<?php
  include 'conf.php';//it contains the php database configuration
   session_start();

   $quantityRequired=0; 
   $productName_error="";
    if(is_ajax()){
      if(isset($_POST["productName"])){
        $productName=$_POST["productName"];
        $row=mysqli_query($conn,"SELECT * from OrderDetails where ProductName='".$productName."'");
        if($row)
        {
          $result=mysqli_fetch_assoc($row);
          $quantityRequired=$result["Quantity"];
        }   
        else
         {
          $productName_error="The product name is not valid or product does not exist";
          echo $productName_error;
         }  
      }
    } 
  function is_ajax() {
    $flag=(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'); 
    return $flag;
  }
?>
<html>
   <head>
       <title>Order Page </title>
       <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
   </head>
   <body>
      <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
         <label for="userName">Username</label><br>
         Product Name<input type="text" name="productName" id="productName" onchange="validateProduct()"><?php echo $productName_error?><br>
         Quantity Required<input type="text" name="quantityRequired" id="quantityRequired"><br>
         Availability<input type="text" name="availability">
         <p id="demo"></p>
      </form>
      <script>
        function validateProduct()
        {
            $.ajax({
             type: "POST"
         });

        }
      </script>
   </body>  
</html> 

so the code is when the user enters the product name.The function validate product is called.From validate product it will call the php which is in the same file. is_ajax() function is used to check whether it is the ajax request or not.

3个回答



可能还有其他问题我没有发现,但第一件事是我的服务器端代码运行 有条件地:</ p>

  if(isset($ _ POST [“productName”]))
</ code> </ pre>

那个条件是 永远不满意,因为你没有在AJAX请求中发送任何值:</ p>

  $ .ajax({
type:“POST”
});
</ 代码> </ pre>

发送您正在寻找的值:</ p>

  $ .ajax({
type:“POST “,
data:{productName:$('#productName')。val()}
});
</ code> </ pre>

您可能还需要指定一个 如果他们没有正确默认,可以选择其他选项。 在许多情况下,显式代码通常比隐式更好:</ p>

  $ .ajax({
url:'yourUrl.php',
type:“POST”,
dataType:'html',
data:{productName:$('#productName')。val()}
});
</ code> </ pre>

一般来说你 我可能想检查 $。ajax()</ code>的文档,看看你能做什么,应该告诉它。 您还需要查看浏览器的调试工具,以便更详细地了解测试这些内容时失败的原因和方法。</ p>

说到您应该做的事情,您应该阅读< a href =“http://php.net/manual/en/security.database.sql-injection.php”rel =“nofollow noreferrer”>这个和这个。 您的代码目前对SQL注入攻击持开放态度,这基本上意味着您执行代码</ em>您的用户发送给您的任何内容。</ p>
</ div>

展开原文

原文

There may be other problems I haven't spotted, but the first thing that jumps out to me is that your server-side code runs conditionally:

if(isset($_POST["productName"]))

And that condition was never satisfied because you didn't send any values in the AJAX request:

$.ajax({
    type: "POST"
});

Send the value(s) you're looking for:

$.ajax({
    type: "POST",
    data: { productName: $('#productName').val() }
});

You may also need to specify a couple other options if they don't default correctly. Explicit code is generally better than implicit in many cases:

$.ajax({
    url: 'yourUrl.php',
    type: "POST",
    dataType: 'html',
    data: { productName: $('#productName').val() }
});

In general you'll probably want to check the documentation for $.ajax() and see what you can and should tell it. You'll also want to take a look at your browser's debugging tools to see more specifically why and how it fails when testing these things.

Speaking of things you should do, you should read this and this. Your code is wide open to SQL injection attacks at the moment, which basically means that you are executing as code anything your users send you.

doolo00026
doolo00026 好的David我会做更多的调试并分享结果。谢谢你的帮助
接近 4 年之前 回复
douyun3022
douyun3022 “这不起作用”并没有真正说出这个问题。 你将不得不做至少一些调试,没有人可以为你做这件事。
接近 4 年之前 回复
douao3063
douao3063 我尝试删除is_ajax()但是它也没有用。
接近 4 年之前 回复
dtcyv3985
dtcyv3985 什么让你有那个想法? 你做了什么调试来确认? 我怀疑你真的不需要is_ajax()函数。 只需将您的AJAX代码放入其自己的页面并假设一个AJAX请求。 每个服务器端资源都应该处理自己的职责,而不是将多个不同的资源组合到一个带有一堆if语句的页面中。
接近 4 年之前 回复
dsgft1486
dsgft1486 我已经完成了更改,但后来代码也没有工作。我认为is_ajax()函数导致问题。
接近 4 年之前 回复



用于Ajax的PHP库</ strong> </ p>

Jaxon是一个开源的 用于轻松创建Ajax Web应用程序的PHP库。 它允许进入一个网页,直接对PHP类进行Ajax调用,然后更新其内容,而无需重新加载整个页面。</ p>

Jaxon实现了一整套PHP函数来定义 网页的内容和属性。 有几个插件可以扩展其功能并提供与各种PHP框架和CMS的集成。</ p>

Jaxon是如何工作的</ strong> </ p>

使用Jaxon定义和注册PHP类。</ p>

  $ jaxon-&gt; register(Jaxon :: CALLABLE_OBJECT,new MyClass); 
</ code> </ pre> \ n

使用Jaxon生成的javascript代码调用您的类。</ p>

 &lt; input type =“button”onclick =“JaxonMyClass.myMethod()”/&gt  ; 
</ code> </ pre>

检查链接 https:/ /www.jaxon-php.org/docs.html </ p>
</ div>

展开原文

原文

A PHP library for Ajax

Jaxon is an open source PHP library for easily creating Ajax web applications. It allows into a web page to make direct Ajax calls to PHP classes that will in turn update its content, without reloading the entire page.

Jaxon implements a complete set of PHP functions to define the contents and properties of the web page. Several plugins exist to extend its functionalities and provide integration with various PHP frameworks and CMS.

How does Jaxon work

Define and register your PHP classes with Jaxon.

$jaxon->register(Jaxon::CALLABLE_OBJECT, new MyClass);

Call your classes using the javascript code generated by Jaxon.

<input type="button" onclick="JaxonMyClass.myMethod()" />

check link https://www.jaxon-php.org/docs.html



  var data1 =“Something”; 
$ .ajax({
url:“script.php”,
n type:“POST”,
data:{data1:data1}
})。done(function(resp){
console.log(resp)
})。fail(function(jqXHR,textStatus){

提醒(“请求失败:”+ textStatus +“ - 请再试一次。”)
})
</ code> </ pre>

这里有一个脚本可以发送 data1变量到php脚本。 完成部分中的resp是您从php脚本发回的返回。</ p>

如果要发送更多数据,只需添加 {data1:data1,data2:data2} </ code>等等。</ p>

只需调整以满足您的需求。</ p>
</ div>

展开原文

原文

var data1 = "Something";
$.ajax({
    url: "script.php",
    type: "POST",
    data: { data1: data1 }
}).done(function(resp) {
    console.log( resp )
}).fail(function(jqXHR, textStatus) {
    alert("Request failed: " + textStatus + " - Please try again.")
})

Here you have a script that will send the data1 variable across to the php script. The resp in the done portion is the return you send back from the php script.

If you want to send more data just add it { data1: data1, data2: data2 } and so on.

Just adjust to suit your needs.

duanfu1942
duanfu1942 我已经完成了更改,但它没有工作。我认为is_ajax()不起作用
接近 4 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐