jQuery for each loop - child element on page - php

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)

Related

Using JQuery to refresh an HTML form (located on a PHP page)

I'd like to update a form, more exactly I wish to display an extra scroll menu, depending on the user's choice in a first scroll menu.
I have a page, mypage.php page on which there is a form. Here it is :
<form method="post" action="wedontcare.php" enctype="multipart/form-data">
<label for="base">3 - Select a DB </label><br />
<?php
include 'functions.php';
offers_choice_DB();
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
I have a separated file "functions.php" where are declared all the functions I use here. offers_choice_DB() displays a scroll menu where I can select a database (actually, this function performs a MySQL query and echoes the result in a scroll menu). If the user selects a database, then $_POST['base_name_choice'] exists. And it does, because when i only work with PHP/HTML, all is doing fine.
My purpose is to allow the user to select a database, then for this database I'd like to display a second scroll menu that displays some tables from this DB. This scroll menu will only be displayed if a POST value has been set. The offers_choice_table($_POST['base_name_choice']) function takes this value as an argument, then echoes the HTML for the scroll menu, containing the tables. Here we are !
Oh, and the submit button is not important here, because I want to have my second scroll menu displayed before the user clicks on the submit button, so we just disregard the target page, ok ?
Before, everything was OK : I used tests, conditions (isset...) but it was not dynamic, I had to call other pages, ...etc. And now I want, as you guessed, to use jQuery to refresh mypage.php as soon as the user selects a database so that an extra menu appears.
I started to listen to a change in my scroll menu, but then I don't know what to do to refresh my page with a POST parameter containing the selected database. Anyway, here is my code :
<script type="text/javascript">
$( '#base_name_choice' ).change(function() {
var val = $(this).val(); //here I retrieve the DB name
alert( val ); //I notify myself to check the value : it works
$.ajax({
type: 'POST', //I could have chosen $.post...
data: 'base_name_choice='+val, //I try to set the value properly
datatype: 'html', //we handle HTML, isn't it ?
success: function(){
alert( "call ok" ); //displays if the call is made
//and here...???? I don't know whatto do
}
})
});
</script>
Here it is...any help will be appreciated ! Thanks :)
Regards
The issue here is that your page is rendered first (html + php preprocessing). That means that once your page is rendered, you won't be able to make direct php method calls such as offers_choice_table or change the $_POST parameters.
How you normally do this, is by making an AJAX call from your javascript to a PHP script/method which than generates the second menu based on the parameter that the user chose.
So, you don't need this part:
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
because you will call "offers_choice_table" method with an ajax call.
You make the ajax call to a url which will return the second menu
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data){
alert( "call ok" ); //displays if the call is made
// here you can append the data that is returned from your php script which generates the second menu
$('form').append(data);
}
})
You should use GET instead of POST, in your new PHP file:
if (isset($_GET['base_name_choice'])) {
offers_choice_table($_GET['base_name_choice']);
}
You SHOULD check if the variable has a value set, especially if your function is expecting one. You can use whatever functions you want in this file, it is like any other PHP file you would write. Include any files that you want.
You should make sure to avoid SQL injection when using a GET or POST value in a query: How can I prevent SQL injection in PHP?
In the .ajax() call, there is a callback function success, this runs if the server response is good (i.e. not a 404 or 500). There first parameter in that function is what the server returned. In your case, it would be the HTML you echoed out. You can use jQuery to append the response to an element:
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data) {
// it looks like you're only returning the options of the select, so we'll build out the select and add them
var $newSelect = $('<select></select>');
$newSelect.append(data);
// and then add the select to the form (you may want to make this selector for specific)
$('form').append($newSelect);
}
});

Ajax + PHP in multi row

I created a simple webpage to add product one at a time. User only need to input the product name and all product info will be get thru AJAX. I used jQuery AJAX and it works.
But Now user want to have a button at the end of the row so that they can add many products in the same page. so when they want to add one more product, then can just click the button and a new row will appear below for them to add product.
How can I do that to pass data to PHP? what's the name for each textbox? In PHP, how do I can all these products info? In array?
How can I use ajax to put the received info to different row? IE. when user select row two product, how to make put the product info back to row two fields?
If I use AJAX, I know we can pass multiple data to server by using JSON. Can I receive multiple Data too? Now I am using separator only.
any example?
Thanks
There is a lot of possibilities to do that. This is one.
I dont know where you want to calculate your subtotal. And discount. It could be done in javascript or it could be done by php. It is your choice.
$(document).on("change", ".cboProdc", function(e){ // As you change the select box element
$("*").removeClass("active");//Remove active class from all elements in the DOM
$(this).parent().addClass("active");//Add active for a div container parent
//Add active for each input som form active div
$(".active .txtPrice").addClass("active");
$(".active .txtDisc").addClass("active");
$(".active .txtSugDisc").addClass("active");
$(".active .txtQt").addClass("active");
$(".active .txtStot").addClass("active");
//Make your AJAX request to PHP.
//Send to PHP id product like this $("option:selected", this).val();
var dt={
productId: $("option:selected", this).val()
};
//Ajax
var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
url: "yourServer.php",
type: "POST",
data: dt,
dataType: "json"
});
//Retrieve all information through JSON and put it in each active element.
//Ajax Done catch JSON from PHP
request.done(function(dataset){
for (var index in dataset){
txtPrice=dataset[index].Price;
txtDisc=dataset[index].Discount;
txtSugDisc=dataset[index].SugDisc;
txtQt=dataset[index].Quanty;
txtStot=dataset[index].Stot;//If you want to use php to perform the calculus
}
//JavaScript conditions. Here you can control the behaivior of your html object, based on your PHP response and pass values to acvive elements
$(".active .txtPrice").val(txtPrice);
$(".active .txtDisc").val(txtDisc);
$(".active .txtSugDisc").val(txtSugDisc);
$(".active .txtQt").val(txtQt);
$(".active .txtStot").val(txtStot);
});//End of request.done(...
});//End of $(document).on("change",
///////////////////////////////////////////////////////////////////////////////////
//Your php code
//Make your query at database
//Return like this:
$arrToJSON = array(
"Price"=>"the price",
"Discount"=>"the Discount",
"SugDisc"=>"the SugDisc",
"Quanty"=>"the Quanty",
"txtStot"=>"the txtStot",
);
return json_encode(array($arrToJSON));
//////////////////////////////////////////////////////////////////////////////////////
To save all information make a .each() http://api.jquery.com/each/ for each element, retiereve each information an use separator to send to php. Exemple "*"
In php you can use explod http://php.net/manual/en/function.explode.php
Here you have a fiddle http://jsfiddle.net/hp5kbtce/1/ to see how to select elements for each product row

Cross checking with database before rendering page

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.

Calling different POST variables using Ajax

I'm still new to jQuery and stuck trying to figure this one out, hope someone can help. I have this jQuery code that needs to pass different values depending on the clicked element. Each element created has a unique number in it's ID (which is needed). If I manually change the jQuery code to a specific ID and call, for example:
http://mysite/examplepost?effect=113
This will work. But I need to have $('#div- ...different numbers here...') to be able to handle multiple elements on the same page. I already have the PHP side producing different values using:
if($_GET['effect'] == $id){
I just need this to work with ajax so that it doesn't reload the page.
Example:
$('#div-113').on('click', function() {
var dataString = 'effect=113';
jQuery.ajax(
{
type:'GET',
url:'?',
data: dataString,
success: function(data){
alert('Works');
}
}
);
});
Any help would be appreciated.
I would give all your divs a common classname (i.e. myClickableDiv) and also a specific data-id.
This way you can target all your divs by that common classname, rather than having to figure it out depending on how the id is formed. The data-id allows you to only provide very specific information to the click handler (like an integer), without having to parse the id.
HTML:
<div class=".myClickableDiv" id="div-XXX" data-id="XXX">My Div</div>
JS:
$('.myClickableDiv').on('click', function() {
var dataString = $(this).attr('data-id');
jQuery.ajax({...});
});

Update php generated content without page refresh

I've created a php function (called "category_page" in "category-page.php") which reads data from a file into an associative array and then generates some html to display the information on products.php (the page calling the "category_page" function)
My aim is to allow the user to select from a drop down in order to sort the displayed information without refreshing the page.
I have so far managed to achieve this using document.formname.submit on change of the dropdown and then using $_GET to choose which key in the array to sort by, however, this causes the page to reload.
I have a little knowledge of php, javascript/jquery and have done a fair bit of searching/reading on AJAX to enable an update without refresh/reload, but can't seem to put all the pieces together.
So, in products.php, I have the following javascript/jquery:
function sort_products() {
queryString = "?sort_list="+$("#sort_list").val();
$.ajax({
type: 'GET',
url: 'category-page.php',
data: 'sort_list='+queryString
})
}
$("#sort_list").on("change", function() { sort_products() });
and then in category-page.php:
if(isset($_GET['sort_list'])) {
$sort = $_GET['sort_list'];
}
else {
// set default sort order
}
I've verified in Chrome's network panel that a request for category-page.php?sort_list=price is being sent, but the page isn't updating. Any help would be appreciated!
Change this line of code:
$("#sort_list").on("change", function(e) { sort_products(); e.preventDefault(); e.stopPropagation(); });
Once the query is sent, you need to make something with what is returned.
$.ajax({
type: 'GET',
url: 'category-page.php',
data: 'sort_list='+queryString
})
.done(function(data) {
// if your php code returns the html you can make something like this
// the var data will be the html code
$('#your-container').html(data)
})

Categories