I'm using this
auto-complete plugin with my new project. It's working fine. See image
But I want to populate these fields when I select the result.
Here is my code:
var as = $("#query" + x + "").autocomplete({
minChars: 1,
maxHeight: 100,
serviceUrl: 'index.php?r=purchaseorder/list',
});
IN CONTROLLER
public function actionList() {
$criteria = new CDbCriteria;
$criteria->select = array('id','description','unit','rate');
$criteria->addSearchCondition("description", $_GET['query']);
$criteria->limit = $this->limit;
$items = Item::model()->findAll($criteria);
$suggestions = array();
$data = array();
foreach ($items as $c) {
$suggestions[] = $c->description;
$data[] = $c->id;
}
header('Content-type: application/json; charset=utf-8');
echo CJSON::encode(
array(
'query' => 'q',
'suggestions' => $suggestions,
'data' => $data
)
);
exit;
}
grid jquery
jQuery("#addrow").click(function() {
jQuery(".item-row:last").after('<tr class="item-row">\n\
<td>\n\
<span id="delete' + x + '" style="cursor: pointer" class="icon-remove"></span>\n\
</td>\n\
<td class="item-code"><input autocomplete="off" name="code[]" id="code' + x + '" type="text" class="input-code"/></td>\n\
<td class="item-description"><input autocomplete="off" name="q" id="query' + x + '" type="text" class="input-description"/></td>\n\
<td class="item-unit"><input readonly autocomplete="off" name="unit[]" id="unit' + x + '" type="text" class="input-unit"/></td>\n\
<td class="item-qty"><input name="qty[]" autocomplete="off" value="0" id="qty' + x + '" type="text" class="input-qty"/></td>\n\
<td class="item-rate"><input readonly name="rate[]" autocomplete="off" value="125.25" id="rate' + x + '" type="text" class="input-rate"/></td>\n\
<td class="item-discount"><input name="discount[]" autocomplete="off" value="0.00" id="discount' + x + '" type="text" class="input-discount"/></td>\n\
<td class="item-total"><input name="total[]" readonly autocomplete="off" value="0.00" id="total' + x + '" type="text" class="input-amount"/></td>\n\
</tr>');
controller is already there
I have done it like this...
IN JQUERY....
var as = $("#query").autocomplete({
minChars: 1,
maxHeight: 100,
serviceUrl: 'index.php?r=purchaseorder/list',
onSelect: function(suggestion) {
var row = $(this).closest('tr');
row.find('.input-code').val(suggestion.id).attr('readonly', 'readonly');
row.find('.input-description').attr('readonly', 'readonly');
row.find('.input-unit').val(suggestion.unit).attr('readonly', 'readonly');
row.find('.input-rate').val(suggestion.rate).attr('readonly', 'readonly');
row.find('.input-qty').focus();
}
});
AND THEN IN CONTROLLER
public function actionList() {
$criteria = new CDbCriteria;
$criteria->select = array('description', 'id','unit','rate');
$criteria->addSearchCondition("description", $_GET['query']);
$criteria->limit = $this->limit;
$items = Item::model()->findAll($criteria);
$suggestions = array();
$x=0;
foreach ($items as $c) {
$suggestions[$x]['value'] = $c->description;
$suggestions[$x]['id'] = $c->id;
$suggestions[$x]['rate'] = $c->rate;
$suggestions[$x]['unit'] = $c->unit;
$x++;
}
header('Content-type: application/json; charset=utf-8');
echo CJSON::encode(
array(
'suggestions' => $suggestions,
)
);
exit;
}
thats it...!
Sample code as shown below
$('#yourautoCompleteId').change(function(){
var selecteddata=$(this).val();
$.ajax({
url: "'.$this->createUrl('Controller/yourMethod').'",
data: {
//special:specialisation,
data :selecteddata,
},
type:"GET",//you can also use POST method
dataType:"html",//you can also specify for the result for json or xml
success:function(response){
//write the logic to get the response data as u need and set it to the fields
$("#dataId").val("SetHere");
$('#quantityId').val("setHere");
},
error:function(){
//TODO: Display in the poll tr ifself on error
alert("Failed request data from ajax page");
}
});
})
get the data in the controller using post and query with this data and send the result as u need and set to the fields as shown in the sample
Related
I have the following script that i use to update multiple rows from the SQL table ''account''.
In the table ''account'' I have column named category, the cat_ID form table ''categories'' is inserted as value in the table ''accounts'' in the column category.
I now have those values hard coded and i want them to be selectable as dropdown list from the table categories, cat_ID as value and cat_name as name of the category. I have tried a lot, googled a lot, but i cant get this to work.
All i want is to have the options fetched from the SQL table categories and use them as dropdown select option in the update option of the script, which are now hard coded now and is working fine.
The hard coded part:
html += '<td class=\"footer\"><select name="category[]" id="category_'+$(this).attr('id')+'" class="editbox"><option value="4">Moet gerankt worden</option><option value="6">Wordt gerankt</option><option value="5">Current BF Holder</option><option value="7">Main Account</option><option value="8">Money Private</option><option value="11">CB/Suc</option><option value="13">Casino Holder</option><option value="15">Wordt Gestockt</option><option value="10">Dont use, ask first!</option><option value="14">Stockgeld</option><option value="0"></option></select></td>';
The SQL select call:
$query = "SELECT a.*, c.cat_color, c.cat_name, c.cat_txt FROM account a LEFT JOIN categories c ON c.cat_ID = a.category WHERE `betaald` = 'Yes' AND `secret` = 'No'";
$statement = $connect->prepare($query);
if($statement->execute())
{
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
The whole script.
<script>
$(document).ready(function(){
$(document).on('click', '.loginBtn', function(e) {
e.preventDefault();
var row = $(this).closest('tr');
var tds = row.find('td');
var name = ''
var cnt = 0;
$.each(tds, function() {
if(cnt == 1) {
name = $(this).text();
return false;
}
cnt++;
});
$.ajax({
url:"select_login_update.php",
method:"POST",
data: {name: name},
dataType: 'JSON',
success:function(data)
{
if(data !== '') {
var email = data[0].email;
var pword = data[0].password
var frm = document.createElement('form');
frm.setAttribute('action', 'http://login.php');
frm.setAttribute('method', 'post');
frm.setAttribute('target', 'view');
var frmEmail = document.createElement('input');
frmEmail.setAttribute('type', 'hidden');
frmEmail.setAttribute('name', 'email');
frmEmail.setAttribute('value', email);
var frmPass = document.createElement('input');
frmPass.setAttribute('type', 'hidden');
frmPass.setAttribute('name', 'password');
frmPass.setAttribute('value', pword);
frm.appendChild(frmEmail)
frm.appendChild(frmPass)
document.body.appendChild(frm);
window.open('', 'view');
frm.submit();
} else {
console.log('empty data');
}
},
error:function(xhr, status, err)
{
console.log('select_login_update.php error ' + err);
}
});
});
function fetch_data()
{
$.ajax({
url:"select_update_all.php",
method:"POST",
dataType:"json",
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{var purpose = data[count].purpose;
if(purpose == "BFH") purpose = "Holders";
else if(purpose == "CAS") purpose = "Ranking";
else if(purpose == "PWA") purpose = "Money Rankers";
else if(purpose == "Crew") purpose = "PW Accounts";
else if(purpose == "Crew2") purpose = "The Colombo Family";
else if(purpose == "Crew3") purpose = "Hassinions";
else if(purpose == "aa") purpose = "Admin Account";
else if(purpose == "slist") purpose = "Stocklist";
else if(purpose == "Eragon") purpose = "Eragon";
else if(purpose == "NP") purpose = "Non Paying";
else if(purpose == "DA") purpose = "Deadly Alliance";
html += '<tr >';
html += '<td class=\"footer\"><input type="checkbox" id="'+data[count].id+'" data-name="'+data[count].name+'" data-bullets="'+data[count].bullets+'" data-rang="'+data[count].rang+'" data-category="'+data[count].category+'" data-door="'+data[count].door+'" data-ranker="'+data[count].ranker+'" data-purpose="'+data[count].purpose+'" data-notes="'+data[count].notes+'" class="check_box" /></td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].name+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].bullets+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].rang+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].ranker+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].cat_name+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+purpose+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].notes+'</td>';
html += '<td style="color:'+data[count]['cat_color']+' " class=\"footer\">'+data[count].door+'</td>';
html += '<td class=\"footer\"><button type="button" class="loginBtn" >Login</button></td></tr>';
}
$('tbody').html(html);
}
});
}
fetch_data();
$(document).on('change', '.check_box', function(){
var html = '';
if(this.checked)
{
html = '<td class=\"footer\"><input type="checkbox" id="'+$(this).attr('id')+'" data-name="'+$(this).data('name')+'" data-bullets="'+$(this).data('bullets')+'" data-rang="'+$(this).data('rang')+'" data-category="'+$(this).data('category')+'" data-door="'+$(this).data('door')+'" data-ranker="'+$(this).data('ranker')+'" data-purpose="'+$(this).data('purpose')+'" data-notes="'+$(this).data('notes')+'" class="check_box" checked /></td>';
html += '<td class=\"footer\"><input type="text" name="name[]" class="editbox" value="'+$(this).data("name")+'" /></td>';
html += '<td class=\"footer\"><input type="number" onClick="this.select()" style="width:58px !important;" name="bullets[]" class="editbox" value="'+$(this).data("bullets")+'" /></td>';
html += '<td class=\"footer\"><select name="rang[]" id="rang_'+$(this).attr('id')+'" class="editbox"><option value="Bacteria">Bacteria</option><option value="Low Life">Low Life</option><option value="Apprentice">Apprentice</option><option value="Hitman">Hitman</option><option value="Assassin">Assassin</option><option value="Local Boss">Local Boss</option><option value="Boss">Boss</option><option value="Godfather">Godfather</option></select></td>';
html += '<td class=\"footer\"><input type="text" name="ranker[]" class="editbox" value="'+$(this).data("ranker")+'" /></td>';
html += '<td class=\"footer\"><select name="category[]" id="category_'+$(this).attr('id')+'" class="editbox"><option value="4">Moet gerankt worden</option><option value="6">Wordt gerankt</option><option value="5">Current BF Holder</option><option value="7">Main Account</option><option value="8">Money Private</option><option value="11">CB/Suc</option><option value="13">Casino Holder</option><option value="15">Wordt Gestockt</option><option value="10">Dont use, ask first!</option><option value="14">Stockgeld</option><option value="0"></option></select></td>';
html += '<td class=\"footer\"><select name="purpose[]" id="purpose_'+$(this).attr('id')+'" class="editbox"><option value="">-- No Type --</option><option value="Killer">Killers</option><option value="BFH">Holders</option><option value="CAS">Ranking</option><option value="PWA">Money Rankers</option><option value="Crew">PW Accounts</option><option value="Crew2">The Colombo Family</option><option value="Deadly Alliance">Deadly Alliance</option><option value="Crew3">Hassinions</option><option value="aa">Admin Account</option><option value="NP">Non Paying</option><option value="Eragon">Eragon</option><option value="slist">Stocklist</option></select></td>';
html += '<td class=\"footer\"><input type="text" name="notes[]" class="editbox" value="'+$(this).data("notes")+'" /></td>';
html += '<td class=\"footer\"><input disabled="" style="width:50px !important;" name="door[]" class="editbox" value="'+$(this).data("door")+'" /><input type="hidden" name="hidden_id[]" value="'+$(this).attr('id')+'" /></td>';
html += '<td class=\"footer\"><input type="submit" name="multipleupdatedata2allacc" id="multipleupdatedata2allacc" class="submit" value="Update" /></td>';
}
else
{
html = '<td class=\"footer\"><input type="checkbox" id="'+$(this).attr('id')+'" data-name="'+$(this).data('name')+'" data-bullets="'+$(this).data('bullets')+'" data-rang="'+$(this).data('rang')+'" data-category="'+$(this).data('category')+'" data-door="'+$(this).data('door')+'" data-ranker="'+$(this).data('ranker')+'" data-purpose="'+$(this).data('purpose')+'" data-notes="'+$(this).data('notes')+'" class="check_box" /></td>';
html += '<td class=\"footer\">'+$(this).data('name')+'</td>';
html += '<td class=\"footer\">'+$(this).data('bullets')+'</td>';
html += '<td class=\"footer\">'+$(this).data('rang')+'</td>';
html += '<td class=\"footer\">'+$(this).data('ranker')+'</td>';
html += '<td class=\"footer\">'+$(this).data('category')+'</td>';
html += '<td class=\"footer\">'+$(this).data('purpose')+'</td>';
html += '<td class=\"footer\">'+$(this).data('notes')+'</td>';
html += '<td class=\"footer\">'+$(this).data('door')+'</td>';
html += '<td class=\"footer\"><button type="button" class="loginBtn">Login</button></td></tr>';
}
$(this).closest('tr').html(html);
$('#rang_'+$(this).attr('id')+'').val($(this).data('rang'));
$('#category_'+$(this).attr('id')+'').val($(this).data('category'));
$('#purpose_'+$(this).attr('id')+'').val($(this).data('purpose'));
});
$('#update_form').on('submit', function(event){
event.preventDefault();
if($('.check_box:checked').length > 0)
{
$.ajax({
url:"update_multiple.php",
method:"POST",
data:$(this).serialize(),
success:function()
{
alert('Data Updated');
fetch_data();
}
})
}
});
});
</script>
Well, it is somewhat easy, and believe it or not, even easier for what you need. So, based on what you have, you really only need a string of <option> tags for the <select>, which only needs to be fetched once for reference. The tougher part is usually making the new handling work with code that already exists, if possible, without having to refactor.
Try the things below, I've added another ajax to pre-fetch the category options after the document is ready: (see the two // New comment markers)
$(document).ready(function() {
var categoryOptions = ''; // New var
$.ajax({ // New ajax
url: 'get_categories.php',
method: 'GET',
dataType: 'text',
success:function(data)
{
categoryOptions = data;
},
error:function(xhr, status, err)
{
console.log('get_categories.php error ' + err);
}
});
$(document).on('click', '.loginBtn', function(e) {
Content of get_categories.php: (replace with your DB handling)
<?php
$db = new mysqli('localhost', 'root', '', 'test');
// Get the category id/name pairs
$result = $db->query("SELECT cat_ID, cat_name FROM categories");
$options = '';
// Build the options
while ($row = $result->fetch_array()) {
$options .= '<option value="' . $row['cat_ID'] . '">' . $row['cat_name'] . '</option>';
}
// The option 0 was last, keeping the same way.
$options .= '<option value="0"></option>';
echo $options;
Then change the categories html from:
html += '<td class=\"footer\"><select name="category[]" id="category_'+$(this).attr('id')+'" class="editbox"><option value="4">Moet gerankt worden</option><option value="6">Wordt gerankt</option><option value="5">Current BF Holder</option><option value="7">Main Account</option><option value="8">Money Private</option><option value="11">CB/Suc</option><option value="13">Casino Holder</option><option value="15">Wordt Gestockt</option><option value="10">Dont use, ask first!</option><option value="14">Stockgeld</option><option value="0"></option></select></td>';
...to:
html += '<td class=\"footer\"><select name="category[]" id="category_'+$(this).attr('id')+'" class="editbox">' + categoryOptions + '</select></td>';
I believe that should achieve the desired goal.
I'm working to update a module for Prestashop. In this I use the hookDisplayAdminOrder in this way:
public function hookDisplayAdminOrder($params)
{
$orderId = Tools::getValue('id_order'); // mi prendo l'id dell'ordine per le query sui docId
$order = new Order($orderId);
$order_status = $order->getCurrentOrderState();
if(is_object($order_status)){
if($order_status->name[1] == 'Annullato')
$order_status_name = '';
else
$order_status_name = $order_status->name[1];
}else{
$order_status_name = $order_status;
}
$query = 'SELECT docId, docIdOrder, apiResponseOrder, apiResponseInvoice FROM '._DB_PREFIX_.'orders WHERE id_order=\'' . $orderId . '\';';
$docId = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['docId'];
$docIdOrder = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['docIdOrder'];
$apiResponseOrder = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['apiResponseOrder'];
$apiResponseInvoice = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['apiResponseInvoice'];
$obj_apiResponseOrder = json_decode($apiResponseOrder);
$obj_apiResponseInvoice = json_decode($apiResponseInvoice);
$orderResponseDescription = is_object($obj_apiResponseOrder)? $obj_apiResponseOrder->description : $obj_apiResponseOrder['description'];
$invoiceResponseDescription = is_object($obj_apiResponseInvoice)? $obj_apiResponseInvoice->description : $obj_apiResponseInvoice['description'];
$config_CreaOrdine = Configuration::get('PS_CREAZIONE_ORDINE');
$config_CreaFattura = Configuration::get('PS_CREAZIONE_FATTURA');
if(!$config_CreaOrdine){
$message_order = 'creazione documento disabilitata';
} else if(empty($order_status_name)){
$message_order = 'ordine annullato in Prestashop';
} else {
if(!empty($docIdOrder))
$message_order = 'documento salvato';
else
$message_order = 'documento NON salvato';
}
if(!$config_CreaFattura){
$message_invoice = 'creazione documento disabilitata';
} else if(empty($order_status_name)){
$message_invoice = 'ordine annullato in Prestashop';
} else {
if(!empty($docId))
$message_invoice = 'documento salvato';
else
$message_invoice = 'documento NON salvato';
}
// uso order_documents per incrementare il contatore
$order_documents = 0;
if(strpos($message_order, 'documento salvato') !== false)
$order_documents++;
if(strpos($message_invoice, 'documento salvato') !== false)
$order_documents++;
$this->context->smarty->assign('id_order', json_encode($order));
$this->context->smarty->assign('order_status_name', $order_status_name); //se l'ordine è annullato nascondo i pulsanti
$this->context->smarty->assign('config_CreaOrdine', $config_CreaOrdine);
$this->context->smarty->assign('config_CreaFattura', $config_CreaFattura);
$this->context->smarty->assign('order_documents', $order_documents); // contatore documenti salvati
$this->context->smarty->assign('invoice_docId', $docId); //docId per tasto fattura
$this->context->smarty->assign('invoice', $message_invoice);
$this->context->smarty->assign('order_docId', $docIdOrder); //docId per tasto ordine
$this->context->smarty->assign('order', $message_order);
return $this->display(__FILE__, 'views/templates/hook/admin_order.tpl');
}
Here below my template:
<div class="panel" id="myModule">
<div class="panel-heading">
<i class="icon-money"></i>{l s='myModule' mod='myModule'}
<span class="badge">{$order_documents}</span>
</div>
<table>
<tbody>
<thead>
<tr>
<td><strong>{l s='Stato ordine' mod='myModule'} </strong></td>
<td style="padding-left: 20px;"><strong>{l s='Stato fattura' mod='myModule'} </strong></td>
</tr>
</thead>
<tr>
<td id="f24_order">{$order}</td>
<td id="f24_invoice" style="padding-left: 20px;">{$invoice}</td>
</tr>
<tr>
<td>
{if $order_status_name neq '' && $order_docId == '' && $config_CreaOrdine eq 1}
<button type="submit" name="submit_order" id="submit_order" class="btn btn-primary">Salva Ordine</button>
{/if}
</td>
<td style="padding-left: 20px;">
{if $order_status_name neq '' && $invoice_docId == '' && $config_CreaFattura neq 0 }
<button type="submit" name="submit_invoice" id="submit_invoice" class="btn btn-primary">Salva Fattura</button>
{/if}
</td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
var orderbtn = document.getElementById("submit_order");
orderbtn.addEventListener('click', function (e) {
$.ajax({
type: 'POST',
data: {
ajax: true,
action: 'SmartyOrder' + {$id_order},
},
url: 'myModule',
success: function (response) {
console.log(response);
return response;
}
});
});
Eventually I created in myModule SmartyOrder function, but when I click in my button it does nothing.
Here below the method:
function ajaxProcessSmartyOrder($params){
$this->ajax = true;
$config_CreaOrdine = Configuration::get('PS_CREAZIONE_ORDINE');
$orderId = Tools::getValue('id_order'); // mi prendo l'id dell'ordine per le query sui docId
$check_order = new Order($orderId);
$order_status = $check_order->getCurrentOrderState(); // controllo lo stato dell'ordine prima di tutto
if(is_object($order_status)){
if($order_status->name[1] == 'Annullato')
$order_status_name = '';
else
$order_status_name = $order_status->name[1];
} else {
$order_status_name = $order_status;
}
$query = 'SELECT docId, docIdOrder, apiResponseOrder, apiResponseInvoice FROM '._DB_PREFIX_.'orders WHERE id_order=\'' . $orderId . '\';';
$docIdOrder = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['docIdOrder'];
$apiResponseOrder = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['apiResponseOrder'];
//$apiResponseInvoice = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query)['apiResponseInvoice'];
$obj_apiResponseOrder = json_decode($apiResponseOrder);
//$obj_apiResponseInvoice = json_decode($apiResponseInvoice);
$this->afterHook($check_order, false);
if(!empty($docIdOrder)){
$query = 'UPDATE ' . _DB_PREFIX_ . 'orders SET docIdOrder=\'' . $docIdOrder . '\' WHERE id_order=\'' . $orderId . '\';';
Db::getInstance()->Execute($query);
//$this->downloadDocument($docIdOrder, $orderId, true);
} else if (!empty($obj_apiResponseOrder->description)) { // con questa condizione popolo il docId anche nel caso in cui il documento è già esistente in F24
$query = 'UPDATE ' . _DB_PREFIX_ . 'orders SET docIdOrder=\'' . $obj_apiResponseOrder->description . '\' WHERE id_order=\'' . $orderId . '\';';
Db::getInstance()->Execute($query);
}
}
I want to call SmartyOrder function from template passing order data but at the moment I'm not able to do it. Any suggestion? Thanks
You can find more information about your issue in a module of Prestashop called 'CarrierComparion". You can compare your current code with the code of the module.
Post form using (Ajax): https://github.com/PrestaShop/ps_carriercomparison/blob/master/js/carriercompare.js#L84
Receiving post (PHP): https://github.com/PrestaShop/ps_carriercomparison/blob/master/controllers/front/carrier_comparison.php#L45
I want get all my input and select elements off my page HTML. I've tried getElementsByTagName('input,select') but it does not work.
My code HTML and JavaScript:
function myFunction() {
var data = [];
var data1 = [];
var data2 = [];
for (var i = 0; i < 10; ++i) {
var x = document.getElementsByTagName("INPUT,SELECT")[i].getAttribute("name");
var y = document.getElementsByTagName("INPUT,SELECT")[i].getAttribute("type");
var z = document.getElementsByTagName("INPUT,SELECT")[i].getAttribute("maxlength");
data.push(x);
data1.push(y);
data2.push(z);
location.href ="ttt.php?name=" + data + "&active=" + data1 + "&data2=" + data2
}
}
<select name="CIV"><option selected="selected" value=""></option><option selected="selected" value="">Mr</option><option selected="selected" value="">Mme</option></select>
<input type="text" size="20" name="first_name" id="first_name" maxlength="50" class="cust_form" value="">
<input type="text" size="20" name="last_name" id="last_name" maxlength="50" class="cust_form" value="">
<input type="text" size="20" name="address3" id="address3" maxlength="50" class="cust_form" value="">
You should access the elements separately; INPUT and SELECT. BTW, Select element doesn't have type and maxlength attributes.
function myFunction() {
var nameData = [];
var typeData = [];
var maxLengthData = [];
var input = document.getElementsByTagName("INPUT")
var select = document.getElementsByTagName("SELECT")
// Targeting the first 9 of elements of input collections and select collections
// Assuming you understand what you are doing here
for (var i = 0; i < 10; ++i) {
nameData.push( input[i].getAttribute( 'name' ) );
nameData.push( select[i].getAttribute( 'name' ) );
typeData.push( input[i].getAttribute( 'type' ) ); // Select element doesn't have type attribute
maxLengthData.push( inputt[i].getAttribute( 'maxlength' ) ); // Select elemnt doesn't have maxlength attribute
// Assuming you understand what you are doing to build your url here
location.href ="ttt.php?name=" + nameData + "&active=" + typeData + "&data2=" + maxLengthData
}
}
Please, read more on HTML elements and their attributes. Also, read more on pure JavaScript.
Note: this has not been tested yet. Try it and let me know if it does what you you want it to do.
Am using Jquery FormData for the first time, but seems am missing something. In the JS - postAjax method, when new FormData() is called, it just skips the remaining lines and goes to the end of the function without any errors. What am I doing wrong here?
template.js //script files in this order
<script src="js/jquery-2.1.0.js"></script>
<script src="js/jquery.form.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrapValidator.js"></script>
<script src="js/hemoncCBCFunctions.js"></script>
<script src="js/validations.js"></script>
JSP
<form name ="newSectionSubmitForm" id="newSectionSubmitForm" class="form-horizontal" role="form" method="post" ENCTYPE="multipart/form-data">
<table>
<tr>
<td>
<input type="file" id='imageFile0' name='imageFile0' class="form-control" />
</td>
</tr>
</table>
<form>
JS
function submitNewSection(targetUrl, form) {
postAjaxData(null, 'content', targetUrl, form, null, null);
}
function postAjaxData(initiatingElement, targetElement, targetUrl, form,
additionalParamMap, successCallback) {
var $targetElement = $('#' + targetElement);
var serializedFormData;
serializedFormData = $('#' + form).serialize();
for ( var j in additionalParamMap) {
serializedFormData += "&" + j + "=" + additionalParamMap[j];
}
alert('serialized form data ' + serializedFormData);
var formData = new FormData(serializedFormData);//**exits the function no errors**
formData.append("file", $('#imageFile0').files[0]);
alert('serialized form data ' + formData);
$.ajax({
type : "POST",
cache : false,
data : formData,
url : targetUrl,
success : function(data) {
processRedirect(data);
$targetElement.html(data);
$targetElement.show();
if (successCallback != null) {
successCallback(data);
}
},
error : function(xhr, httpRequest, textStatus, errorThrown) {
var errorId = xhr.getResponseHeader("errorId");
var errorMsg = xhr.getResponseHeader("errorMessage");
if (errorId != null && errorId != undefined) {
$("#page_error").html(
"An unexpected error has occurred. Error Id: "
+ errorId);
} else {
$("#page_error").html("An unexpected error has occurred.");
}
},
});
Controller File (however the code does not reach here)
#RequestMapping(value = "/submitNewSection.html")
public String submitNewSection( MultipartHttpServletRequest req, HttpServletRequest request, Model model) {
Iterator<String> itr = req.getFileNames();
MultipartFile mpf = req.getFile(itr.next());
System.out.println("file name " + mpf.getOriginalFilename() +" uploaded!");
}
Thanks so much.
I am finalising a college project and I am stuck.
I have created an API in netbeans and it is working fine.
Returing e.g.
<?xml version="1.0" encoding="UTF-8"?>
<accountholder>
<accountnumber>45672</accountnumber>
<address>234 THE BANK, DUBLIN 1</address>
<balance>763.32</balance>
<email>JOHANN#SMITH.COM</email>
<firstname>JOHANN</firstname>
<id>1</id>
<lastname>SMITH</lastname>
<pinnumber>1234</pinnumber>
</accountholder>
Now I am trying to create a javascript to return data when searching by Id.
<script language="javascript" type="text/javascript">
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("MsXML2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null)
alert("Error creating request object!");
}
function getMessage()
{
createRequest();
var accountholderid = document.getElementById("Id").value;
id=eval(accountholderid);
var url = "http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/"+id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState==4 && request.status==200)
{
var xmlDocument=request.responseXML;
var firstname = xmlDocument.getElementsByTagName("firstname");
var lastname = xmlDocument.getElementsByTagName("lastname");
var accountnumber = xmlDocument.getElementsByTagName("accountnumber");
for(var i=0; i<firstname.length; i++) {
var firstname = firstname[i].childNodes[0].nodeValue;
var lastname = lastname[i].childNodes[0].nodeValue;
var accountnumber= accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value=firstname;
document.getElementById('firstname').value=lastname;
document.getElementById('accountnumber').value=accountnumber;
}
}
}
</script>
In the body I have an input textfield with a button with an on click:
<td>Enter Account holder ID : </td>
<td><input type="text" id="playerid" size="10"/>
<input type="button" value="Get Details" onclick="getMessage()"/>
</tr>
<tr>
<td>Account holder Last Name : </td>
<td> <input type="text" id="lastname" size="10"/> </td>
</tr>
<tr>
<td>Account holder First Name : </td>
<td> <input type="text" id="firstname" size="10"/> </td>
</tr>
<tr>
<td>Account number : </td>
<td> <input type="text" id="accountnumber" size="10"/> </td>
</tr>
What am I missing as it is not returning anything :(
I believe your id value for the 'accountholderid' was looking for 'Id' instead of 'playerid'.
May I ask why you are calling 'eval' on the value? Do you need parseInt?
(function () {
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject('MsXML2.XMLHTTP');
} catch (othermicrosoft) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (failed) {
request = null;
}
}
}
if (request === null) {
alert('Error creating request object!');
}
}
function getMessage() {
createRequest();
var accountholderid = document.getElementById('playerid').value,
id = eval(accountholderid),
url = 'http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/' + id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState === 4 && request.status === 200) {
var xmlDocument = request.responseXML,
firstname = xmlDocument.getElementsByTagName('firstname'),
lastname = xmlDocument.getElementsByTagName('lastname'),
accountnumber = xmlDocument.getElementsByTagName('accountnumber');
for(var i = 0, max = firstname.length; i < max; i += 1) {
var firstname = firstname[i].childNodes[0].nodeValue,
lastname = lastname[i].childNodes[0].nodeValue,
accountnumber = accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value = firstname;
document.getElementById('firstname').value = lastname;
document.getElementById('accountnumber').value = accountnumber;
}
}
}
}());
Also, I did a quick refactoring of your code to aid in my assessing the issue, adhere to more community conventions as well as avoid common JS pitfalls. (ex. closure, missing var declarations, ===, curlys everywhere, single variable pattern, and some others).