Cross checking with database before rendering page - php

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.

Related

jQuery for each loop - child element on page

I have an ecommerce 'grouped' product page, with multiple variations of the product displayed. I need to do a live stock check with distributors (XML http post) so am using AJAX to speed up the page.
E.g. - On the grouped product page there are 20 SKUs, each will have a unique stock level looked up via its unique VendorPn code. I need top loop through each part number and fire the AJAX. I have built the script to fire successfully, but cant get it to loop for each child element (it always uses the same value):
$('.stockAvailability').each(function(i, el) {
var $imVPN = $(this)
var dataString = "VendorPn=" + $(".VendorPn").val();
$.ajax({type: "POST",
url: "ajax/stock-check.php",
data: dataString,
dataType:'json',
success: function(data)
{
if(!data.error)
{
$(".stockAvailability").prepend(data.stock);
}
else
{
alert(data.error);
}
}
});
});
So the stock level will append to each product variations .stockAvailability. This is all working fine, but i'm having trouble getting it loop for all 'child elements'. The php on the product runs a for loop, so I can grab the .VendorPn for each sku and send it to the AJAX post datastring from there.
Can anyone help as to setting up the jQuery so that for each occurrence of the VendorPn value it finds on the page it runs the above, and updates relevant the .stockAvailability accordingly?
I'm pretty sure its just how I structure the page, and use child elements?
Many Thanks
Posted answer as requested by OP (see comments trail above)
$(el) should get you the current loop instance of stockAvailability, so try:
$(el).html(data.stock)

How do I post to a new php page with jquery

I am trying to post the element information that jQuery pulls, when a user clicks on table cell, to a new page that will use that information (an id in this case) in a sql query. i.e., the user clicks a cell and the job he/she clicks has an id of 25, that is to be passed to my php page that queries the database for the job with that id and then populates the page with said information. The user can then alter the information from the query and submit it to update the database table. I have the id from the click function and a success alert tells me that the info was posted. The problem is that when the page is opened it states that the posted name index is undefined.
Here is my script to get the information:
<script>
$(document).ready(function()
{
$("table.jobs tbody td#job").click(function()
{
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
if (col == '')
alert("Please pick another column");
else
$.ajax(
{
type:"POST",
url:"../php/jobUpdate.php",
data:"name=" + LeftCellText,
success: function()
{
window.location = "../php/jobUpdate.php";
}
});
});
});
</script>
and here is the simple php page it is sending to:
$name = $_POST['name'];
echo $name;
I am new to jQuery, and I cannot figure out why this is not working?
When you use ajax, the second page ../php/jobUpdate.php processes the data sent by the first page, and returns a value (or even a huge string of html, if you want).
The first page receives the new data in the ajax routine's success function and can then update the current page. The updating part happens in the success: function, so you're on the right track.
But in your success function, you are redirecting the user to the 2nd page -- after already being there and processing the data. Redirecting them is probably not what you want to do.
Try replacing this:
success: function()
{
window.location = "../php/jobUpdate.php";
}
with this:
success: function(data)
{
alert(data);
}
If you want to see how to update the first page with the data received via ajax, try adding an empty DIV to your html, like this:
<div id="somestuff"></div>
Then, in the success: function of the ajax routine, do this:
$('#somestuff').html(data);
(Note that the term "data" can be any name at all, it only needs to match the name used in the function param. For example:
success: function(whatzup) {
alert(whatzup);
}
From your comment to my previous post, it seems that you don't need ajax at all. You just need a form in your HTML:
<form id="MyForm" action="../php/jobUpdate.php" method="POST">
<input type="hidden" id="jobID" name="yourJobID">
</form>
Note that forms are invisible until you put something visible inside them.
You can have select controls (dropdowns) in there, or all form elements can be invisible by using hidden input fields (like the HTML just above), which you can populate using jQuery. Code to do that would look something like this:
<script>
$(document).ready(function() {
$("table.jobs tbody td#job").click(function() {
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
//Set value of hidden field in form. This is how
//data will be passed to jobUpdate.php, via its `name` param
$('#jobID').val(LeftCellText);
if (col == '')
alert("Please pick another column");
else
$('#myForm').submit();
});
});
</script>
If you add more values to your form to send over to jobUpdate.php, just ensure that each element has a name, such as <input type="text" name="selectedJobType"> (this element, type="text", would be visible on screen).
In the jobUpdate.php file, you would get these values thus:
$SJT = $_POST['selectedJobType'];
$id = $_POST["yourJobID"];
//Use these vars in MySQL search, then display some HTML based on results
Note that the key referenced in the $_POST[] array (selectedJobType / yourJobID) is always identical to the name specified in the HTML tag. These names are case sensitive (and spelling counts, too).
Hope this isn't TMI, just wish to cover all the bases.
On your success function causing the window to reload will delete any of the variables passed in via .ajax.
What you can try is returning the data and use it in the existing page.
success: function(msg) {
$('#someDiv').append(msg);
}
The reason the index is not defined is because you are using a string in the data-argument, however, that is actually an array-like object. :)
data: { name: col }
that should be the line you need to change. Otherwise I have not seen any problems. Also if I can give you a little idea, I wouldn't use POST actually. In fact, I'd use GET. I can not confirm if that is saver or not, but using $_SERVER["HTTP_REFFERER"] you can check from where that request is coming to determine if you want to let it pass or not.
The way I would suggest is, that you sent the ID in a GET-request and have the PHP code return the data using json_decode(). Now in jQuery, you can use $.getJSON(url, function(data){}) - which is, for one, shorter and a bit faster.
Since you probably will crop the URL yourself here, make sure that you use a function like intVal() in JS to make sure you are sending an intenger instead of a malicious string :)

how to refresh the data being loaded on the form after showing it off?

I have a a div, wherein, it displays the data, and beside it, is an edit button..if one clicks the edit button, it hides the div and shows a different div with input forms which allows the user to update the data..the problem now is, when the user submits the form, my script updates the data and hides this input forms and shows again the former div of data display, the data shown is not updated....my question now is,, how to show the updated data after the script show() it again ?
here's my jquery ajax code
$(function(){
$('#profileinfoedit').click(function(){
$('#profileinfomain').hide();
$('#profileinfoajax').show();
$('form#pdetails').submit(function(){
var cvid = $('#cvid').val();
var resumetitle = $('#resumetitle').val();
var name = $('#name').val();
var dob = $('#dob').val();
var gender = $('input[name=gender]:checked').val();
$.ajax({
type: "POST",
url: 'classes/ajax.personalupdate.php',
data: $("form#pdetails").serialize(),
success: function(data){
alert(data);
$('#profileinfoajax').hide();
$('#profileinfomain').show();
}
});
return false;
});
});
});
$('#datepicker').datepicker();
So location.reload is just refreshing the page, which as you have discovered is a quick and dirty fix.
If you want to do it without a page refresh, you would have to regenerate the html for just the 'profileinfomain' element from data received back from ajax.personalupdate.php. I would assume you would only want to do this on "success".
One approach would be to have the success data contain the html needed to regenerate the 'profileinfomain' element html. So perhaps have php return back data.profileinfomain_html, and then:
$('#profileinfomain').html(data.profileinfomain_html);
which will replace the inner content of the profileinfomain element.
If you are working in a framework of some sort, have the profileinfomain inner html content be a partial template included in so you only have to maintain its html in one place.
was able to sort it out via
$('#profileinfomain').show('normal',function(){
location.reload();
});
but, isn't there any better way to do this?

Adding divs on the fly with jQuery and submit them through AJAX

I'm having some blocking issues with something I'm developing.
The idea is to have customers who may have more than one address. So, when you see the customer "profile" you have a Select box which have all his/her addresses tagged so you only see the one which is selected.
They are really there but hidden with some javascript/jquery.
So, the problem comes when adding new address. I don't know how could I add more dinamically. What I do is to have a hidden div which is empty so, when you press the Add address button it shows the div and let you fill the form however I don't know how to add more than one and then save them.
The issue is with usability and with programming. The usability part is that you may have visible the div with the Address you are about to add but what happens with that div if you try to add a new one? Should be hidden? If so, there should be a way to get them back just in case you need to change some data or if you don't hide them, you may end with a really big scroll bar.
And then, there is the way I save the info for each address div, I'll paste my code here:
$('.form-direcciones').each(function(){
var ajData = $(this).serialize();
var idDireccion = $(this).attr('id');
if (idDireccion === 'form-nueva-direccion'){
ajData = ajData + '&action=insertar'+
'&cod_cliente='+cod_cliente;
}
else{
idDireccion = idDireccion.split('-');
ajData = ajData + '&cod_dir='+idDireccion[2] +
'&action=' + action +
'&cod_cliente=' + cod_cliente;
}
$.ajax({
type: "POST",
url: "controllers/direccion.php",
async: false,
data: ajData,
dataType: "html",
cache: false
});
});
As you may see, it checks if the ID of the div is the one I use for that but even with that solutions it seems a little bit dirty to me.
Also, it comes the problem where I'm having repeated IDs...
Just take a look at this jsfiddle
http://jsfiddle.net/Z3JPW/12/
I have done the basics to give you an idea on how to do stuff client side. You can do everything such as editing and deleting and inserting all at client side and finally take the data to the server side persistence.

Looking for syntax guidance on implementing AJAX project

I am taking on my first AJAX project and conceptually have everything mapped out for the most part but am being held back due to my lack of knowledge syntactically. I think I also might be off the mark slightly with my structure/function logic.
I am looking for some guidance, albeit reference to tutorials or any corrections of what I am missing or overlooking.
profile.php: this is the page that has the actual thumb icon to click and the $.post function:
Here is the thumb structure.
When thumb is clicked, I need to send the id of the comment? I know I need to calculate the fact that it was clicked somehow and send it to the $. Post area at the bottom of this page, I also need to put some sort of php variable in thumb counter div to increment numbers when the $. Post confirms it was clicked.
<div id="thumb_holder">
<div id="thumb_report">
<a href="mailto:info#cysticlife.org">
report
</a>
</div>
<div id="thumb_counter">
+1
</div>
<div id="thumb_thumb">
<?php $comment_id = $result['id'];?>
<a class="myButtonLink" href="<?php echo $comment_id; ?>"></a>
</div>
</div>
Here is the $.post function
This should be sent the id of the comment? But most certainly should be sent a record of the thumb link being clicked and somehow send it to my php page that talks to the db.
<script>
$.ajax({
type: 'POST',
url:" http://www.cysticlife.org/thumbs.php,"
data: <?php echo $comment_id; ?>,
success: success
dataType: dataType
});
</script>
thumbs.php: is the page that the request to increment is sent when the thumb is clicked and then in turn tells the db to store a clikc, I don't really have anything on this page yet. But I assume that its going to be passed a record of the click from via $.post function from the other page which syntactically I have no clue on how that would work and then via insert query will shoot that record to the db.
Here is what the table in the db has
I have three rows: a id that auto incrments. a comment_id so it knows which comment is being "liked" and finally a likes to keep track on the number of thumbs up.
At least you've made a good start, there are still some mistakes. First of all there are some basic principles you might want to get used to:
1) How to create a click event
First of all the button, I inserted '2' as the href.
<a class="myButtonLink" href="2">Vote Up!</a>
EDIT: Just in case JS in disabled, this would be a better option:
<a class="myButtonLink" href="voteup.php?id=2" id="2">Vote Up!</a>
Then the JS:
$('.myButtonLink').click(function(e) {
e.preventDefault();
alert('the button has been clicked!');
});
The e represents the event, so the first thing we do after the submit is to cancel the default action (redirecting to '2'). Then we're alerting that the button was clicked. If this works, we can go to the next step.
2) Getting the ID value from the clicked link.
Inside the click function, we can use $(this), it's a representation of the element clicked. jQuery provides us with a set of functions to get attributes from a given element, this is exactly what we need.
$('.myButtonLink').click(function(e) {
e.preventDefault();
var comment_id = $(this).attr('id');
alert('We are upvoting comment with ID ' + comment_id);
});
When everything goes well, this should alert 'We are upvoting comment with ID 2'. So, on to the next step!
3) Sending the Request
This might be the harders step if you're just getting started with ajax/jquery. What you must know is that the data you send along can be a url string (param=foo&bar=test) or a javascript array. In most cases you'll be working with an url string because you are requesting a file. Also be sure that you use relative links ('ajax/upVote.php' and not 'http://www.mysite.com/ajax/upVote.php'). So here's a little test code:
$('.myButtonLink').click(function(e) {
e.preventDefault();
var comment_id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'thumbs.php',
data: 'comment_id=' + comment_id,
success: function(msg) { alert(msg); }
});
the dataType is detected automatically, you can for instance choose between a JSON response (which can be an array with a status and message response) or just plain text. Let's keep it simple and take plain text to start of with.
What this script does is calling thumbs.php and sending a $_POST value ($_POST['comment_id'] = 2) along with this request. On thumbs.php you can now do the PHP part which is:
1) checking if the comment_id is valid
2) upvoting the comment
3) print the current amount of votes back to the screen (in thumbs.php)
If you print the number of votes back to the screen, the last script I gave you will alert a messagebox containing the number of votes.
4) Returning an array of data with JSON
In order to get a proper response on your screen you might consider sending back an array like:
$arr = array(
'result' => 'success', // or 'error'
'msg' => 'Error messag' // or: the amount of votes
)
Then you can encode this using the php function json_encode($arr). Then you would be able to get a more decent response with your script by using this:
$('.myButtonLink').click(function(e) {
e.preventDefault();
var comment_id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'thumbs.php',
data: 'comment_id=' + comment_id,
success: function(data) {
if(data.result == "error") {
alert(data.msg);
} else {
alert('Your vote has been counted');
$('#numvotes').html(data.msg);
}
}
});
As you can see we're using (data) instead of (msg) since we're sending back a dataset. The array in PHP ($arr['result']) can be read as data.result. At first we're checking to see what the result is (error or success), if it's an error we alert the message sent along (wrong DB connection, wrong comment ID, unable to count vote, etc. etc.) of the result is success we alert that the vote has been counted and put the (updated) number of votes inside a div/span/other element with the ID 'numvotes'.
Hopefully this was helpfull ;-)
//edit: I noticed some mistakes with the code tags. Fixed the first part of the 'manual'.

Categories