how to get html array data to another laravel view - php

assuming that i have an HTML textbox with a name with an array:
<input type="hidden" id="text_array" name="text_array[]" class="test">
and i have a jquery code that gets the data on the textbox:
$('.test').each(function(){
arr = $(this).val();
});
how can i get the array content and transfer it into another laravel view and then print it? i tried to get it by using echo my controller but i have recieved comments about printing outputs in a controller is a bad practice.

Hmm i would recommend to use a Database or Session storage. But one idea is to save the value via JavaScript into a cookie.
Disclaimer: Untested ;)
Save the Value:
$('.test').each(function(){
arr = $(this).val();
document.cookie = 'mycookie=' + arr +'expires=DateHere;path=/'
});
Get it (somewhere):
$value = $request->cookie('mycookie');

Related

Jquery.ajax load data from html using php

I have some problems loading input field from html using php. I am using jQuery Ajax $.post function to send my data from input filed to php file in order to do the query from the database.
I have fixed the code. Code below is working perfectly.
Here is the html from my main page
<input class="detail" maxlength="60" name="detail" placeholder="Type to search">
<button class="searchbtn" name="search">Search</button>
and this is the jQuery Ajax part
$(".searchbtn").click(function(e) {
makeAjaxRequest();
});
function makeAjaxRequest(){
var input = $(".detail").val();
$.post("search.php",{detail:input},function(data,status){
$('#resultTable tbody').html(data);
});
Then last part is the php file (search.php)
if (isset($_POST['detail'])) {
$data = $_POST['detail'];
$query = "SELECT * FROM products WHERE ".%data;
$result = $conn->query($query) or trigger_error($mysqli->error."[$sql]");
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
}
Now it worked perfectly. Thanks for the answer.
You are extracting $_POST['detail'] on your server side page, but while sending on client side, you are sending like this, $.post("search.php",input.
Data should be sent data as PlainObject or string. I mean, every POST data should have some index to get referenced on the other end.
Since you are extracting with index detail, add detail on following like:
$.post("search.php",{detail:input},function(data,status){
See : jQuery : $.post()
currently you're just sending a string with no key/value. You need to send a key/value pair as your data parameter, either as a string or an object (object is safer, as it'l get automatically urlencoded)
$.post("search.php",{detail:input},function(data,status){
You could try this.
function makeAjaxRequest(){
var input = $(".detail").val();
$.post("search.php",
{detail: input},
function(data,status){
$('#resultTable tbody').html(data);
});
}

Dynamic data in a custom attribute

I use
$('.test').attr('data-payment', 'value');
to create a custom attribute for
<table class="test" data-payment="value">
further down the table I have
<td class="outlay">100</td>
The table is outputted using a PHP script, it is a sort of calculator that updates when form fields are changed and a button is clicked.
My question is how to insert the contents of .outlay into the data-payment value?
You can do something like this
$('#button').clicked(function(){
var val = $('.outlay').text(); // Store content in val variable
$('.test').attr('data-payment', val); // change data-payment value
})
If you're using data-attributes, you can use things like:
$('.test').data('payment');
In your case, you'll want something like:
var outlay = $('.outlay').text();
$('.test').data('payment', outlay);

Adding Table Cell Contents to PHP $_POST

From my understanding, the only way to retrieve $_POST data is using the name attribute of the element, like so:
<INPUT type="text" name="txt">
and the PHP portion:
<?php $text = $_POST["txt"]; ?>
I've got a table with cells containing plain text, for example:
<td class="textField" id="txt1"> Some text </td>
Is there anyway to post the text in these table cells and retrieve them using either the class or id? Maybe there is a clever way to get around this? <td> doesn't have a name attribute thus the reason for my question.
Thanks!
You can use ajax, getting values from the table with javascript. JQuery is a good library for this:
http://api.jquery.com/category/ajax/
$_POST and $_GET come from the request. Meaning the browser sends them with the headers and PHP provides an interface to them with $_POST, $_GET, $_COOKIE, and $_REQUEST. The browser doesn't send contents of a table in the request.
If you're trying to make a field 'read-only' you're going about it the wrong way. If a field is read-only you should never trust the browser to re-send that same value.
To retrieve values from many form-fields who all have the same name (because you generate them with a loop in PHP), append brackets to the names of your fields.
Simple example:
<form method="post">
<input type=text name="myfield[]">
<input type=text name="myfield[]">
<input type=text name="myfield[]">
<input type=text name="myfield[]">
</form>
If you add to your code:
<?php print_r($_POST); ?>
you'll notice that the $_POST variable is populated with an array named "myfield" having 4 values from $_POST['myfield'][0] to $_POST['myfield'][3]. You may then use a foreach loop in PHP to retrieve all values.
The solution that ended up working for me was to grab the data using jQuery, encode it in JSON, and add it to a serial array of the rest of the form data.
$("#orderForm").submit(function(e) {
e.preventDefault();
// Get NON-INPUT table cell data
var subtotal = new Array();
$('#priceTable td.subtotal').each(function() {
subtotal.push($(this).html());
});
// Get all INPUT form data and organize as array
var formData = $(this).serializeArray();
// Encode with JSON
var subArray = JSON.stringify(subtotal);
// Add to formData array
formData.push({name: 'sub', value: subArray});
// Submit with AJAX
$.ajax({
url: "submitOrder.php",
data: formData,
type: 'post',
success: function(data) {
alert(data);
}
});
});
And on the PHP side:
$subtotals = json_decode($_POST['sub']);

how to store php object to access its data on click with javascript

I'm trying to figure out the least obtrusive and least computationally expensive way to store PHP objects coming from my MySQL database such that their data can be rendered by JavaScript on click by a user.
Currently, I'm storing the data as custom attributes on a button. But this generates a lot of code and I've heard is "slow". I'm wondering if I should JSON encode my PHP object, $items (see below), and how that JavaScript would then look. Note I'm using Codeigniter for the PHP so that's what up with the alternate foreach loop syntax.
Here's where I'm at so far with the HTML/PHP:
<img id="img"></img><a id="url"></a> <!--elements where data is rendered on click-->
<? foreach($items as $item):?>
<button data-id="<?=$item->id?>" data-url="<?=$item->url?>" data-img="<?=$item->img?>">click<?=$item->id?></button>
<?endforeach;?>
And here's my JS:
$(document.body).on('click', 'button', function(){
var $this=$(this), id=$this.data('id'), url=$this.data('url'), img=$this.data('img');
$('#img').attr('src', img);
$('#url').attr('href', url).html(url);
});
Most of my site's data is coming from PHP via MySQL and I've long been confused by the issue of when should I convert that data to a JavaScript array/JSON or not.
If you json_encode your $items array (assuming it only consists of data you will want in JS), you can assign this to a JS variable:
<script>var items = <?php echo json_encode($items); ?></script>
You can then remove the data-url and data-img attributes. Then, within your JS code:
var $this = $(this), id = $this.data('id'), url = items[id].url, img = items[id].img;
// the rest of your code
Edit: when you move the click handler in a separate file, you would get something like this:
function setup_click(items) {
var $img = $('#img'), $url = $('#url');
$('button').click(function(evt) {
var id = $(this).data('id'),
url = String(items[id].url),
img=String(items[id].img);
$url.attr('href', url).html(url);
$img.attr('src', img);
});
}
here's a JSfiddle showing off the javascript/JSON part: http://jsfiddle.net/fz5ZT/55/
To call this in one shot from your template:
<script src="[your ext script file path].js"></script>
<script>setup_click(<?php echo json_encode($items); ?>);</script>
Hope that helps :)

Using oninput function with php?

As far as I've seen, the oninput funciton in HTML is always used with Javascript. Is it possible to add PHP into it?
<input name="boxNo" type="number" value="1" oninput="<?php $intro = $intro . "boxNo.value"?>"/>
If it is possible, how should I structure my code?
Of course you can't call php directly from html as shown in your example.
But you can use AJAX to do it, using JS, jQuery and PHP script placed on your server.
For example:
JavaScript:
$('input[name=boxNo]').input(function(){
var inputObject = $(this);
var value = inputObject.val();
$.post('/yourfileOnServer.php', {value: value}, function(data){
//in the variable data you've already got your info from the php
inputObject.val(data); //inserting data to the value of your input
});
});
PHP:
if(!isset($_POST['value'] || empty($_POST['value'])){
exit; //Avoiding security problems
}
$value = $_POST['value']; //In this variable you store your value, entered to the input
// DO something with this value
echo $value; //and print it (return to the JS)
Good luck!

Categories