Benjamin Robert
Benjamin Robert

Reputation: 81

Call PHP function with parameter onSubmit / onClick event

I have a PHP file containing a shop class, which has several static public functions like:

File : shop.php

And one of my function is :

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());

}

In another file (product file) I want to make a button, to handle this function, thank to an event on it.

So I am trying to call this PHP function insertProductIntoBasket($id, $quantity, $name) like this, with an event on a button:

File: product.php

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

I saw that Javascript is handled when the button is pressed, and there is a way to call a function with AJAX. But I definetly do not know how to pass parameters from my insertProductIntoBasket function.

Upvotes: 0

Views: 2392

Answers (3)

Noel Samuel
Noel Samuel

Reputation: 23

Use ajax to call product.php

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

and use $1 $2 etc to access passed values

Upvotes: 1

L.C. Echo Chan
L.C. Echo Chan

Reputation: 596

//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.

Upvotes: 0

mjdth
mjdth

Reputation: 6536

Just call the function from with your shop.php file. You can get the post variables and call the appropriate functions from there.

Upvotes: 0

Related Questions