Post multiple data using Jquery/Ajax - javascript

I have this script below that sends only 1 value to the requested URL, but now I need to adjust it to accept 2, I couldn't find a way to do that.
Each checkbox is accompanied by an input hidden named #note, I need to pass this #note value (that's my order ID) together.
$('#importaNF').click(function(){
var checkbox = $('.import_checkbox:checked');
if(checkbox.length > 0)
{
var checkbox_value = [];
$(checkbox).each(function(){
checkbox_value.push($(this).val());
});
$.ajax({
url:"<?php echo base_url(); ?>adm/pedidos/importaNF",
method:"POST",
data:{checkbox_value:checkbox_value},
success:function()
{
$('.removeRow').fadeOut(1500);
}
})
}
else
{
alert('Select atleast one records');
}
}
My HTML
<div class="btn-group">
<input type="checkbox" class="import_checkbox" name="import_checkbox" value="<?= $registro->NUMERO ?>">
<input type="input" id="note" class="import_input" name="import_input" value="<?= $registro->FATURA ?>" style="visibility:hidden">
</div>

I may be misinterpretting, but you can just extract it like you did the checkbox value and add a second property to the data object:
data:{checkbox_value:checkbox_value, note_value: note_value},
Unless you mean you're trying to pass a second url parameter?

Related

Update input fields one at a time without page refresh

I have a mixture of input fields, textareas and combo boxes which I would like to be able to update one at a time (without page refresh) but I am not quite sure how to approach this. When update is clicked it should update the MySQL Database respectively. I know how to update all of them at the same time but I am trying to avoid using this method. Every input, textarea, combo has a input type submit next to them to get me started.
This is part of the html file that I am referring too.
<form action="" class="customform" method="post" id="file-upload-form" enctype="multipart/form-data">
<h5>Set competition name</h5>
<input type="text" id="Gamename" name="Gamename" value="<?php echo $GameName; ?>" size="400" style="max-width: 410px"> <input name="Update1" type="submit" value="Update" style="width: auto;">
<h5>Set competition date & time</h5>
<input type="text" id="demo" name="timedate" value="<?php echo $sdate; ?>" size="200" style="max-width: 210px"> <input name="Update2" type="submit" value="Update" style="width: auto;">
What would be the best way to achieve this? Would I need to use Ajax, Javascript or Jquery? I am not asking for all the code to be written for me, just some guidance on how to approach it. thanks
Try:
HTML
<div id="output"></div> // This is where response (res/err) will be showed
JS
var form = document.getElementById("file-upload-form");
var output = document.getElementById("output");
form.onsubmit = () => {
fetch("your_page.php", {
method: "POST",
body: new FormData(form)
})
.then(res => res.text())
.then(res => {
output.innerHTML = res;
})
.catch((err) => output.innerHTML = err);
return false;
};
You don't need jQuery for such a simple task.
this was done by ajax full code is here with all guidance.
https://steemit.com/utopian-io/#sogata/how-to-update-data-mysql-from-php-without-reload-page-using-jquery-ajax
$.ajax({
url:'update.php',
method:'POST',
data:{
name:name,
ctgr:ctgr
},
success:function(response){
alert(response);
}
});

how to update the price if quantity changed in cart

I am making the Review Cart & Checkout form. IF user want to change the quantity I want that if quantity is changed the price of it will be changed automatically.
Please help to adjust the code in the same JS of plus minus or separate.
Image is below of Review Cart & Checkout:
JS for Plus & Minus:
<script type="text/javascript">
function subtractQty(){
if(document.getElementById("number").value - 1 < 0)
return;
else
document.getElementById("number").value--;
}
</script>
HTML/PHP for plus minus:
<div class="quantity">
<input style="font-size:21px;" type="button" value="-" onclick='javascript: subtractQty();' class="">
<input id="number" type="number" value="<?php echo $qtyT; ?>" class="qty" name="picpac">
<input style="font-size:21px;" type="button" value="+" onclick='javascript: document.getElementById("number").value++;' class="plus">
</div>
You can follow two different strategies:
Invoke the server with an Ajax call, pass the quantity as parameter, calculate the total amount and return it.
Do all the operations in the front-end with jQuery and finally, pass the calculated value to store it.
In this link I have coded a quick example for the second one with your provided HTML. I just added a div for the calculated value
<div id="product1_total_price">0</div>
An input hidden for the product base price
<input type="hidden" id="product1_base_price" value="10">
And this jQuery code that do the magic:
$(document).ready(function() {
$(".operator").on('click',function() {
$("#product1_total_price").text($("#product1_base_price").val()*$("#number").val());
});
});
Hope it helps.
EDITED:
I add a (and update the JSFiddle link) suppossed Ajax call with jQuery, to update the DB on every quantity change:
$.ajax({
type: "GET",
data: {
idProduct: yourProductId,
quantity: $("#number").val(),
totalPrice: calculatedValue
},
url: "your-script.php",
success: function(json_response) {
if(json_response.result != 'SUCCESS') {
// Whatever
} else {
alert("Updated in DB");
});
})

javascript validation to check input length

I want to check the length of input string and validate it.If its greater than length the show message beside the text box.I my case the length is 10
<div>
<input type="text" name="ref_code" id="ref_code" value="" onchange="checkCodeStatus()" size=18>
<div id="msg" style="margin-left: 15px;"></div>
</div>
<script type="text/javascript">
function checkCodeStatus(){
var ref_code = $("#ref_code").val();
$.ajax({
type:'post',
url:'<?php echo site_url('mypage/check_code/'); ?>',
data:{ref_code: ref_code},
success:function(msg){
if(msg.indexOf('value does exist') > -1)
$('#msg').html('<span style="color: green;">'+msg+"</span>");
else $('#msg').html('<sapn style="color:red;">Value does not exist</span>');
}
});
}
</script>
Use .length to check input string's length and if it is more than 10 just set the value of div with id msg. And then return so function does not run anymore.
if(ref_code.length >10) {
$("#msg").val("Some error message");
return;
}
There are two ways to do one by html you just allow max length for example
<input type="text" name="usrname" maxlength="10">
or also you can do this by using jquery
var ref_code = $("#ref_code").val();
var refLength = ref_code.length;
if(refLength >10) {
$("#msg").html("your message");
return;
}
Check the length of input using .length
var ref_code = $("#ref_code").val();
if (ref_code.length > 10) {
$('#msg').text('Your error text will go here');
return false;
}
Also you should make a separate .js file to keep js code. Embed in html is not a good practice.For <?php echo site_url; ?> line you can keep your site url inside js file.

Check if fields are edited or not? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have 7 textfields put inside a table. These textfields data i get from server when user presses submit. After filling textfield with fetched data, user submits that data to the server from a new button submit.
If the user submits the data as it is, I need to show an error message that 'at least one field must be edited'. If it edits at least one field and then submits I will update data on the server.
How can I check whether user has changed a field or not?
Problem is I will need to store data fetched for comparison, which I will have to do it in global variable in my JavaScript (which is not a good practice).
You can create an hidden input (like say #lastr2d2) named haschange like
<input type="hidden" name="haschange" id="haschange" value="0" />
and add an jquery or javascript function witch change the value of haschange from 0 to 1
when happens an event onChange on each textfields. for example you can create a function like bellow:
$(document).ready(function(){
//Check this link
$("#textfields1").change(function(){
$("#haschange").val(1);
});
});
Finally when you click the button of finally submit then you can check if haschange value is 0 or 1
--- Edit ---
If you want check for original changing (see #antindexer comments) then you can use below code
$(document).ready(function(){
//Check this link
$("#textfields1").change(function(){
var defaultValue = document.getElementById('textfields1').defaultValue;
var currentValue = document.getElementById('textfields1').value;
if( currentValue != currentValue ) {
$("#haschange").val(1);
}
});
});
You could do something like this:
Add data attributes to your input fields. Replace "<%= serverValue %>" with whatever syntax your server code uses.
<form id="form">
<table>
<tr>
<td><input type="text" value="<%= serverValue %>" data-original-value="<%= serverValue %>" /></td>
</tr>
</table>
<input type="submit" value="submit" />
</form>
And then place a script tag on the page with something like this (assuming you're using jQuery):
<script>
$(function () {
var $form = $('#form');
$form.on('submit', function (e) {
$(form).find('[data-original-value]').each(function (index, el) {
var $el = $(el);
if ($el.val() === $el.attr('data-original-value]')) {
e.preventDefault();
console.log('please edit at least one value');
}
});
});
});
</script>
Here is a JSFiddle - http://jsfiddle.net/X4S4y/1/
You can use attr data-value ( or any name you want ) to keep your original value
Example: ( Assume you use PHP )
<input type="text" value="<?php echo $value_1?>" data-value="<?php echo $value_1?>" class="input_text">
<input type="text" value="<?php echo $value_2?>" data-value="<?php echo $value_2?>" class="input_text">
<input type="text" value="<?php echo $value_3?>" data-value="<?php echo $value_3?>" class="input_text">
<input type="text" value="<?php echo $value_4?>" data-value="<?php echo $value_4?>" class="input_text">
In Jquery you can check if there are any change in input text then submit form
Example:
$(document).ready(function(){
$("form").submit(function(){
var is_changed = false;
$(".input_text").each(function(){
if ( $(this).val() == $(this).attr("data-value") {
return false;
} else {
is_changed = true;
}
});
if( is_change == true ) {
alert("Please change at least one input");
return false;
}
});
})

Ajax submit various input values with jquery UI next button click

I am currently working with jquery ui tabs and ajax/post submit without page refresh. With some guidance I have been able to get the div #wmd-preview submited when clicking the next button. The issue is that I also have other fields I will like to submit at the same time when the next button is clicked in various tabs.
How can I submit the input values of various input fields in different tabs when clicking the next button? EXAMPLE
(for some testing i currently have the other input fields submit with keyup and timer setup)
JS- NEXT/Previous button merged with submit/ajax
<script>
var currentTab = 0;
$(function() {
var $tabs = $('#tabs').tabs({
disabled: [0, 1, 2]
, select: function() {
if (currentTab == 0) {
$.ajax({
type: "POST",
url: "test1.php",
data: { "wmdVal": $("#wmd-preview").html() },
success: function(result) {
$('#wmd_result').html( $('#resultval', result).html());
}
});
}
}
, show: function(event, ui) {
currentTab = ui.index;
}
});
$(".ui-tabs-panel").each(function(i) {
var totalSize = $(".ui-tabs-panel").size() - 1;
if (i != totalSize) {
next = i + 2;
$(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page »</a>");
}
if (i != 0) {
prev = i;
$(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>« Prev Page</a>");
}
});
$('.next-tab, .prev-tab').click(function() {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex)
.tabs('select', tabIndex)
.tabs("option","disabled", [0, 1]);
return false;
});
});
</script>
HTML
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<label for="title">Title</label>
<input type="text" id="title" name="title" size="60" autocomplete="off" value="<? $title ?>"/>
<div id="wmd-editor" class="wmd-panel">
<div id="wmd-button-bar"></div>
<textarea id="wmd-input" name="wmd-input"></textarea>
</div>
<div id="wmd-preview" class="wmd-panel"></div>
<div id="wmd_result"></div>
<div id="title_input"style="padding:20px;"></div>
</div>
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
<label for="name">Name</label>
<input type="text" id="name" name="name" size="60" autocomplete="off" value="<? $name ?>"/>
<div id="name_input"></div>
</div>
PHP
<?
if (isset($_POST['title'])){
$wmdVal = $_POST['title'];
echo ('<div id="title_input"><span id="resultval"><h2>Title Echo result:</h2>'.$wmdVal.'</span></div>');
}
if (isset($_POST['wmdVal'])){
$wmdVal = $_POST['wmdVal'];
echo ('<div id="wmd_result"><span id="resultval"><h2>Description Echo result:</h2>'.$wmdVal.'</span></div>');
}
if (isset($_POST['name'])){
$name = $_POST['name'];
echo ('<div id="name_input"><span id="resultval"><h2>Description Echo result:</h2>'.$name.'</span></div>');
}
?>
As far as i know , there's no matter if the fields are in tabs or hidden ,
as long as they have ID , you can get them.
When using , for instance: $('#bla').val() , it will search the whole page until it will find an element with the ID "bla".
Therefore , just add it to the data option, like that:
{key1: 'value1', key2: 'value2'}
Try:
data: { "wmdVal": $("#wmd-preview").html() , "name": $("#name").val() , "title": $("#title").val() },
Should work (not been tested)
UPDATE:
After looking at your site's source code I think I found the problem.
From the results of clicking the next button you can understand that there's a $_POST['title'] variable (isset) , however it's empty.
So there's a problem in the ajax request,
This line:
"title": $("#title").html()
You're not looking for the html() of that input field.
You're looking for val().
Change the line above to:
"title": $("#title").val()
Should work now, update me if not
If you want to run the AJAX POST whenever you change the tab. You have to remove this condition: if(currentTab == 0){. Because this one is forcing the code to run, just when the first TAB is selected.
Besides that, you can post any data that you want. You just need to pass them to "data:" properties of the ajax. And Since they are global and uniques, you can call any of them by their IDs. Like that:
data:{
param1: $("#input1").val(),
param2: $("#input2").val(),
paramHtml1: $("#elementHtml1").html()
}
"title": $("#title").html() should be
"title": $("#title").val() -> you want the value of the field in question. This will send the correct value to the server.
It sort of seems like now you are asking why nothing is being printed in the 'Title Echo result:' area.
I think a good next step might be:
success: function(result) {
// fill title_input with the result of the ajax call
$('#title_input').html(result);
}
That will give you some output, but I think probably not the output you want. Maybe respond with what content you want in the 'title echo area'

Categories