lundi 2 février 2015

wordpress use single ajax in place of multiple ajax requests in a smarter way


In wordpress I have database tables like this



product name

id product_name

1 A
2 B
3 C
4 D

product_buying_price

id product_name product_buying_price
1 A 10
2 B 12
3 C 15
4 D 18

product_selling_price

id product_name product_selling_price
1 A 12
2 B 13
3 C 19
4 D 23


So I have a dropdown like this



<select name="product_name" id="product_name">
<option value="">Products</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>


and I want to show the values for product buying price and product selling price inside a table like this



<table>
<tr>
<td>
<select name="product_name" id="product_name">
<option value="">Products</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</td>
<td class="product_buying_price"></td>
<td class="product_selling_price"></td>
</tr>
</table>


Like this I have more around 3-4 such fields and I want to get those values for the product.


In the js file I have made the ajax like this



$('body').on('change','#product_name', function() {
var selected = $(this).val;

//Get product buying price
$.post( test.ajaxUrl, { 'selected' : selected, 'action' : 'get_product_buying_price' }, function(data){
data = $.parseJSON(data);
selected.find('td.product_buying_price').html(data);
});

//Get product selling price
$.post( test.ajaxUrl, { 'selected' : selected, 'action' : 'get_product_selling_price' }, function(data){
data = $.parseJSON(data);
selected.find('td.product_selling_price').html(data);
});
});


Inside function I have the function like this



function get_product_buying_price() {
global $wpdb;
$selected_product = $_POST['selected'];
$get_product_price = $wpdb->get_row("SELECT `product_buying_price` FROM `product_buying_price` WHERE `product_name` = '.$selected_product.' ");
$product_buying_price = $get_product_price->product_buying_price;
echo json_encode($product_buying_price);
exit;
}

function get_product_selling_price() {
global $wpdb;
$selected_product = $_POST['selected'];
$get_product_price = $wpdb->get_row("SELECT `product_selling_price` FROM `product_selling_price` WHERE `product_name` = '.$selected_product.' ");
$product_selling_price = $get_product_price->product_selling_price;
echo json_encode($product_selling_price);
exit;
}


Here its working fine. But don't you think that doing multiple ajax request on one click makes it slow? I have around 3-4 request for one change. So can someone tell me some smarter way to achive this? Any help and suggestions will be really appreciable. Thanks.





Aucun commentaire:

Enregistrer un commentaire