使用参数onSubmit / onClick事件调用PHP函数

时间:2014-01-14 09:32:24

标签: php ajax function button call

我有一个包含shop类的PHP文件,它有几个静态公共函数,如:

  • createBasket()
  • getProductNameFromId()
  • ...

档案:shop.php

我的一个功能是:

static public function insertProductIntoBasket($id, $quantity, $name)

{ 
$basket = self::createBasket(); // We create the basket in another function if not exist before handling a product for a basket.

$query = mysql_query("INSERT INTO myTable(id_order, id_product, quantity_product, file_name)
VALUES('".$basket['id_order']."', '".$id."', '".$quantity."', '".$name."')

;") or die($query.' '.mysql_error());

}

在另一个文件(产品文件)中,我想创建一个按钮,以处理此功能,感谢上面的事件。

所以我试图像这样调用这个PHP函数insertProductIntoBasket($id, $quantity, $name),按钮上有一个事件:

文件:product.php

<form name="addProduct" method="post" action="shop.php">
   <input type="submit" value="Add to basket" name="pdt_basket"/>
</form>

我看到按下按钮时会处理Javascript,并且有一种方法可以使用AJAX调用函数。但我绝对不知道如何从insertProductIntoBasket函数传递参数。

3 个答案:

答案 0 :(得分:0)

只需使用shop.php文件调用该函数即可。您可以获取post变量并从那里调用相应的函数。

答案 1 :(得分:0)

//Before you use ajax, you have to know how to pass(POST) parameter first,
//The following is a simple example

/*In product.php
* if you want to send parameter from this page,
* just create more input field within the form
* then the form will "POST" those parameter to shop.php
*/

<form name="addProduct" method="post" action="shop.php">
   <input name="id_order" type="text" value="1" />
   <input name="id_product" type="text" value="1" />
   <input type="submit" value="Add to basket" name="pdt_basket"/>
</form>

/*In : shop.php
*you can get those parameter by using $_POST['input_name']
*the following is the example to get the id_order and id_product send from product.php
*/

$id_order = $_POST['id_order'];
$id_product = $_POST['id_product'];

/* Then you can try to call function inside shop.php will calling function directly */
insertProductIntoBasket($para);

//You may not need AJAX in this case, I will update my answer if you require for it.

答案 2 :(得分:0)

使用ajax调用product.php

function blah() { $.ajax({ url: 'product.php?arg1=val1&arg2=val2&arg3=val3' }); }

并使用$ 1 $ 2等来访问传递的值