Updating quantity of multiple field from selections using jQuery - javascript

I'm updating quantities in an order form with predefined "packs" from the database. Updating the from fields from the "packs" dropdown in the first function works, but the second function that uses those values and multiplies them by the value in a text input does not update the fields.
Also, when looking at the console output, it looks like the ajax request from the first and second function both run when the quantity input is changed.
jQuery(document).ready(function($) {
$("[id^=packs]").on('change', function() {
var packname = this.value;
console.log("packname:"+packname);
var lineno = this.getAttribute('data-lineno');
console.log("lineno: "+lineno);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>products/pack",
cache: false,
// ContentType : 'application/json',
data: {name: packname},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
console.log(obj);
console.log("size1: "+obj.packdetail[0].size1);
$('#'+lineno+'-size1').attr("value", obj.packdetail[0].size1);
$('#'+lineno+'-size2').attr("value", obj.packdetail[0].size15);
$('#'+lineno+'-size3').attr("value", obj.packdetail[0].size2);
$('#'+lineno+'-size4').attr("value", obj.packdetail[0].size25);
$('#'+lineno+'-size5').attr("value", obj.packdetail[0].size3);
$('#'+lineno+'-size6').attr("value", obj.packdetail[0].size35);
$('#'+lineno+'-size7').attr("value", obj.packdetail[0].size4);
$('#'+lineno+'-size8').attr("value", obj.packdetail[0].size45);
$('#'+lineno+'-size9').attr("value", obj.packdetail[0].size5);
$('#'+lineno+'-size10').attr("value", obj.packdetail[0].size55);
$('#'+lineno+'-size11').attr("value", obj.packdetail[0].size6);
$('#'+lineno+'-size12').attr("value", obj.packdetail[0].size65);
$('#'+lineno+'-size13').attr("value", obj.packdetail[0].size7);
$('#'+lineno+'-size14').attr("value", obj.packdetail[0].size75);
$('#'+lineno+'-size15').attr("value", obj.packdetail[0].size8);
$('#'+lineno+'-size16').attr("value", obj.packdetail[0].size85);
$('#'+lineno+'-size17').attr("value", obj.packdetail[0].size9);
$('#'+lineno+'-size18').attr("value", obj.packdetail[0].size95);
$('#'+lineno+'-size19').attr("value", obj.packdetail[0].size10);
$('#'+lineno+'-size20').attr("value", obj.packdetail[0].size105);
$('#'+lineno+'-size21').attr("value", obj.packdetail[0].size11);
$('#'+lineno+'-size22').attr("value", obj.packdetail[0].size115);
$('#'+lineno+'-size23').attr("value", obj.packdetail[0].size12);
$('#'+lineno+'-size24').attr("value", obj.packdetail[0].size125);
}
catch(e) {
console.log('Exception while request..');
}},
error: function(){
console.log('Error while request..');
}
});
});
//multiply packs
$("[id^=packs_qty]").on('change', function() {
var pack_qty = this.value;
var packname = $(this).attr("data-name");
console.log("qty:"+pack_qty);
console.log("packname:"+packname);
var lineno = this.getAttribute('data-lineno');
console.log("lineno: "+lineno);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>products/pack",
cache: false,
// ContentType : 'application/json',
data: {name: packname},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
console.log(obj);
console.log("size1: "+obj.packdetail[0].size1*pack_qty);
$('#'+lineno+'-size1').attr("value", (obj.packdetail[0].size1*pack_qty));
$('#'+lineno+'-size2').attr("value", obj.packdetail[0].size15*pack_qty);
$('#'+lineno+'-size3').attr("value", obj.packdetail[0].size2*pack_qty);
$('#'+lineno+'-size4').attr("value", obj.packdetail[0].size25*pack_qty);
$('#'+lineno+'-size5').attr("value", obj.packdetail[0].size3*pack_qty);
$('#'+lineno+'-size6').attr("value", obj.packdetail[0].size35*pack_qty);
$('#'+lineno+'-size7').attr("value", obj.packdetail[0].size4*pack_qty);
$('#'+lineno+'-size8').attr("value", obj.packdetail[0].size45*pack_qty);
$('#'+lineno+'-size9').attr("value", obj.packdetail[0].size5*pack_qty);
$('#'+lineno+'-size10').attr("value", obj.packdetail[0].size55*pack_qty);
$('#'+lineno+'-size11').attr("value", obj.packdetail[0].size6*pack_qty);
$('#'+lineno+'-size12').attr("value", obj.packdetail[0].size65*pack_qty);
$('#'+lineno+'-size13').attr("value", obj.packdetail[0].size7*pack_qty);
$('#'+lineno+'-size14').attr("value", obj.packdetail[0].size75*pack_qty);
$('#'+lineno+'-size15').attr("value", obj.packdetail[0].size8*pack_qty);
$('#'+lineno+'-size16').attr("value", obj.packdetail[0].size85*pack_qty);
$('#'+lineno+'-size17').attr("value", obj.packdetail[0].size9*pack_qty);
$('#'+lineno+'-size18').attr("value", obj.packdetail[0].size95*pack_qty);
$('#'+lineno+'-size19').attr("value", obj.packdetail[0].size10*pack_qty);
$('#'+lineno+'-size20').attr("value", obj.packdetail[0].size105*pack_qty);
$('#'+lineno+'-size21').attr("value", obj.packdetail[0].size11*pack_qty);
$('#'+lineno+'-size22').attr("value", obj.packdetail[0].size115*pack_qty);
$('#'+lineno+'-size23').attr("value", obj.packdetail[0].size12*pack_qty);
$('#'+lineno+'-size24').attr("value", obj.packdetail[0].size125*pack_qty);
}
catch(e) {
console.log('Exception while request..');
}},
error: function(){
console.log('Error while request..');
}
});
});
});

can you please convert obj.packdetail[0].size1 and pack_qty in to Number and try,
for this you can use
parseInt(obj.packdetail[0].size1) * parseInt(pack_qty);
Please have a try..

Related

Function is returning value before running inner actions

Using SharePoint's PreSaveAction() that fires when the Save button is clicked, I am trying to run checks and manipulate fields before the form is saved. If PreSaveAction() returns true, the form will be saved and closed.
function PreSaveAction() {
var options = {
"url": "https://example.com/_api/web/lists/getbytitle('TestList')/items",
"method": "GET",
"headers": {
"Accept": "application/json; odata=verbose"
}
}
$.ajax(options).done(function (response) {
var actualHours = response.d.results[0].ActualHours
var personalHours = $("input[title$='Personal Hours']").val();
var regex = /^\d*\.?\d+$/ // Forces digit after decimal point
if (personalHours && regex.test(personalHours)) { // Run if input is not blank and passes RegEx
if (response.d.results[0].__metadata.etag.replace(/"/g, "") == $("td .ms-descriptiontext")[0].innerText.replace("Version: ", "").split('.')[0]) {
// Run if item's data from REST matches version shown in form
addChildItem(id, title, personalHours, actualHours)
}
}
});
return true; // firing before request above begins
}
The function is returning as true before running the jQuery AJAX call which runs addChildItem() that manipulates fields within the form and posts relevant data to a separate list.
function addChildItem(id, title, personalHours, actualHours) {
$.ajax({
method: "POST",
url: "https://example.com/_api/web/lists/getbytitle('ChildList')/items",
data: JSON.stringify({
__metadata: {
'type': 'SP.Data.ChildListListItem'
},
ParentID: id,
Title: title,
HoursWorked: personalHours
}),
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json; odata=verbose",
},
success: function (data) {
console.log("success", data);
var actualHoursNum = Number(actualHours);
var personalHoursNum = Number(personalHours);
$("input[title$='Actual Hours']").val(actualHoursNum + personalHoursNum);
$("input[title$='Personal Hours']").val('');
// Input is getting cleared on save but shows previous number when form is opened again
},
error: function (data) {
console.log("error", data);
}
});
}
This is causing the form to accept the field value manipulations but only after the save and before the automatic closure of the form.
I need PreSaveAction() to wait until after addChildItem() is successful to return true but I'm not sure how to do this. I have tried using a global variable named returnedStatus that gets updated when addChildItem() is successful but the return value in PreSaveAction() still gets looked at before the jQuery AJAX call is ran.
How can I solve this?
I got a similar case by setting async: false to add user to group in PreSaveAction.
Original thread
<script language="javascript" type="text/javascript">
function PreSaveAction() {
var check = false;
var controlName = 'MultiUsers';
// Get the people picker object from the page.
var peoplePickerDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");
var peoplePickerEditor = peoplePickerDiv.find("[title='" + controlName + "']");
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];
if (!peoplePicker.IsEmpty()) {
if (peoplePicker.HasInputError) return false; // if any error
else if (!peoplePicker.HasResolvedUsers()) return false; // if any invalid users
else if (peoplePicker.TotalUserCount > 0) {
// Get information about all users.
var users = peoplePicker.GetAllUserInfo();
for (var i = 0; i < users.length; i++) {
console.log(users[i].Key);
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(22)/users";
$.ajax({
url: requestUri,
type: "POST",
async: false,
data: JSON.stringify({ '__metadata': { 'type': 'SP.User' }, 'LoginName': '' + users[i].Key + '' }),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data) {
console.log('User Added');
check = true;
},
error: function (error) {
console.log(JSON.stringify(error));
check = false;
}
});
}
}
} else {
console.log('No user');
}
return check;
}
</script>

jquery how to display values in alert message

this is my code please help me with the query
$("#update").click(function () {
var security_code = (red[0]["id"]);
var sector_class_id = (red[0]["cid"]);
var sector_id = $("#s1").val();
$.ajax({
type: "POST",
url: "Default.aspx/update",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ security_code: security_code, sector_class_id: sector_class_id, sector_id: sector_id }),
dataType: "json",
success: function (response) {
var updatedata = (response.d);
var ud1 = JSON.parse(updatedata);
udata = $.map(ud1, function (n, i) {
var temp7 =
{
secr_code: n.SECURITY_CODE,
sect_class: n.SECTOR_CLASS_ID,
sect_id: n.SECTOR_ID
}
return temp7
});
$("#mod1").modal('hide');
display();
$("#t1").hide();
$(".alert-succcess").alert();
window.setTimeout(function () {
$(".alert-success").fadeTo(2000, 500).slideUp(500, function () {
//$("#l1").val(security_code);//label values from db
//$("#l2").val(sector_class_id);//label values from db
//$("#s1").val(sector_id);// user selects n den updates value
$(".alert-success").slideUp(500);
});
});
},
i want to show updated values in my alert message along with the previous values which were updated what should i do
what should i do??????

how to get JSON value through Dropdown

We have JSON like this
"[{\"UserID\":1,\"Name\":\"demo\"},{\"UserID\":4,\"Name\":\"ekova\"},{\"UserID\":2,\"Name\":\"Himansu-it\"},{\"UserID\":3,\"Name\":\"Himansu-it Services\"}]"
We need Show UserName to drop-down list and if I Select Name on dropdown We need to get UserID.Like if We Select ekvoa We need get UserID 4
We show userName drop Down like this
function selectitems(){
var getCustomerIDs = jQuery.parseJSON( customerID );
$(getCustomerIDs).each(function() {
console.log(this.UserID);
console.log(this.Name);
$('#date').append('<option>'+this.Name+'</option>');
});
}
We need to post UserID like this
$.ajax({
url:'http://www.himansuit.com/DemoSalesApp/MyService.svc/GetCurrentGeoLocationsByUserID/'+userID,
dataType: 'jsonp',
type:'get',
cache:false,
timeout: 10000,
error: function(x, t, m) {
if(t==="timeout") {
debugger;
$('#alertmessage').empty();
alert("NO Internet Connection");
// withOutNetConnection();
} else {
//alert(t);
}},
success:function(data) {
debugger;
GetAllElementsjson=data;
elements();
}
});
Please guide me .
Set the value of the option to the UserID like so:
$('#date').append('<option value="'+this.UserID+'">'+this.Name+'</option>');
Then when #date changes, you can grab the value ($('#date').val()), which should be the userid.
Add user id as a value in option.get selected option on change event of select box(#date')
$('#date').append('<option value='+this.UserID+'>'+this.Name+'</option>');
call ajax on change event of (#date).
$('#date').on('change',function(){
var userID = $(this).val();
$.ajax({
url:'http://www.himansuit.com/DemoSalesApp/MyService.svc/GetCurrentGeoLocationsByUserID/'+userID,
dataType: 'jsonp',
type:'get',
cache:false,
timeout: 10000,
error: function(x, t, m) {
if(t==="timeout") {
debugger;
$('#alertmessage').empty();
alert("NO Internet Connection");
// withOutNetConnection();
} else {
//alert(t);
}},
success:function(data) {
debugger;
GetAllElementsjson=data;
elements();
}
});
})

AJAX reloads the page without inserting into database

I am new to Ajax and confused. The problem is the ajax reloads the page. The function mentioned in the url inserts the data into database. but the page reloads. I guess the URL is not working but i am not sure on this.
Here is my Controller Function
public function insert_student_fee_payment()
{
$std_code=$this->input->post('std_code');
$total_fee=$this->input->post('total_fee');
$payable_fee=$this->input->post('payable_fee');
$date=date('Y m d');
$class_detail=$this->db->select('class.class_year,class.class_semester')
->join('class','class_student.class_id=class.class_id','LEFT')
->where('class_student.student_id',$std_code)
->where('class_student.class_student_status',2)
->limit(1)
->get('class_student')
->result();
if(count($class_detail)>0)
{
foreach($class_detail as $cd)
{
$year=$cd->class_year;
$semester=$cd->class_semester;
}
}
$data=array(
'std_code'=>$std_code,
'year'=>$year,
'semester'=>$semester,
'total_fee'=>$total_fee,
'payable_fee'=>$payable_fee,
'date'=>$date,
'status'=>2
);
if($this->db->insert('student_fees',$data))
{
echo '1';
}
}
and here is my Ajax code in form
<script type="text/javascript">
$(document).ready(function(){
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '<?php echo base_url()."index.php/finance/insert_student_fee_payment;?>',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
});
});
});
any help guys
We don't see the HTML so it's hard to say what's wrong but my guess is that $('#insert_fee_payment') is a submit button so you have to cancel the action by default which is submitting the form.
$('#insert_fee_payment').click(function(e){
e.preventDefault();
};
or
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '/index.php/finance/insert_student_fee_payment',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
});
return false;
});
Add return false after the error function.
$(document).ready(function(){
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '/index.php/finance/insert_student_fee_payment',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
return false;
});
});
});

ajax to pass array value , how to fetch array on called page

I have array containg image path ,
GenerateReport[0] ="../images/Desert1.jpg"
GenerateReport[1] ="../images/Desert2.jpg"
GenerateReport[2] ="../images/Desert3.jpg"
GenerateReport[3] ="../images/Desert4.jpg"
GenerateReport[4] ="../images/Desert5.jpg"
I am trying to pass this array with following code,
$.ajax({
type: "POST",
url: "generatePdf.php",
data: {
genRep: "sample value"
},
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
sample value is passed successfully , but how can i pass array to ajax and use it on another page?? i tried passing array and using with below code but it is not working
$data1 = $_REQUEST['genRep'];
echo "tested".$data1[0];
Try like
genRep = [];
$.ajax({
type: "POST",
url: "generatePdf.php",
data: {
genRep: GenerateReport
},
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
It will send your array as genRep
try to use json object. in object you can store your images path
var data=[]; // array
var data[0] = 'something';
var data[1] = 'something1';
var data = { 'name': name, 'email' : email, 'contact' : contact, 'type' : type, 'msg' : msg }; // object
$.ajax({
url : 'contact.php',
type : 'POST',
data : {contact:JSON.stringify(data)}, // for json object
data : {contact: data}, // for array
success : function (msg)
{
alert(msg);
}
})
contact.php
$info = $_POST['contact'];
$info = json_decode($info,true); // for json object
echo $info.name; // for json object
echo $info[0]; // will print something...
$arr = array();
$arr[0] = "Mark Reed";
$arr[1] = "34";
$arr[2] = "Australia";
echo json_encode ($arr);
use this on the php page
and use the following to get the output
success:function(msg){
id_numbers = JSON.parse(msg);
alert(id_numbers)
}
Try:
$.ajax({
url: "generatePdf.php",
type: 'POST',
data: form_data,
dataType:"json",
success: function(data) {
alert(data[0]);
}
On the PHP side, you'll be wanting to print:
print json_encode($photos);
Made Some Change
print json_encode(array("photolist"=>$photos));
Then on the server, you'd access these with:
data.photolist[0]; //First photo
I have tested it, this will definitely work !
JS:
var GenerateReport = [];
GenerateReport[0] ="../images/Desert1.jpg";
GenerateReport[1] ="../images/Desert2.jpg";
GenerateReport[2] ="../images/Desert3.jpg";
GenerateReport[3] ="../images/Desert4.jpg";
GenerateReport[4] ="../images/Desert5.jpg";
$.ajax({
type: 'POST',
url: 'generatePdf.php',
data: 'image_array='+GenerateReport,
success: function(msg) {
alert(msg);
}
});
generatePdf.php :
<?php
$image_string = $_POST['image_array'];
$image_array = explode(",", $image_string);
print_r($image_array);
?>
Then you can loop over the $image_array to get the values.
try this
GenerateReport[0] ="../images/Desert1.jpg"
GenerateReport[1] ="../images/Desert2.jpg"
GenerateReport[2] ="../images/Desert3.jpg"
GenerateReport[3] ="../images/Desert4.jpg"
GenerateReport[4] ="../images/Desert5.jpg"
corrected code:
var imagedata = '';
$.each(GenerateReport,function(index,value))
{
if(imagedata=='')
{
imagedata = imagedata +'image'+index+'='+value;
}
else
{
imagedata = imagedata +'&image'+index+'='+value;
}
});
$.ajax({
type: "POST",
url: "generatePdf.php",
data: imagedata //pass string imagedata
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
imagedata should have sting like this:
image1=../images/Desert1.jpg&image2=../images/Desert2.jpg and so on
if(isset($_REQUEST['genRep']))
{
$data = $_REQUEST['genRep'];
print_r($data1);
echo "tested".$data1[0];
createPdf($data);
}
My code was correct , there was no value on index 0 , thats why it was not printing anything .My Mistake !!!

Categories

Resources