Detect ID of each form submitted - php

I try modify plugin of cms and have problem with forms
Actually i have system which generate polls for send votes and all forms are as this :
<div class="sp-poll" id="poll-<?php echo $pollid; ?>">
<p class="sp-question">
<?php echo $question; ?>
</p>
<form method="post" action="<?php echo $postFile; ?>" id="spe_form-<?php echo $pollid; ?>"></form>
</div>
The javascript process:
jQuery(function () {
var $ = jQuery; // Because `$` is easier than using `jQuery`
$('.sp-poll form').submit(formProcess); // Access formProcess() when the poll is submitted
/**
* Form Process
* Process through the form
*
* #param object e
*/
function formProcess(e) {
e.preventDefault();
var poll = $('input[name=poll]').val(),
answer = $('input[name=answer]:checked').val(),
div = $(this).parent(),
action = $(this).attr('action');
$(this).slideUp('slow', function () {
updatePoll(action, poll, answer);
});
}
});
The problem it´s each form have different ID , and the processor only detect the first id , for example if i have 5 forms with differents IDs all time detect only one ID of one form but no the others when launch the process form , i try use :
jQuery(".sp-poll form").attr(id);
But always detect the same number and no detect each ID in each form
PS : I need the send the form ID attribute since the form repeats itself each and every time I create a poll on the page. I want to be able to detect data for each different form using their ID to sort them out.

When using HTML forms, only information stored in FORM FIELDS or the URL are sent back to the server. Element IDs have nothing to do with forms at all - they're for UI manipulation.
If you want to pass the form ID back to the server, use a hidden field.

Related

Acces mysql value in html to send to php file through jquery

I want to get the value of id so that I can delete the data from mysql based on the id number
This is a project for events, the main idea here is I want to get the id number of the event based on the clicked button, so that I can update/delete the event based on the id number.
Code for displaying details
<?php $sql= "SELECT event_name, event_date, event_id FROM events WHERE event_status=0";
$result= mysqli_query($conn, $sql);?>
while($row = mysqli_fetch_assoc($result))
{
echo '
<div class="pending-card">
<div class="pending-image">
</div>';
echo " <div class='pending-title'>
<h1>{$row["event_name"]}</h1>
</div>";
echo " <div class='pending-des'>
<p>{$row["event_date"]}</p>
<button class='choice-pending'><a href='detail.php'>Read More...</a></button>
<input style='display: none;' type='text' id='test-pend' value='{$row["event_id"]}'>
</div>
</div>
";
}
Jquery code
Here I tried to check if this works by making an alert, but after i press the button, the id number that came out is not correspond with the button i click
$(document).ready(function(){
$('.choice-pending').click(function(){
alert("Value: " + $('#test-pend').val());
});
});
Can anyone tell me where did I go wrong
Example, the event i pressed is suppose to be 34, but the alert shows 26 which is the first event id in the code for displaying details
You can use data-* attribute in your element.
Based on https://www.w3schools.com/tags/att_global_data.asp
The data-* attributes is used to store custom data private to the page
or application.
The data-* attributes gives us the ability to embed custom data
attributes on all HTML elements.
The stored (custom) data can then be used in the page's JavaScript to
create a more engaging user experience (without any Ajax calls or
server-side database queries).
The data-* attributes consist of two parts:
The attribute name should not contain any uppercase letters, and must
be at least one character long after the prefix "data-" The attribute
value can be any string Note: Custom attributes prefixed with "data-"
will be completely ignored by the user agent.
<button class="choice-pending" data-event-id="<?= $row['event_id']; ?>">Read More...</button>
Then in your script you can access the clicked button:
$(".choice-pending").click(function() {
if($(this).attr('data-event-id') !== undefined) {
// You can do ajax call here to your detail.php
// Or you can simply create a hidden field inside your form, assigned the data-event-id value to it, then $("form").submit();
} else {
/** Error message here, maybe? */
}
});
First remove your anchor tag inside button and use only anchor or button and print your html with assign some dynamic class or id into each to make them unique like this.
<div class='pending-des'>
<p>{$row["event_date"]}</p>
<a class='choice-pending-{$row["event_id"]}' href='detail.php'>Read More...</a>
<input style='display: none;' type='text' id='test-pend-{$row["event_id"]}' value='{$row["event_id"]}'>
</div>
Now bind click event on it-
$(document).ready(function(){
$('.pending-des').each(function(){
$(this).on('click', 'a[class^=choice-pending-]', function(){
alert($(this).find('input[id^=test-pend-]').val());
});
});
});

Populate a drop-down list depending on what is selected from another drop-down list from two variables PHP

I have a question on how to populate a drop-down list depending on the value that is selected in another drop-down list.
I'm working with an MVC pattern and when the view loads, it already brings me two variables with the values I need. What are $tipohardware and $tiposoftware.
So I wouldn't need to call a .php file again to get the data, because it's already loaded.
My static drop-down list is:
<select id="producto" class="form-control" required>
<option value="">Seleccionar..</option>
<option value="1">Hardware</option>
<option value="2">Software</option>
</select>
And the dynamic drop-down list I want to populate depending on what is selected in the drop-down list "producto" is:
<select id="tipoproducto" name="tipoproducto" class="form-control">
</select>
I already have two variables that have the data of the tables, "tipo_hardware" and "tipo_software". What are $tipohardware and $tiposoftware.
So, for example, if I select the "Hardware" option in the drop-down list, the second drop-down list should be filled with the data of the variable $tipohardware.
On the other hand, if I select "Software" the drop-down list should be populate with the values of the variable $tiposoftware.
Here's my controller if you needed to.
<?php
namespace app\controllers;
use \app\models\Hardware;
use app\models\Software;
use app\models\TipoHardware;
use app\models\TipoSoftware;
use \Controller;
use \Response;
class IngresarProductoController extends Controller
{
public function actionIndex()
{
$softwares = Software::all();
$hardwares = Hardware::all();
$tiposoftware = TipoSoftware::all();
$tipohardware = TipoHardware::all();
Response::render("ingresarProducto", ["hardwares" => $hardwares,
"softwares" => $softwares, "tipohardware" => $tipohardware,
"tiposoftware" => $tiposoftware]);
}
}
I think I should call a php code in a javascript onchange function like:
$("#producto").on("change",function){
<?php
foreach($tipohardware as $tipohard) {
?>
<option value="<?php echo $tipohard->idtipo_hardware ?>"><?php echo
$tipohard->nombre_tipo_hardwarecol ?></option>
<?php
}
?>
}
});
But I dont know how I can continue with that,
Thanks for the help!
You are mixing frontend script with backend script, which does not work. Backend will build the entire page before the frontend starts doing it's thing. PHP creates the DOM and JavaScript manipulates the DOM after PHP spits it out. That is why your jQuery does not work/update.
For example, if you do this:
$('.button').on('click',function(){
var whatever = <?php echo rand() ?>;
alert('This value is'+whatever);
});
It will run the php first so you will end up with the random number off the bat:
$('.button').on('click',function(){
var whatever = 3241231;
alert('This value is'+whatever);
});
No matter how many times you click the button element, it will always say 3241231 until you reload the page when PHP will run the rand() function at load.
To make it load in real time, you need to create an ajax listener to receive a value from the target, send to the backend PHP, then when that backend page responds, you place the response back into your currently loaded page, altering the DOM.
A simple example would be:
/index.php
<?php
# Create the back end to listen for your front end ajax
if(!empty($_POST['test'])) {
# Do your code here to send back.
$rand = rand();
die('Ajax done! Here is a random number: '.$rand);
}
?>
<!-- CLICK ELEMENT -->
<div id="button">CLICK</div>
<!-- PLACEMENT ELEMENT -->
<div id="response"></div>
<script>
$(function(){
// When you click the div
$('#button').on('click',function(){
// Fire the ajax to the same page (you may want to do a
// different page in production). Note, I am referencing a new instance of
// of index.php in the background and sending $_POST['test'] = true as noted
// in the data section of the ajax below.
$.ajax({
'url': '/index.php',
'type': 'post',
// Send the data from the click or whatever
'data': {
'test':true
},
// If there are no server errors,
'success': function(response){
// place the phrase 'Ajax done! Here is a random number: 123124'
// back into the placement div
$('#response').text(response);
}
});
});
});
</script>
In this example, the random number will change each click of the div. Anyway hope this example was helpful.

php how to handle hyperlink like a POST instead of GET?

I will have a query that return a set of results, and these results will be in hyperlink form as shown below:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
Now user get to click on this hyperlink and get routed to abc.php?cif=$cif..
My question is, is it possible to only show abc.php to user, just like a POST method, and $cif remains available at abc.php?
As #Flosculus said above, the "best" solution to simulate a post request is doing something like proposed here: JavaScript post request like a form submit
However, despite it's surely a reliable solution, I'm wondering you just don't use sessions instead, something like:
From the page where you set the cif variable:
session_start();
$_SESSION['cif'] = $row['cif'];
In abc.php:
session_start();
if (isset($_SESSION['cif'])) {
// Do what you need
}
EDIT::
Another (possible) solution is setting an hidden input and silently submit a form when you click on an anchor, like this:
From your example, instead of:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
You do this:
When you print all the entries, please add this first (from PHP):
<?php
echo <<<HEADER
<form action="abc.php" method="post" id="submitAble">
<input type="hidden" name="cif" id="cif" value="{$row['cif']}">
<table>
HEADER;
// Get data from your query.. Here is an example:
while ($row = mysli_fetch_assoc($query)) {
echo <<<ENTRY
<tr>
<td>{$row['cif']}</td>
</tr>
ENTRY;
}
echo "</table> <!-- \table collapse --></form> <!-- \form collapse -->";
?>
Then, if you're using jQuery (thing that I'm recommending), simply add an event listener in javascript, like this:
$('.cifSetter').on('click', function(e) {
e.preventDefault();
$('#cif').val($(this).data('cif'));
$('#submitAble').submit();
});
If you don't have jQuery, use this instead:
var cifSetter = document.getElementsByClassName('cifSetter');
for (var i = 0; i < cifSetter.length; i++) {
cifSetter[i].addEventListener('click', function(e) {
e.preventDefault();
var cif = document.getElementById('cif');
cif.value = this.dataset.cif;
document.getElementById('submitAble').submit();
});
}
In both ways, whenever an anchor gets clicked, it will prevent its standard behavior (redirecting) and will instead set the value of an hidden field to the value of the CURRENT "cif" and submit the form with the desired value.
To retrieve the desired value from abc.php, just do this:
$cif = $_POST['cif'];
However, keep in mind that the hidden field is editable by the client (most persons won't be able to edit it, though), therefore you should also sanitize your data when you retrieve it.
Sessions could do it but I'd recommend to just use $_POST. I dont get why you wouldn't want to use POST.

How to use reload/refresh when click cross then jquery modal will be close

I have used same form for adding and edtting data. Adding and Editting is done successfully and I am refreshing after editing and adding. But I need some solution which is below
My jquery code is below
$(".update_vehicle_info").click(function(){
var hdn_id = $(this).attr('data-hdn_id');
$("#vehicle_form_div").find("#hdn_id").val(hdn_id);
var post_url = "<?php echo base_url();?>index.php/spc_con/get_vehicle_info_data/" + hdn_id;
$('#hdn_id').empty();
$.getJSON(post_url, function(response){
document.getElementById('financial_year_id').value = response.financial_year_id;
document.getElementById('vehicle_id').value = response.vehicle_id;
document.getElementById('brand_id').value = response.brand_id;
document.getElementById('country_id').value = response.country_id;
document.getElementById('reg_no').value = response.reg_no;
document.getElementById('capacity').value = response.capacity;
document.getElementById('running').value = response.running;
document.getElementById('serviceable').value = response.serviceable;
document.getElementById('condemned').value = response.condemned;
});
$("#vehicle_form_div").dialog("open");
});
I have screen shoot which is below
If i click edit button, if i don't edit now and if click Add Vehicle Info then edit field value has stayed but
I need when i click edit and click cross without editing. Then Page will be refresh/reload which if i click Add Vehicle Info then every field Data won't stay it.
How to solve it, Please help me.
UPD:
give to each of your tr some unique id, for example <tr id="tr_pk_23">...</tr> where 23 is a primary key of the row in you databse.
<button onClick="showModalForm(this,23);">EDIT</button>
function showModalForm(button,id){
var $tr = $(button).closest('tr');
/*
* Send ajax request to your php script /myScript.php?id=23
* Find data in database by id, and generate modal form with php, send it back to browser append to body and show it to user.
*/
}
Update button in modal form must be an ajaxButton. So onClick should be assigned as function
<button onClick="saveDataAndUpdateRow(this,23);">UPDATE</button>
JavaScript:
function saveDataAndUpdateRow(button,id){
var $form = $(button).closest('form');
var data = $form.serialize();
/*
* Send data to another script, save your data in DB and generate a new <tr> with updated values
*/
var $new_tr = #ajaxresponse;
var $old_tr = $('#tr_pk_'+id);
$old_tr.after($new_tr);
$old_tr.remove();
}
Feel free to ask me any questions about this concept.

How to pass data from input form to js on another page

I have a page where a user enters an address and clicks search. The user should be taken to the next page which should contain a google map with the address the user specified. How should I pass the address from the form on page 1, to js on page 2 where I can manipulate it with the google maps api? I'm using codeigniter btw.
EDIT:
My ideal solution would be to use flash data or pass the address in the url the codeigniter way. My problem is i'm not sure how I would retrieve the data if I used either of these methods.
In the CodeIgniter view for page 1:
<form method="POST" action="getMap">
<input type="text" name="address" value="" />
<input type="submit" value="Map It!" />
</form>
In the CodeIgniter view loaded by getMap() method of the controller (in other words, in page 2):
<script>
address = "<?php echo htmlspecialchars($this->input->post['address']); ?>";
// create the map with the address here
</script>
You'll want to take care to do some validation on the user input.
Use url variables to accomplish this. An example might look like this:
http://www.testurl.com/mappage.html?address=someaddress&city=somecity&state=ca&zip=12345
You can pick up the values of these url variables in javascript and pass it to the google map.
Do you want the user to be able to save the url?
If you don't, just use POST in the input field and retrieve the data in the second page this way (inside the javascript):
var address = '<?=$this->input->post('address')?>'
Otherwise:
In javascript, in the first page, prevent the default action on form submit and instead redirect the user to [url of the second page]/[stuff written in the form] (I can give you a jquery example if you want);
In the second page controller (let's pretend the function is called get_map and it is in the maps controller you get the data in this way
function get_map($address = null)
Now you have the input address. Pass it to the view that should contain the map.
Why don't you simply print the POSTed information via PHP on the destination page using Javascript literals syntax?
As an example, if your form POSTs the following (both GET or POST query):
firstname=aaron&lastname=pink
you can print in a destination PHP page:
<html>
<head>
<script type="text/javascript">
var fname = "<?php echo addslashes($_POST['firstname']); ?>";
var lname = "<?php echo addslashes($_POST['lastname']); ?>";
</script>
</head>
<body>
...
<button onclick="alert(fname);">Say First Name!</button>
</body>
</html>
Then, you can simply use fname and lname Javascript vars as you wish, just as my sample button does on click!
I hope it was helpful, even if very simple :)
If you are using jquery, you can use the $.cookie plugin to transfer informations between PHP and Javascript.
or 2. Send data from 1. page per $_GET or $_POST and catch the data in 2. page
<script>
var myData = '<?php=htmlspecialchars($_POST['data_from_page1']);?>';
</script>
#Catfish you're getting all confused. The objective of making your urls "pretty" and having them resemble paths / files rather than query strings is for SEO & user friendliness. You shouldn't really be including any form input in as a "pretty" url. Either send your address data via the $_POSTS global or send it as a query string. CI uses the [QSA] flag in its mod_rewrite definitions in the htaccess file so you're totally fine to stick on a (IMO) semantically correct query string on the end.
Anyway, to the code.
On form.php:
<form action="map.php" method="get">
<input type="text" name="addr" />
</form>
On map.php:
<?php
$addr = $this->input->get('addr');
// or $addr = $_GET['addr'];
echo $addr;
?>
You can use sessionStorage on modern browsers to stock your datas between pages inside the same browsing session.
For older browser you can use an hacky solution that allow you to stock datas inside the window.name
if( typeof sessionStorage !== 'undefined' ){
myStorage = sessionStorage;
}else{
myStorage = {
setItem:function(key,val){
this.removeItem(key);
window.top.name+=(window.top.name.length?'&':'')+escape(key)+'='+escape(val);
}
,getItem:function(key){
var r = window.top.name.match(new RegExp('(^|&)'+escape(key)+'=([^&=]*)($|&)'));
return r?unescape(r[2]):null;
}
,removeItem:function(key){
window.top.name = window.top.name.replace(new RegExp('(^|&)'+escape(key)+'=([^=&]*)(?=$|&)'),'');
}
};
}
Now you can use myStorage.setItem('key',value) with each of the form fields you want to keep and retrieve them on the next page with myStorage.getItem('key')
It's not more complicated than using cookies, and have the benefits to not transfer the cookie datas in each request header.
Hope this help..
Why not do it entirely in JavaScript, using the Google Maps API ?
Let's say that your Map is initialized with the variable var Map and the Geocoder in the var Geocoder and that you have an <form id="searchForm">Address:<input /> <br /> <input type="submit" /></form>.
I'm also assuming you have jQuery loaded, so:
<script type="text/javascript">
$('#searchForm').submit( function(e) {
e.preventDefault();
var searchString = $(this).find('input:first').val(); // get the address
Geocoder.geocode( { 'address': searchString}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
Map.setCenter(results[0].geometry.location);
} else {
alert("Geocode error: " + status + "\n" + "Try another address");
}
});
});
</script>
Demo here: http://jsfiddle.net/toxik/Xjy3S/embedded/result/
Codeigniter sessions would be the easiest to work with.
Once you get the address submitted, set some userdata like so.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mycontroller extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//do something from post
$this->session->set_userdata('street', $this->input->post('street'));
$this->session->set_userdata('city', $this->input->post('city'));
$this->session->set_userdata('state', $this->input->post('state'));
$this->session->set_userdata('zip', $this->input->post('zip'));
//then redirect to the next page
redirect('mycontroller/map');
}
else
{
//load the form
$this->load->view('address_form');
}
}
function map()
{
$data = array(
"street" => $this->session->userdata('street'),
"city" => $this->session->userdata('city'),
"state" => $this->session->userdata('state'),
"zip" => $this->session->userdata('zip')
);
$this->load->view('map' $data);
}
}
Set the values in a hidden input. Just have javascript grab the value of that inputs ID...
check this
// JavaScript function function abc(pram1, pram2) { alert(pram1 + pram2); } // end of JS function
now call this function on your search form. pass all parameters you want to move other page
like
<a name="search" href="javascript:void(0)" onclick="abc('param1','param2')> search </a>

Categories