I am trying to cross check some values with what I have in the database before letting those data go any further.
I have a form and in this form I am post
pid, Name, size, category and qty.
I have a validation already for the qty
.
In those data I am posting I am using those to find the price in the database
. I AM NOT POSTING THE PRICE.
Because I am using those post data to find the price someone might want to mess about with them for an example change the category or size value to whatever. If they do this, it will still get posted and the page will render and it will look like
Name: qty: unit price: total item price:
size:
Although those table name shows NOTHING
is getting shown which means the page is just rendering for nothing. I know some of you might think "if the person whats to mess about with the values, that is their fault" and I totally agree but I still want to stop the page from rendering
if everything posted doesn't relate to any of the item with that product ID (Pid
).
How can I use ajax to validate them before rendering it in the other page?
I already Have an ajax which looks like
$(document).ready(function(){
$('#selected').hide();
$('#button').click(function(){
var pid = $('#pid').val();
var size = $('#size').val();
var qty = $('#Qty').val();
var price = '\u00A3' + parseInt($('#pricetag').text().replace(/^\D/, ''), 10) * qty;
if (!/^[1-9]\d?$/.test(Qty)){
alert('Quantity should not be below 1 or null');
return false; // don't continue
}
else {
$('#sprice').text(price);
$('#ssize').text(size);
$('#selected').slideDown();
}
$.ajax({
url: 'cart.php',
type: 'POST',
data: { pid:pid,
size:size,
Qty:Qty,
Category:Category },
success: function(data)
{
}
});
});
});
in cart.php
is where I am posting those values to.
How can I do this please?
You want to ask the server to see if the data is valid. Aside from the form data, I would also post a flag telling PHP that this is the AJAX validation so it can tell the AJAX post from normal form submission.
In PHP, after the data validity is determined, it can just return true or false. Then your Javascript can determine what to do from that point on.
However, I think there are other ways to go about this. Maybe you shouldn't let the user modify these fields, or maybe you can post the form, and render the form again if the user has submitted invalid data. Another alternative is to limit the choices that the user can do, so their input is always valid.