Hidden input text submit with jquery - javascript

I have a javascript var that returns the value of a input text ID "ven_prod", with the value of "ven_prod" I need to make a search in my database without submiting the page.
I can't use a javascript var in the java code, so i've setted the value in a hidden input text ID "prod_hidden", but I need to submit it to get the value with the java code and make the search...How do I do it ?
<input id="ven_prod" type="text" placeHolder="Código de Barras" autofocus>
<input id="prod_hidden" type="text" value="">
<script>
$('#ven_prod').keypress(function (e)
{
if(e.keyCode==13)
{
var table = document.getElementById('tbprodutos');
var tblBody = table.tBodies[0];
var newRow = tblBody.insertRow(-1);
var prod = document.getElementById('ven_prod').value;
var qtd = document.getElementById('ven_qtd');
var barra = prod.substring(0, 12);
var num = prod.substring(14, 16);
document.getElementById('prod_hidden').value = barra;
var ref = <%=pd.getProdutosBarra(request.getParameter("prod_hidden")).getPro_referencia()%>;
OR
var ref = <%=pd.getProdutosBarra(JS VAR 'barras HERE).getPro_referencia()%>;
if(prod.length==16) {
var newCell0 = newRow.insertCell(0);
newCell0.innerHTML = '<td>'+ref+'</td>';
var newCell1 = newRow.insertCell(1);
newCell1.innerHTML = '<td>'+num+'</td>';
var newCell2 = newRow.insertCell(2);
newCell2.innerHTML = '<td>'+qtd.value+'</td>';
var newCell3 = newRow.insertCell(3);
newCell3.innerHTML = '<td>R$ '+valor+'</td>';
var newCell4 = newRow.insertCell(4);
newCell4.innerHTML = '<td>'+barra+'</td>';
document.getElementById('ref').value = '6755';
document.getElementById('imgsrc').src = './?acao=Img&pro_id=1';
document.getElementById('valortotal').value = 'Testando novo valor';
document.getElementById('ven_prod').value = '';
document.getElementById('ven_qtd').value = '1';
} else {
document.getElementById('ven_prod').value = '';
document.getElementById('ven_qtd').value = '1';
alert("Código de barras inválido!");
}
return false;
}
});
</script>

you can make ajax call using jQuery as follows. will submit your form data as well along with hidden elements.
var form = jQuery("#YourFormID");
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(), // serializes the form's elements.
success: function(data) {
console.log(data);
}
});

value of a input text named "pro_barras"
Are you sure? Look at this:
<input type="hidden" id="pro_barras">
its not the name of the input, its the ID. You can try using this:
<input type="hidden" name="pro_barras">
And now, you can use $.ajax to send the request to a new page, where you will request the data from the database. And then you'll write the response, and take it back on the first page.
What it will do depends on how you use it. I will try to ask you to simply use serialize() method by jQuery API, this will let you to create a simple URL param with the data from the form, use it as:
$.ajax({
var data = $('#formid').serialize(); // serialize the form..
url: "link/to/file.cshtml",
data: data,
success: function (datares) {
$('#resultid').html(datares); // write the result in the element
}
})
If you want to get only the value from that field you can use
var data = $('input[name=pro_barras]').val();
without submiting the page.
Your page will have to be submitted when you click on input type="submit" button. To prevent that you can use
$('#idofsubmitbutton').click(function () {
return false; // stop execution and stay on page..
}
Then the ajax will continue, other method is to remove the input type="submit" and use <button></button> which won't cause any submission.
get the value with the java code
This isn't java :) Its JavaScript, they are totally different. :)

a) You can use like that:
$("#pro_barras").bind("change paste keyup", function() {
//$('.someClass').submit();
$('#it_is_form_id').submit(); // it call form's submit function
});
The piece of code detected when input text change. To more info see also here If you want to customize form submit function
$('#it_is_form_id').bind("submit", function(){
//alert("submit");
// make here simple ajax query
return false; //<-- it is used so that default submit function doesn't work after above code.
});
Don't forget, all code will be inside
<script>
$(function() {
// your code must be here
});
</script>
b) If you don't want to use form, you can do like that:
<script>
$(function() {
$("#pro_barras").bind("change paste keyup", function() {
var text = $("#pro_barras").val();
$.ajax({
type: "POST",
url: "yourUrl",
data: text,
success: function(res){
console.log(res);
},
error: function(err){
console.log(err);
}
});
});
});
</script>
Making simple ajax query:
Using Jquery post method
https://stackoverflow.com/a/8567149/1746258
Pass entire form as data in jQuery Ajax function

You could also add a custom attribute to your input element (in Jquery):
<input type='text' id='pro_barras' customattr='myCustomInfo'/>
<script>
var customValue = $('#pro_barras').attr('mycustomvar');
alert(customValue);
</script>
Fiddle

Related

Post to PHP backend from javascript code

I have tried other answers but none have worked. The javascript code is supposed to submit a list of product id's to a php page. When products are selected, the submit button triggers the submit function.
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
console.log(ids);
//send the ids to api
bundle = [];
$('.bundle-list').empty();
$('.total').html('No item in bundle');
$('.submit').addClass('hide');
}
I have tried inserting this line in the function
document.getElementByID("test").value = bundle;
and a hidden tag within the form but can't get the var to submit to PHP
<input type="hidden" id="test" name="test" visibility="hidden"></input>
Where should the position of the hidden element be relative to the JS code? and any other methods of retrieving the ID's?
Either by $.post or $.get variable you can send data to PHP file, but i think you want to save pids in hidden field, but you are not update its value on submit. like
$('#test').html('YOUR DATA')
Try this..
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
$.ajax({
url: 'YOUR_URL HERE',
type: 'POST',
data: { qry: ids },
success: function(data) {
///WHEN SUCCESS
}
},
error: function(e) {
}
});
}

VBA Excel run javascript form event

I’ve already tried to get the element by id, however, the html does not include it. As shown below, this is the script for the drop down that I am trying to change automatically. It will change the name with
appIE.Document.getElementById("supervisor").Value = "Sup_name"
However, it doesn’t fire the event that generates a list of people.
The top of the form also includes <form id='filterform' action="javascript:void(0);">
The JavaScript containing the function I need to call is below.
<script type="text/javascript">
$(function() {
$('#supervisor').change(function() {
document.getElementById('results').innerHTML = '<img src="/img/busy.gif" />';
var str = $('#filterform').serializeArray();
$.ajax({
url: 'ajax.php?p=agentrosters&mode=1&field=supervisor',
type: 'POST',
data: str,
success: function(j) {
//alert(j);
document.getElementById('results').innerHTML = j;
document.getElementById('lastsearch').value = 'supervisor';
resetscript('supervisor');
},
failure: function() {
document.getElementById('results').innerHTML = 'There has been an error, please try again';
resetscript('null');
}
})
})
})
</script>
Any Ideas on how I can get this to work?
If the element is part of a form you may to submit the form, alternatively you can use the onchange event on the element itself. So you may want to change appIE.Document.getElementById("supervisor").Value = "Sup_name" to
With appIE.document.getElementById("supervisor")
.Value = "Sup_name"
.onchange
End with
And if it is part of a form change the ".onchange" to
".parentElement.Submit"
This worked for me.

Jquery/Ajax selectbox onChange trigger

Ok, what i'm trying to do is to create a list of select boxes which update their value each depending on the above:
the first one is like that:
<script>
var $schoolRegion = $('#stage_attendedSchoolRegion');
$schoolRegion.change(function() {
var $form = $(this).closest('form');
var data = {};
data[$schoolRegion.attr('name')] = $schoolRegion.val();
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
$('#stage_attendedSchoolDistrict').replaceWith(
$(html).find('#stage_attendedSchoolDistrict')
);
}
});
});
</script>
when it's value changes an ajax request is dispatched, and the choices of the "#stage_attendedSchoolDistrict" select are updated with the POST html value.
Since here's all good, now i need to do the same with the "#stage_attendedSchoolDistrict" select so:
<script>
var $schoolDistrict = $('#stage_attendedSchoolDistrict');
$schoolDistrict.on.change(function() {
var $form = $(this).closest('form');
var data = {};
data[$schoolDistrict.attr('name')] = $schoolDistrict.val();
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
$('#stage_attendedSchoolCity').replaceWith(
$(html).find('#stage_attendedSchoolCity')
);
}
});
});
</script>
The problem is that the event doesn't trigger at all. I'm thinking it is related to the fact that the former has values in the HTML of the page while the latter doesnt. How can i solve?
Any suggestion is appreciated, thanks for the help.
You're calling on.change in the second example instead of just .change as in the first example.

Checkboxes in Form to javascript to php

I have a form with dynamic checkboxes based on MySQL data. On submit the DIV refreshes without blinking with JavaScript. I'm trying to send the form data to PHP for updating the MySQL but I constantly run into one error or another due to my lack of JavaScript knowledge. My current attempt (see below) gives the "TypeError: document.multipix_form.pix is undefined" error in FireBug.
function multipicupdate(php_file, purpose, where) {
var request = getXMLHTTP(); // call the function for the XMLHttpRequest instance
var a = document.getElementById("optone").value ;
var b = document.getElementById("table").value ;
var boxes = document.multipix_form.pix.length
txt = ""
for (i = 0; i < boxes; i++) {
if (document.multipix_form.pix[i].checked) {
txt = txt + document.multipix_form.pix[i].value + " "
}
}
var the_data = 'purpose='+purpose+'&var1='+a+'&var2='+b+'&var3='+txt;
request.open("POST", php_file, true); // set the request
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(where).innerHTML = request.responseText;
}
}
}
The form name is multipix_form. The three form inputs are optone (select), table (select), and pix[] (checkbox). The pix[] is dynamic as I said before. It is the passing of the checkbox data from JavaScript to php that has me stumped.
My form submit is :
<input type="button" onClick="multipicupdate('php/ajaxprocess.php', 'multipix', 'message_profile'); return false;" value="Save changes to this photo">
The ajaxprocess.php will take the form data and update MySQL.
As you have tagged jQuery, here's a jQuery solution. You can simplify this code quite a lot. Firstly, you can use serialize() to create a querystring from the values of the inputs in that form. Then you can use $.ajax to send that information to the page you need. Try this:
<input type="button" value="Save changes to this photo" id="multipicupdate">
$('#multipicupdate').click(function() {
$.ajax({
url: '',
type: 'POST',
data: $('#myForm').serialize(), // change the selector as needed
success: function(data) {
$('#message_profile').html(data);
}
});
});
You need a semicolon after
var boxes = document.multipix_form.pix.length
and
txt = ""

AJAX Multiple Forms With Same Submit/Click Function

I've got multiple forms (that are similar) that are passed using Ajax to appended a PHP page using this code below. However, when I click the first or second form, it only sends the data from the first form. Can I use just the one function on all forms, or is there a better way to go?
$('.col_1').click(function(){ // $('#col_1').on("click", function(){
var parent_id = $('input[name=parent_id]').val();
var child_id = $('input[name=child_id]').val(); ////
$.ajax({
type:"POST",
url: "array-2.php",
data:{parent_id: parent_id, child_id: child_id},
success: function(){
//do stuff after the AJAX calls successfully completes
}
}).done(function(data) {
$('body').append(data);
});
});
Here is the HTML I'm using.
<form name="col_1" id="columnA1" class="col_1"><div>Entrepreneur</div>
<input name="parent_id" type="hidden" id="parent_id" value="1234" />
<input name="child_id" type="hidden" id="child_id" value="abcd" />
</form>
<form name="col_1" id="columnA2" class="col_1"><div>Musician</div>
<input name="parent_id" type="hidden" id="parent_id" value="5678" />
<input name="child_id" type="hidden" id="child_id" value="efgh" />
</form>
I've seen similar threads using the submit functions but none with the click event. Thanks
You need to make your selector specific, what you have is too generic that it will select all the input[name=parent_id] and val() on the collection will return the value of the first item in the collection.
So change it to:
var $this = $(this),
parent_id = $this.find('input[name=parent_id]').val(),
child_id = $this.find('input[name=child_id]').val();
Also note that you may want to use submit event instead of click event. What you have is an event registered for the click event on the form which will keep invoking the event when you click anywhere inside the form(unless you really want to do so).
You can also use serializeObject. It will take care of all form fields:-
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and you can do:
$.ajax({
type:"POST",
url: "array-2.php",
data: $(this).serializeObject(), //This will give you the map
success: function(){
...
}
...
Demo
you should really be using the submit method and not click, your current code will fire every time the whole form is clicked on, it should look something like this:
$('.col_1').on('submit', function(e){ // fire on submit
var form = $(this);
var parent_id = form.find('input[name=parent_id]').val();
var child_id = form.find('input[name=child_id]').val();
$.ajax({
type:"POST",
url: "array-2.php",
data:{parent_id: parent_id, child_id: child_id}
}).done(function(data) {
$('body').append(data);
});
e.preventDefault();
});
Don't use the click on a form. It does not make any sense.
Just do this
<div class="col_1" data-parent_id="1234" data-child_id="abcd">Entrepeneur</div>
<div class="col_1" data-parent_id="5678" data-child_id="efgh">Musician</div>
using
$(function() {
$('.col_1').click(function(){
var parent_id = $(this).data("parent_id");
var child_id = $(this).data("child_id]");
$.post("array-2.php",{parent_id: parent_id, child_id: child_id},
function(data){
//do stuff after the AJAX calls successfully completes
$('body').append(data);
});
});
});

Categories

Resources