Ajax + PHP in multi row - php

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

Related

Best practice for using jquery to interact with php classes?

I have a dropdown selector on a page that allows a user to select a template type (for example, "human" or "dog").
Based on what template is selected, different fields will need to populate below the dropdown (for example, text fields for "parents names" or a dropdown list for "breed") that are unique to each template.
I will have a button that the user will click once the data fields are put in that will output data to an "output div" section of the same page when clicked (no POSTing data as it's not being saved). The output will have different output logic based on the selected template (for example, "I'm a human named X" or "I'm a dog, my breed is Y").
My real program will be more complex and each template will have a php class that stores all of the logic. Since I will be dealing with both php objects and variables gathered by jquery, what's the best way to let them interact?
For 1., I know I can do something easy like -
var selected_template = $('#my-template-dropdown :selected').text();
if (selected_template == 'Human'){
$('#my-fields').html('<?php echo HumanTemplate::render_fields(); ?>');
}
which is easy enough, but for 2. I need to pass variables from jquery to php, then return output back to jquery.
I would like some advice on the easiest way to do this before I start down the wrong path.
HTML
Allow the user to select the template type:
<form>
<select id="my-template-dropdown" name='template'>
<option value="dogs">Dogs</option>
<option value="humans">Humans</option>
</select>
</form>
<div id="my-fields"><div>
<div id="output"><div>
jQuery
Any time the user changes the template selection, request new content to display via AJAX, and insert it on the current page so the page does not have to refresh:
$('#my-template-dropdown').on('change', function() {
var template = $(this).val();
$.ajax({
url: 'http://your-site/path/to/' + template,
success: function(resp) {
$('#my-fields').html(resp);
}
});
});
PHP
http://your-site/path/to/template simply generates the HTML you want to display for that template, eg (just an example, don't know if this is suitable for your app):
if ($template == 'humans') {
echo HumanTemplate::render_fields();
} else if ($template == 'dogs') {
echo DogTemplate::render_fields();
}
For part 2, assuming all the logic you refer to is in the template rendered by PHP, you could then handle it with jQuery. This is pretty crude, you probably need something more sophisticated (eg a full template which you swap variables into?), but you get the idea:
$('#output').on('click', 'button', function(e) {
e.preventDefault();
// fields in your template which the user will fill
var species = $('#species').val(),
title = $('#title').val();
// Probably better to have this text as a template in your source
$('#output').html("I'm a " + species + ' named ' + title);
});
NOTE the gotcha in the event handler. Event handlers will only attach to elements that exist at the time the handler is defined. Since the content is injected after page load, an event handler like $('#button).on('click', function() {... would have no effect when clicking a button inserted via AJAX. The syntax here attaches to the parent #output div, which does exist at page load, and filters for clicks on a button. See the jQuery event delegation docs for more info.
Another option would be to POST the submitted data to some PHP controller, which generates and returns the output. This way all your logic is in the one place. For example, here the user's click will query the same PHP file which generated the initial template, this time including the values the user has entered. It could then generate the required output and return it, to be inserted on the page. You'd need to update the PHP so it can determine which of these cases it is handling (eg hidden field?); alternatively if you wanted to keep those separate you could hit another PHP file all together.
$('#output').on('click', 'button', function(e) {
var template = $('#my-template-dropdown').val(),
$form = $('form'),
data = $form.serialize(); // Values from all fields user has entered
$.ajax({
url: 'http://your-site/path/to/' + template,
data: data,
success: function(resp) {
$('#output').html(resp);
}
});
});
The best way to pass data from jQuery to PHP, is by using AJAX.
Mozilla has an excellent guide on getting started, that i recommend you follow.
An example of how you can achieve what you are requesting, is by trying the following:
var selected_template = $('#my-template-dropdown :selected').text();
var ajaxurl = 'ajax.php',
data = {'select_template': selected_template };
$.post(ajaxurl, data, function (response) {
console.log(response);
});
On the PHP end (Ajax.php in my example) It could look something like this
if(isset($_POST['select_template'])) {
// do something with the input from jQuery
$selected_template = $_POST['select_template'];
// return the result back to the client
echo $seleted_template;
}
?>
$selected_template will be sent back to the client, and response in the AJAX function will be whatever the server returned. So the console.log(response) should display whatever was being sent to the server
You can have a look to the function wp_localize_script.
This function make available PHP datas to JS files on the page load through the wp_enqueue_scripts action.
This will not work like an Ajax request and only populate data for a specific handle on page load. But you can mix this method with ajax in the same script.
Hope it helps even it doesn't seems to fit to your case.
As your class not fires on page load, you can use the action wp_ajax_{custom _action} and wp_ajax_nopriv_{custom_action} . For example, that's usually used to populate multiple dropdown, each time an event is trigger by the user, a php function returns result the js script.

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)

Showing a dynamically built div

I have a drop-down menu built from entries in a database. What I need to do is to show certain content based on the selected entry in the menu. So, if I choose "Apples" in the menu, I can write a query to pull "Apple" info out of the database and the content div will show this information. "Oranges" will write an "Oranges" query and then show the info on oranges.
Ideally, I'd like the index of the selected menu item. But since I'm not submitting any form, I cannot get the info from $_POST variables. I could get it via jQuery or Javascript but I need it for processing another MySQL statement.
Since I don't know the information in the menu, I can't set up specific divs to show the content.
Hopefully this makes sense! Thanks for any help.
You want to create an asynchronous call. You want JavaScript triggered on the form changing to make a call to the server. On the server, you perform the SQL query and return it in a machine readable format such as JSON or just build the div on the server. When the JavaScript gets the reply from the server, it can parse the contents and insert it into the page.
I can sense you need an example
JQUERY:
$('select').change(function(){
var myfruit = $(this).val(); // apple, orange
$.ajax({
"url": yourphpfile.php,
"type": "POST",
"data":{"fruit":myfruit},
}).success(function(response) {
// response is what we get back from php
for(var i in response){
$('#div').append(response[i]['fruit'];
}
});
});
PHP
if(isset($_POST['fruit'])){
$sql = "SELECT * FROM fruits WHERE fruit = '{$_POST['fruit']}'";
// do something with your query, and get a result;
echo json_encode($result); // this gets sent to your jquery
die;
}

onclick -> mysql query -> javascript; same page

I need button to begin a mysql query to then insert the results into a javacript code block which is to be displayed on the same page that the button is on. mysql queries come from the values of drop-down menus.
Homepage.php contains
two drop down menus
div id='one' to hold the results javscript code block
a button to stimulate the mysql query to be displayed in div id ='one' through Javascript
flow of the process is as such
1. user chooses an option from each drop down
2. when ready, the user clicks a button
3. the onclick runs a mysql query with selections from the drop down menu.
4. send the results as array from the mysql query into the javascript code block
5. display the results in div id ='one'
all of this needs to happen on the same page!
The problem I am having is that as soon as the page is loaded, the javascipt is static. I am unable to push the mysql results into the javascript on the page which I need it to appear on. Having everything on the same page is causing trouble.
I'm not looking for the exact code laid out for me, just a correct flow of the process that should be used to accomplish this. Thank you in advance!
I've tried
using both dropdowns to call the same javascript function which used httprequest. The function was directed towards a php page which did the mysql processing. The results were then return back through the httprequest to the homepage.
I've tried to save the entire Javascript code block as a php variable with the mysql results already in it, then returning the variable into the home page through HTTPRequest, thinking I could create dynamic javascript code this way. Nothing has worked
You need to use a technology called AJAX. I'd recommend jQuery's .ajax() method. Trying to do raw XHR is painful at best.
Here is how you'll want to structure your code:
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
Basically, HTTP is stateless, so once the page is loaded, it's done. You'll have to make successive requests to the server for dynamic data.
Use AJAX,
example
$.ajax({
type: "POST",
url: "yourpage.php",
data: "{}",
success: function(result) {
if(result == "true") {
// do stuff you need like populate your div
$("#one").html(result);
} else {
alert("error");
}
}
});
For this purpose you need to learn ajax.This is used to make a request without reloading the page.so that you can make a background call to mysql
your code will be something like that
$("#submitbutton").live("click",function(){
$.ajax({url:"yourfile"},data:{$(this).data}).done(function(data){
//this data will in json form so decode this and use this in div 2
var x =$.parseJSON(data);
$("#div2").html(x.val());
})
})
and "yourfile" is the main file which connect to server and make a database request
here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

Jquery text field populating from database on clicking select option

I'am having a select option box,if i click on the select option,two other text below it should be loaded with data from database,based on select option id value.How to do this with
php and jquery or cakephp and jquery
thanks in advance
Capture the change event of the select box
do an ajax post of the info to a .php page (which will read the value, retrieve and echo the data from the db)
the ajax post will define a callback function that will be called on success (when the php is done echoing the data), which will populate the two fields..
so
$(document).ready(function(){
$('your_select_box_selector').change(function(){
$.getJSON( 'your_php_page.php',
{selectVal: $(this).val()},
function(data){
$('text1_selector').val(data.text1);
$('text2_selector').val(data.text2);
}
)
});
});
and in your php you will need to read the selectVal url parameter we sent in getJSON call, and output something like this
{"text1": "text to go in the first text box", "text2": "text for the second text box"}

Categories