How to submit data array to server from PHP and jQuery - php

I have an array of PHP with customer data. I will modify this values in jQuery. Then O would like to submit the changed values with an Id (cashup_id) to the server from jquery. Please see the PHP array below. Please help. Thanks.
$Cashups = array(
array(
'cashup_id' => 146456,
'display_time' => 'Wed 16th Mar, 9:55pm',
'terminal_name' => 'Bar 1',
'calculated_cash' => 389.20,
'actual_cash' => 374.6,
'calculated_tenders_total' => 1,551.01,
'actual_tenders_total' => 1,551.01
),
array(
'cashup_id' => 146457,
'display_time' => 'Wed 16th Mar, 9:56pm',
'terminal_name' => 'Bar 2',
'calculated_cash' => 493.3,
'actual_cash' => 493.3,
'calculated_other' => 1509.84,
'actual_other' => 1509.84
)
);

#Powtac see the JS code.
jQuery(function($) {
$(".Cashups").delegate("td:eq(3) > a", "click", function(event) {
var a, parent, input, doneLink, b, i, eq, c, d;
var eq = $(this).parent().children("a").index(this);
// The `a` has been clicked; cancel the action as
// we're handling it
event.preventDefault();
event.stopPropagation();
// Remember it and its parent
a = $(this);
parent = a.parent();
// Insert an input in front of it, along with a done link
// because blur can be problematic
input = $("<input type='text' size='10'>");
input.insertBefore(a);
input.blur(doneHandler);
doneLink = $("<a href='#'>done</a>");
doneLink.insertBefore(a);
doneLink.click(doneHandler);
// Put the text of the link in the input
input.val(a.text());
// Temporarily detach the link from the DOM to get it
// out of the way
a.detach();
// Give the input focus, then wait for it to blur
input[0].focus();
// Our "done" handler
function doneHandler() {
// Replace the content of the original link with
// the updated content
a.text(input.val());
b = a.text();
//c = b;
alert(b);
$.get('js_test.php?b=' + b, function (data) {
$('.Cashups td a').eq(3).html(b);
});

Related

Add new value at the end of URL Woo Elementor

I want to change following code from Elementor:
$this->add_render_attribute( 'button',
[
'rel' => 'nofollow',
'href' => $product->add_to_cart_url(),
'data-quantity' => ( isset( $settings['quantity'] ) ? $settings['quantity'] : 1 ),
'data-product_id' => $product->get_id(),
'class' => $class,
]
);
to add new value like this:
foreach (get_the_terms(get_the_ID(), 'producer') as $cat) {
echo $cat->name;
}
for the 'href' part in first code:
'href' => $product->add_to_cart_url(),
above 'href' code adds this value in path ?add-to-cart=2809 and I want to make it look like this ?add-to-cart=2809&wdm_name=MY-CODE-FOR-EACH-ABOVE-CREATE-VALUE-HERE
How do I implement second code inside HREF part so I dont get the error.
Thanks
Actually, just a few days ago I had the need of changing existing URLs inside href for each category on a widget my shop page.
So for my case I ended up creating this code:
var $ = jQuery;
$(document).ready(function(){
var search = window.location.search; // Get all existing search params in URL
var urlOrigin = document.location.origin; // Get current URL (only domain)
//console.log(urlOrigin); // For testing in browser console
$('.widget-area .product-categories li a').each(function(){ // You can mobify this to get your elements where you have them listed
var catSlug = $(this).attr('href').replace(urlOrigin,''); // I am doing this because I need to get the slug for each category to then append to the final URL
url = urlOrigin+catSlug+search; // Final URL mounted, here is where you can put your variable to set the code you want for each URL
$(this).attr('href',url); // Associate this new generated URL to the element
});
});
Since it is not clear where/how you want to use it, I leave my code here in case you can use it to adapt to your case, which I belive you can.

Yii2 DropDownList Onchange change Autocomplete Widget "source" attribute?

I have already tried this : yii2 dependent autocomplete widget
but i don't know why it's not working.
here my html with script:
<?= $form->field($model, 'lbt_holder_type')->dropDownList(['prompt' => '--- Select Holder Type ---', 'S' => 'Student', 'E' => 'Employee'],
['onChange' => 'JS: var value = (this.value);
if(value == "S"){$(#libraryborrowtransaction-name).autoComplete({source: '. $s_data.');}
if(value == "E"){$(#libraryborrowtransaction-name).autoComplete({source: '. $e_data.');}
'])?>
Autocomplete:
<?= $form->field($model, 'name')->widget(\yii\jui\AutoComplete::classname(), [
'options' => ['class' => 'form-control', 'placeholder' => 'Enter Name/ID'],
'clientOptions' => [
'source' => $s_data,
'autoFill' => true,
'minLength' => '1',
'select' => new yii\web\JsExpression("function( event, ui ) {
$('#libraryborrowtransaction-lbt_holder_id').val(ui.item.id);
}")
],
])?>
i want to change autocomplete source according to dropdownlist value, if S then load $s_data else load $e_data.
Any help with this. Thanks.
Here's my data,
$s_data = (new \yii\db\Query())
->select(["CONCAT(stu_unique_id,' - ',stu_first_name,' ',stu_last_name) as value","CONCAT(stu_unique_id,' - ',stu_first_name,' ',stu_last_name) as label","s_info.stu_info_stu_master_id as id"])
->from('stu_master stu')
->join('join','stu_info s_info','s_info.stu_info_id = stu_master_stu_info_id')
->where('is_status = 0')
->all();
and,
$e_data = (new \yii\db\Query())
->select(["CONCAT(emp_unique_id, ' - ',emp_first_name,' ',emp_last_name) as value","info.emp_info_emp_master_id as id"])
->from('emp_master emp')
->join('join', 'emp_info info', 'info.emp_info_id = emp_info_emp_master_id')
->where('is_status = 0')
->all();
Well, I've added your code snippets to my test yii2 environment to test what's wrong. So there are some problems with your code:
[
'onChange' =>
'JS: var value = (this.value);
if(value == "S"){$(#libraryborrowtransaction-name).
autoComplete({source: '. $s_data.');}
if(value == "E"){$(#libraryborrowtransaction-name).
autoComplete({source: '. $e_data.');}
']
First of all I noticed what yii apply some escaping for quotation mark symbols for your "S" and "E", and your code in browser looks like "S".
Next, jui autocomplete plugin adds a property to jquery prototype with name "autocomplete" but not "autoComplete". As for as js is case sensitive, this two names looks different for it.
So my solution was to move all js from onchange property to separate js script, as it shown below (for testing purposes you can add it right in your yii view file where you use code provided in your question)
<script>
function holderTypeChangeHandler(ev) {
var value = (this.value);
if(value == 'S'){
$('#libraryborrowtransaction-name').autocomplete({source: ' . $s_data . '});
}
if(value == 'E'){
$('#libraryborrowtransaction-name').autocomplete({source: ' . $e_data . '});
}
}
window.onload = function(){
$('#libraryborrowtransaction-lbt_holder_type').on('change', holderTypeChangeHandler);
};
</script>
And paste name of this new event handler to your dropdownList's onchange property like this:
['onChange' => 'holderTypeChangeHandler']
UPDATE: ---------------------
Since Yii2 Autocomplete based on JQuery UI autocomplete widget and Yii2 Autocomplete clientOptions contains settings for JUI autocomplete widget, then we can refer to JUI API docs for explanation of the source option. As you can see, this option can be a string (in this case it used as URI to JSON data), a function or an js array of data or js array of objects.
In your question you are using \yii\db\Query to fetch some data from db with help of method all(), which returns an array of data. So finally you need to convert the array of data which you get with \yii\db\Query->all to js array of objects. To do it, use php json functions, particulary for your case you need to use json_encode() function:
// Let's say this is a result of your query to db with use of `\yii\db\Query->...->all();`
$some_array = [
[
"value" => "Val 1",
"label" => "Label 1",
"id" => 1
],
[
"value" => "Val 2",
"label" => "Label 2",
"id" => 2
]
]
// Just convert it to json string
$s_data = json_encode($some_array);
...
// When concat this json string as a value of source attribute for Yii Autocomplete
$('#libraryborrowtransaction-name').autocomplete({source: <?= $s_data ?> });
The same if for your $e_data. Just pay attention, your get your data from db with PHP, but use it with JS, so php array needs to be converted to a string presentation js array of objects, and this conversion you can do with json_encode.

jQuery html elements dynamically, adding event handlers?

Ive spent several hours trying to resolve an issue with very limited experience with jQuery which is not helping me.
I am wanting to search a database for a list of results using a few input fields and then a submit button, when you click submit the values are passed to a .php script which returns the results and these are displayed in a table within a div container which works perfect.
Each record is then displayed in its own row within the table, with columns for different data.
record number name town etc
What i want is for the record number to be a click link of some kind, which when clicked, it then passes that value and does a different mysql request displaying that unique records data in more detail in a different div container. This is the part i cant get to work as i believe its something to do with BINDING, or the .ON which i dont really know anything or understand how it works, as my experience is very limited.
I have provided some sample code which consists of two files, jQuery.php and db.php, db.php is just simulating a database lookup for now (crude i know), to make it easier to show my code and what i am trying to do.
if you run jQuery.php and either enter a town (sheffield,rotherham) followed by click "get data" you get a refined list of results, if you just click get data you get all the results, you will see each results as a 4 dig ID Number, what i want to happen here is when you click that number it then loads just that record in a different div container, but its not working due to the dynamic content as i have read but don't understand.
You will see i have made an example of the reference number 1005 at the top of the page, and if you click on this, it loads that unique record fine, but i just can't get it to work with the ones in the table.
jquery.php
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".click").click(function() {
var recordid = $(this).attr("id");
$('#2').load("db.php?id=" +recordid);
});
$("#get").click(function() {
var town = $("#town").val();
$('#1').load("db.php?town="+town
);
});
});
</script>
OUTSIDE OF DYNAMIC HTML RECORD ID : - <a class = 'click' id = '1005'>1005</a><br>
<br>
Town <input type="textbox" id="town" ><br>
<button id="get">Get Data</button>
<br>
----<br>
*<div id="1" name='records_all'></div>
----<br>
*<div id="2" name='record_unique'></div>
----<br>
db.php ( crude code to simulate a db lookup, just for purpose of this problem )
<?php
$id = $_GET['id'];
$town = $_GET['town'];
echo "<pre>";
$data[]= array('id' => '1001', 'town' => 'sheffield', 'street' => 'national av', 'name' => 'neil');
$data[]= array('id' => '1002', 'town' => 'rotherham', 'street' => 'maple drive', 'name' => 'steve');
$data[]= array('id' => '1003', 'town' => 'leeds', 'street' => 'poplar drive', 'name' => 'john');
$data[]= array('id' => '1004', 'town' => 'rotherham', 'street' => 'exchange st', 'name' => 'claire');
$data[]= array('id' => '1005', 'town' => 'sheffield', 'street' => 'main street', 'name' => 'sarah');
$data[]= array('id' => '1006', 'town' => 'rotherham', 'street' => 'holderness rd', 'name' => 'jo');
if ($id) {
foreach ((array)$data as $key => $value) {
if ($data[$key]['id'] == $id) {
echo $data[$key]['id']."<br>";
echo $data[$key]['name']."<br>";
echo $data[$key]['street']."<br>";
echo $data[$key]['town']."<br>";
}
}
} else {
if ($town) {
foreach ((array)$data as $key => $value) {
if ($data[$key]['town'] == $town) {
$link = "<a class = 'click' id = '{$data[$key]['id']}'>{$data[$key]['id']}</a>";
echo "{$link} {$data[$key]['town']} {$data[$key]['name']}<br>";
}
}
} else {
foreach ((array)$data as $key => $value) {
$link = "<a class = 'click' id = '{$data[$key]['id']}'>{$data[$key]['id']}</a>";
echo "{$link} {$data[$key]['town']} {$data[$key]['name']}<br>";
}
}
}
You need to use event delegation to solve this issue. Look at the jQuery docs for .on here under the "Direct and delegated events" section
Try something like
$('#1').on('click', '.click', function() {
var recordid = $(this).attr("id");
$('#2').load("db.php?id=" +recordid);
});
This will work as long as the #1 element is in the DOM when the jQuery event bindings are run. Essentially you're binding the click event to the #1 element instead of having to bind it to elements after loading them in. The jQuery docs do a good job of explaining this.
If the elements are not in the DOM at the time of their jQuery selection then the events will not be added with the way you wrote your code. However alternatively you can write your code like this
$(document).ready(function() {
$(document).on('click', '.click', function() { //this is the only thing that changed
var recordid = $(this).attr("id");
$('#2').load("db.php?id=" +recordid);
});
$("#get").click(function() {
var town = $("#town").val();
$('#1').load("db.php?town="+town
);
});
});
This code should completely replace your javascript. It creates a live listener for all future elements in the document with the class click.

Symfony2 Prototype contains not needed field

I'd like to create an admin panel for one of my projects, so I started with this tutorial:
How to Embed a Collection of Forms
Continued with creating double embedded form, so i have an object, what have objects, and these objects also have objects :D
The Doctrine mapping is good, and works, the problem:
When I click on the "Add new Property" it creates the property, but when I click on the "Add Detail" (which adds a detail to the property) it creates the Detail's fields, but one extra field too:
<label class="required">1label__</label>
The formtype codes:
For the main class
$builder
->add('forma')
;
$builder->add('properties', 'collection',array(
'type' => new PropertyType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false
));
For the property class:
$builder
->add('nev')
//->add('szokokut')
;
$builder->add('details', 'collection',array(
'type' => new DetailType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false
));
For the Detail class:
$builder
->add('description')
//->add('property')
;
These codes are from the buildFrom() functions.
Any idea why is there the extra field?
The first prototype:
<div id="szokokut_storebundle_szokokuttype_properties___name__"><div><label for="szokokut_storebundle_szokokuttype_properties___name___nev" class="required">Nev</label><input type="text" id="szokokut_storebundle_szokokuttype_properties___name___nev" name="szokokut_storebundle_szokokuttype[properties][__name__][nev]" required="required" maxlength="100" /></div><div><label class="required">Details</label><div id="szokokut_storebundle_szokokuttype_properties___name___details" data-prototype="<div><label class="required">__name__label__</label><div id="szokokut_storebundle_szokokuttype_properties___name___details___name__"><div><label for="szokokut_storebundle_szokokuttype_properties___name___details___name___description" class="required">Description</label><input type="text" id="szokokut_storebundle_szokokuttype_properties___name___details___name___description" name="szokokut_storebundle_szokokuttype[properties][__name__][details][__name__][description]" required="required" maxlength="100" /></div></div></div>"></div></div></div>
The second:
<div><label class="required">1label__</label><div id="szokokut_storebundle_szokokuttype_properties_1_details_1"><div><label for="szokokut_storebundle_szokokuttype_properties_1_details_1_description" class="required">Description</label><input type="text" id="szokokut_storebundle_szokokuttype_properties_1_details_1_description" name="szokokut_storebundle_szokokuttype[properties][1][details][1][description]" required="required" maxlength="100" /></div></div></div>
The problem will be here:
Its from the tutorial (with a little change) and it replaces the __name__ field in both of the prototypes :/
var $addPropertyLink = $('Tulajdonság hozzáadása');
var $newLinkLi = $('<p></p>').append($addPropertyLink);
jQuery(document).ready(function() {
propertyHolder.append($newLinkLi);
$addPropertyLink.on('click', function(e) {
e.preventDefault();
addPropertyForm(propertyHolder, $newLinkLi);
});
});
function addPropertyForm(collectionHolder, $newLinkLi) {
// Get the data-prototype we explained earlier
var prototype = collectionHolder.attr('data-prototype');
// Replace '__name__' in the prototype's HTML to
// instead be a number based on the current collection's length.
var newForm = prototype.replace(/__name__/g, collectionHolder.children().length);
// Display the form in the page in an li
var $newFormLi = $('<p></p>').append(newForm);
$newLinkLi.before($newFormLi);
addFormDeleteLink($newFormLi);
var $addDetailLink = $('Részlet hozzáadása');
var $LinkLi = $('<p></p>').append($addDetailLink);
$newFormLi.find('div[id$=_details]').append($LinkLi);
$addDetailLink.on('click',function(e){
e.preventDefault();
addDetailForm($newFormLi.find('div[id$=_details]'),$LinkLi);
});
}
function addFormDeleteLink($FormLi) {
var $removeFormA = $('törlés');
$FormLi.append($removeFormA);
$removeFormA.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// remove the li for the tag form
$FormLi.remove();
});
}
function addDetailForm(collectionHolder,$newLinkLi){
// Get the data-prototype we explained earlier
var prototype = collectionHolder.attr('data-prototype');
// Replace '__name__' in the prototype's HTML to
// instead be a number based on the current collection's length.
var newForm = prototype.replace(/__name__/g, collectionHolder.children().length);
// Display the form in the page in an li
var $newFormLi = $('<p></p>').append(newForm);
$newLinkLi.before($newFormLi);
addFormDeleteLink($newFormLi);
}
You should try to make sure your javascript only acts on the right set of elements, by using a good enough selector.
Show your js for a more detailed answer.
UPDATE
Look at the code
There seems to be an undocumented prototype_name option that you can change from name to whatever you want for one of your prototypes.

How to modify my jQuery script to add a math function and pass the result?

You can find my jQuery in this fiddle http://jsfiddle.net/qSkZW/9/ where the value changes based on your dropdown selection.
What I need is to multiply the selected quantity with a PHP variable. For example when$price = '10'; and you select 3 for quantity, you get an output of 30.
Also, how can I pass the result to display it in the next page ?
Thank you.
What I am trying to clone is the Your Purchase system found here https://www.groupon.com/deals/pizza-delight/confirmation?ms=false&pledge_id=538463 that you add the quantity and you get the final price.
$("#quantity").change(function () {
var str = $(this).val();
$("#here").text(parseInt(str, 10) * <?php echo $price; ?>);
}).change();
Your updated fiddle.
The simplest method is to store the php value in a js variable - which you can reference in your js function. Eg...
<script>
var price = <?php echo $price ?>;
</script>
In addition you can encode php vars as json for easy js access. Eg...
<?php
$products = array(
'Hot socks' => array(
'price' => 10,
'description' => 'These socks are steaming HOT!',
),
'Cool socks' => array(
'price' => 20,
'description' => 'The perfect treat for for feet on those hot summer days!',
),
);
?>
<script>
var products = <?=json_encode($products)?>;
alert('Please buy some hot socks # ' + products['Hot socks'].price);
</script>
edit: example is scarf compatible
Just output the integer directly into the script using php:
$("#quantity").change(function () {
var price = parseInt($(this).val(), 10)*<?php echo $price; ?>
$("#here").text(price);
}).change();
Using PHP 5.4 or short tags enabled:
var price = parseInt($(this).val(), 10)*<?=$price?>
You can just echo onto the page in your javascript:
<script>
// some js above here
php_val=<?php echo $price; ?>
// some js that uses php_val down here
</script>
You can use HTML5 custom attributes:
<select data-price="10"> ... </select>
And then get it with jQuery:
$("#quantity").change(function () {
var el = $(this);
var str = el.val() * el.attr('data-price');
$("#here").text(str);
})
.change();
Storing it in a var price value is not a good solution as it doesn't specify a select element.

Categories