Getting the the input value after focus out - php

I want to add a number of input fields in form which depends on value of previous input fields.
For example:
I have two inputs
if user
1.<tr><td>Number of Articles/Posts/Pages:</td><td><input type="number" name="count" ></td></tr>
2.<tr><td>Keywords:</td><td><?php
$number_of_keywords=$_POST['count'];
i="<input type='text' name='keyword'>";
i++;
i==$number_of_articles;
echo i;
?></td></tr>
For example if user type 3 in count field, then i want to show 3 input field. Number of input fields depend on how much user type in count field.
Please tell me that if this above code will work here and how can i get the count field value at run time?

No, you can't get the count field value at run time, the value must be submitted via a form or passed as a parameter in a query string, so that PHP knows about it.
This question is more appropriated to be tagged as a javascript question, than a PHP question. if you want to do it at run time. If you would like to do it strictly using PHP, then you will have to pass the count value to the server somehow, either by submitting a form, or by sending it via a parameter in a query string, as I have told you before.
Please take into consideration that if this is your real code, it will create n inputs with the attribute
name="keyword"
which is not correct and it might get you into a lot of problems later on.

I would simply use some JS and a php file for this.
What i would do is have an onchange on the first input like
<input type="number" name="count" onchange="getval(this);">
The getval is a JS function that it will according to the input fill in a class with the according number of inputs you like.
function getval(sel){
var load = $.get('yourPHPFILE.php',{number:sel.value);
$(".someClass").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".someClass").html('failed to load');
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success GET VA" );
$(".someClass").html(res);
});
load.done(function() {
console.log( "Completed GET VA" );
});
}
You then in the php file get the value by $_GET['number']
and with a loop there you echo the according number of inputs you like.
someClass is going to be the class that you would like to populate with the inputs.

Related

How to let PHP add another line for every form

I'm using Javascript to create more form fields, to be more specific I'm using jQuery append() to create copies of form fields I already have when a button is pressed.
For example there is an exercise form field, then when someone presses the + button they get another form field to add a second exercise. Now I have to get all these exercises into a PHP file, with no limit so someone could add a 1000 exercises and they would all get sent to my PHP.
I have it setup so jQuery gives them all a name tag with exercisex, the 2nd x being the number of the form field, so the original is exercise1, the second one exercise2, etc.
Now I submit the form and it gets send to another file, submitted.php.
In this file I have it setup for the original form field like this:
$exercise1 = $_POST['exercise1'];
and to put it in an array
$arrExercise = array (
>"exercise1" => $exercise1 );
What I'm looking is for a way that PHP automatically adds this:
$exercise2 = $_POST['exercise2'];
$exercise3 = $_POST['exercise3'];
and adds to the array
"exercise2" => $exercise2
"exercise3" => $exercise3
etc. for all the numbers ofcourse
Now obviously I can't add a unlimited amount into this myself so I was wondering how to get PHP to add them automatically according to how many were added.
I see the obvious risk that someone could spam it by adding a million exercises but that's not a concern for the environment this will be used in.
I tried a for loop but got stuck eventually:
I don't remember the exact code but I tried to add a variable, lets call it n, this variable would get a +1 everytime I pressed the + button so if n=1 at the start, pressing the button once makes it 2, then 3, then 4 etc. and then I got stuck thinking I'd still need to add an infinite amount of
$exercise + n = $_POST['exercise' + n];
if that would even work anyways.
Thanks for any help in advance.
I just solved a similar issue yesterday - here's how.....
The 'key' is to get the form names setup before sending to PHP.
(as you didn't give examples of your form, I will use mine for example - easy enough to port over to your project)
In my project, the user is allowed to add custom menu (nav bar) items as well as links under it, etc.
The way I solved it was to name things where PHP would get a nicely formed array in the $_POST;
<input type="text" name="menu1[Name]" value="">
<input required type="text" name="menu1[data][1][text]" value="">
<input required type="text" name="menu1[data][1][link]" value="">
'rinse/repeat' for all the form values that get added (replacing the '1' in the name with your variable) - you would also replace all 'menu1' with your 'exerciseX'
Now, put a 'Submit' button on the page;
<button type="button" id="custommenusave">Save Changes</button>
A bit of jQuery makes simple work of it....
$("#custommenusave").click(function () {
update_custom_menus();
});
function update_custom_menus() {
var form = $("#form_custom_menus");
$.post("../data/ajax.php", 'function=set_custom_menu&' + form.serialize(), function (data) {
form.submit();
});
}
PHP gets a nice array to work with (I've done a json_encode to make it simpler to see....)
{"menu1":{"Name":"'my menu #1'","data":{"1":{"text":"first","link":"https:\/\/example.com","options":"tab"},"2":{"text":"the second link","link":"http:\/\/example2.com","options":"tab"}}},"menu2":{"Name":"'menu #2!!!!'","data":{"1":{"text":"link in menu #2","link":"https:\/\/example.com","options":"tab"}}}
Then, pull your user's answers and work with them (of course, you should clean any data that comes from a user - no matter how much you 'trust' them!)
This should give you an idea of at least one way (with working code) that you can go.
name of your input should be an array so you can add multiple inputs by same name
<input required type="text" name="exercise[]">
$count = 1;
$finalArray = array();
if(is_array($_POST) && count($_POST) > 0){
foreach ($_POST as $value) {
$finalArray['exercise'.$count] = $value;
$count++;
}
}
print_r($finalArray);

Update table with each input character

I've just asked a question on how to refresh an element without refreshing your page. I've been learning ajax for some hours now, but I'm having trouble getting any implemented.
So what I want to do is this:
Refresh a table containing mainly sql executions, for which I need the input value.
To update it I use onkeyup="Search();" which then forwards my value to another php page.
<input type="text" id="IDsearch" onkeyup="Search()" autofocus>
I know I can get this value on a php page like this:
<script type="text/javascript">
function Search() {
var inputValue = $('#IDsearch').val();
$.post('testAjaxJquery.php', {postname: inputValue},
function (data) {
$('#IDsearch').val(data)
});
}
</script>
and in PHP (testAjaxJquery.php)
<?php
$searchValue = $_POST['postname'];
echo $searchValue;
?>
The problem here is: I don't know how to use the retrieved value and update my existing table with it, without a page refresh. I tried putting all of the code inside a new php file and using $("#refreshOnSearch").load("refresh.php");, no luck.
The essence is: Once a letter is typed, I need an updated version of my table.
I guess you could say I am trying to replicate https://datatables.net/index.
Start with looking inside your $.post function.
Then inspect data using console.log(data) or debugger and looking at what data is. It's possible data is an object and you are trying to set #IDsearch to an object instead of a string or int.
If that is the case you will want to do something like $('#IDsearch').val(data.response);

passing Javascript variable to PHP on form submission

This question follows from my previous question counting the rows in html table using php.
Since I got no working solution, I want to try a new way but dont know how to implement it.
I assign unique ID to each dynamic row added using Javascript. So the count variable in Javascript stores the number of rows present in HTML table. When i submit the form, it is processed by savedata.php. Is it possible to automatically pass the Javascript variable count to savedata.php each time the form is submitted.
Following is a short version of my Javascript file that is used to create unique IDs for elements of dynamically created rows.
var count=2;
function addRow()
{
var table=document.getElementById("studenttable");
var row=table.insertRow(-1);
var cell15=row.insertCell(14);
var ipt8 = document.createElement('input');
ipt8.setAttribute("type", "hidden");
ipt8.id = "text" + count;
ipt8.name = "htmlrow[]";
ipt8.value = count;
cell15.appendChild(ipt8);
count++;
}
Each time a new row is added, count increments, so just passing it to the PHP file will allow to get the number of rows in HTML table. I want to do it automatically each time the form is submitted.
Add this inside your form..
<input name="NumRows" id="NumRows" type="hidden" value="0"/>
And then modify your JS to update the value...
document.getElementById("NumRows").value = count;
Then, in your PHP you can do...
$NumRows = $_REQUEST['NumRows'];
Note that if for some reason NumRows isn't passed with the form (unlikely here but possible elsewhere) then you should do this in PHP...
$NumRows = isset($_REQUEST['NumRows'])?$_REQUEST['NumRows']:0;
Which means "If $_REQUEST['NumRows'] is set, use it, otherwise set $NumRows to 0"
I would suggest never use $_REQUEST, use $_POST for post method forms. If you use $_REQUEST you have no guarantee that the data came from the post data, which leads to security holes in your script. So better use
$NumRows = $_POST['NumRows'];
to access the count value in PHP
Go for Ajax call. Each time when submit button is clicked make an ajax call and send the required data to the any php page.
here go through these links and they will definitely gonna help u
http://www.w3schools.com/jquery/ajax_post.asp
http://api.jquery.com/jQuery.post/

Fill Single Input Based On Prior Select - MYSQL PHP JS?

I want to grab my customers phone number from a MYSQL database and auto populate it into an input box based on users selection of customers in a prior dropdown box.
I've managed to do this in the past when filling in larger amounts of data but what I've previously used seems like a lot of code to auto fill a single input box.
I know how to fill the customer phone based on the data passed from the prior page (although I've deleted that bit here) but I want that data to change dynamically as users use the dropdown.
There's got to be an easy way to do this but I'm a complete newb at js (and only barely proficient at PHP & MYSQL). Can anyone give me a hand?
My PHP/HTML:
$result = mysql_query("SELECT cust_id, name, phone FROM customers ORDER BY name ASC");
$customers = mysql_fetch_array($result);
<label for="customer">Customer:</label>
<select name="customer">
<option value="0">Add New Customer</option>
<? foreach ($customers as $customer): ?>
<option value="<?=$customer['cust_id']?>" <?=($customer['cust_id'] == $parts['cust']) ? "selected" : ""?>><?=$customer['name']?></option>
<? endforeach; ?>
</select>
<label for="custphone">Customer Phone:</label>
<input type="text" name="custphone" value="">
Let me know if you need anything else from me and thanks in advance for helping me out on this.
For this answer, I will use the jQuery syntax, jQuery is a free javascript library, and you'll certainly use it in the future, read more.
To resume, we'll use an event triggered by your select element, when his value is changed, we'll process an AJAX request with some parameters to a PHP page (ajax.php) which returns the phone number of the customer previously choosen.
First you need to include in your HTML web page, the jQuery script, with the <script> tag.
<script src="path/to/jquery.js"></script>
In a second time, we'll create a new javascript script (assuming you add some id's to your HTML elements):
<script type="text/javascript">
$(document).ready(function(){ // When the document is ready
$("select#customers").on("change",function(){ // We attach the event onchange to the select element
var customer_id = this.value; // We retirve the customer's id
$.ajax({
url : "path/to/ajax.php", // path to you php file which returns the phone number
method : "post", // We want a POST request
data : "customer_id="+customer_id, // You'll retrieve this data in your $_POST variable in ajax.php : $_POST['customer_id']
success: function(response) { // The function to execute if the request is a -success-, response will be the customer phone number
$("input#custphone").value(response); // Fill the phone number input
}
});
});
});
</script>
Now, you've all the gear to continue, you should read about jQuery and AJAX.
You just have to create the "ajax.php", retrieve your customer id with the $_POST variable, process the SQL query to retrieve the phone number, then, return it with an echo.
Sounds like you want to look into AJAX. jQuery.ajax() makes it pretty easy.
Basically, you have a page on the server that queries the database and returns a JSON encoded string that the javascript can convert (using jQuery.parseJSON)back into an array and populate the list!
Use .change() to bind an event to the dropdown's change event. This will fire whenever the selection changes. Inside, you want to get the value (see demo on that page) and send an AJAX request to the server.
The PHP script on the server will query the database and return a JSON string. In the success function of the jQuery AJAX block you can populate the new list with the decoded information. See this page for a tutorial on how to add items to a select.

Get the value of form input fields loaded by Ajax, dynamic input fields and static input fields

This is a bit complex so I hope I word this right.
I have a form that loads a list of options and starts with one static input:
<span id="keyword_list_out" class="input"><input class="keys margin-bottom" type="text" name="keywords[]" />
When the page is loaded an Ajax call displays additional input fields that belong to the list such as:
<span class="field-wrapper"><input class="keys" type="text" name="keywords[]" value="Option One" /><a class="remove-keyword" href="javascript:void(0);"><img src="images/icons/cross-button-icon.png" /></a></span>
<span class="field-wrapper"><input class="keys" type="text" name="keywords[]" value="Option Two" /><a class="remove-keyword" href="javascript:void(0);"><img src="images/icons/cross-button-icon.png" /></a></span>
These options are prepended to the top of the first static input field ID: keyword_list_out.
The user can dynamically add more input fields and they can remove existing fields.
All of this so far works fine. My problem is accessing the data contained within the input fields. I need to be able to perform three functions once the form is submitted:
If the user has removed an option I need to remove this from the database
If the user has added a field I need to insert this into the database
If the user changes the value of an existing field I need to update this in the database
I can access the data within the input fields by using the input name 'keyword_name[]' as an array, and then I can loop through the array.
However this does not address existing options that have a specific ID number. I can assign ID numbers to the fields that were loaded from the Ajax call, however the static field and user added fields wont have ID numbers, as these arent necessary. These fields will simply be inserted into the database.
So I guess my question is how would I go about determining which existing option belongs to what ID number in the database. I should add that the options are not uniquely named.
I considered something such as:
Provide ID numbers only for the Ajax loaded fields
Upon submit loop through each input and prepend the ID to the end of the name value using a delimiter the user wont provide. IE: Option Two---1
With PHP looping through the array and exploding the array value where it matches '---'
If a match was found on '---' update the database, else insert into the database
Any thoughts?
UPDATE
I have divided the input fields into two arrays: existing_options[] and new_options[].
In my Jquery script prior to posting i have added:
var existing_options = $('input[name=existing_options]').attr('value');
var new_options = $('input[name=new_options]').attr('value');
The Ajax data being sent is:
'existing_options[]=' + existing_options + '&new_options[]=' + new_options;
However PHP is returning that these values are strings and not arrays. Missing something here....
I would suggest on using an auto increment id on the database side. When you load the page, have the id placed like so <span class="field-wrapper" id="$row[id]"> and than when deleting use:
$('.remove-keyword').on('click', function(){
var id = $(this).parents('span').attr('id');
place ajax post here with data sent being this id.
});
And basically it'll be the same for adding a keyword, except use ajax to post to your script, and use mysql_insert_id(); in your script as a returning id than dynamically create the next row.
When the fields are loaded via AJAX assign them IDs
<input class="keys" type="text" id="keyword_11" name="keywords[]" value="Option Two" />
<input class="keys" type="text" id="keyword_12" name="keywords[]" value="Option Two" />
On submit clicked then in jQUery you can loop through the keywords
var new_keywords=Array();
var existing_keywords=Array();
$("input[name^='keywords']").each(function(){
var id = $(this).attr("id");
var val=$(this).val();
if(id=="" && val!="")
{
new_keywords.push($(this).val());
}
else if(id!="")
{
var keyword_id=id.split("_")[1];
existing_keywords.push({"id":keyword_id,"val":val});
}
});
// call AjAX function add new_keywords to database
// call Ajax function to update existing keywords
UPDATE 1
In the success function of adding new_keywords to database do update the existing dom via AJAX so that if you add new keyword, then you edit it and try to save it will have the ID associated with it.

Categories