Form submitting using Ajax? - ajax

My form submits and it shouldn't as I am using aJax?! If I remove the form tag and closing form tag then it works but doesn't upload the image
$('#savebutton').click(function() {
preventDefault();
var val1 = $('#rsPubName').val();
var val2 = $('#address').val();
var val3 = $('#rsLat').val();
var val4 = $('#rsLong').val();
var val5 = $('#add2').val();
var val6 = $('#rsTown').val();
var val7 = $('#rsCounty').val();
var val8 = $('#rsPostCode').val();
var val9 = $('#region').val();
var val10 = $('#PremisesType').val();
var val11 = $('#rsTel').val();
var val12 = $('#rsWebsite').val();
var val13 = $('#rsAboutpub').val();
var val14 = $('#img1').val();
var val15 = $('#offer1').val();
$.ajax({
type: 'POST',
url: 'addpub-script.php',
enctype: 'multipart/form-data',
data: { rsPubName: val1, address: val2, rsLat: val3, rsLong: val4, add2: val5, rsTown: val6, rsCounty: val7, rsPostCode: val8, region: val9, PremisesType: val10, rsTel: val11, rsWebsite: val12, rsAboutpub: val13, img1: val14, offer1: val15},
success: function(response) {
$('#result').html( '<div class="alert alert-success alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><strong>New venue added!</strong> Why not add another?</div>').fadeIn()
}
});
});

preventDefault(); is a method on the event object. It should be:
$('#savebutton').click(function(event) {
event.preventDefault();
...
});
where event is a passed in parameter prefilled by jQuery. See this page and the fourth method down.

Related

Uncaught TypeError: Cannot set properties of undefined (setting '_DT_CellIndex')

i got this error
Error
i was trying to get a value from an ajax call, and then i append that value to a datatable but that error shows up
this is my html for the table
<table id="tablelaporan" class="table table-striped table-hover" style="width:100%;">
<thead>
<tr>
<th>No</th>
<th>Nama Sales</th>
<th>Target</th>
<th>Status</th>
<th>Total Sales</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
below is my full code for that call
function load_data() {
var bulan = $('#inputbulan').val();
var tahun = $('#inputtahun').val();
$.ajax({
url: "services/gettargetsales.php",
method: "POST",
data: {
bulan: bulan,
tahun: tahun
},
success: function(data) {
$('#tablelaporan tbody').html('');
$('#tablelaporan').dataTable().fnClearTable();
$('#tablelaporan').dataTable().fnDestroy();
var co = 1;
html = "";
var i;
data.forEach(function(line) {
var row = $("<tr></tr>");
var col1 = $("<td>" + co + "</td>");
var col2 = $("<td>" + line['nama'] + "</td>");
var col3 = $("<td>" + line['target'].toLocaleString() + "</td>");
stats = 'Sudah Terpenuhi';
if (line['status'] == 0) {
stats = 'Belum Terpenuhi';
}
var col4 = $("<td>" + stats + "</td>");
col1.appendTo(row);
col2.appendTo(row);
col3.appendTo(row);
col4.appendTo(row);
var id_sales = line['id_sales'];
var penjualan = 0;
// console.log(id_sales);
var testing=0;
console.log("1:"+testing);
$.ajax({
url: "services/get_penjualan_bulan.php",
method: "GET",
data: {
bulan: bulan,
tahun: tahun,
id_sales: id_sales
},
success: function(data2) {
penjualan = data2[0]['total'];
testing=data2[0]['total'];
console.log("2:"+testing);
if (data2[0]['total'] == null) {
penjualan = "0";
}
var col5 = $("<td>" + penjualan + "</td>");
col5.appendTo(row);
},
error: function(data2) {
console.log(data2)
}
});
console.log("1:"+testing);
// console.log(penjualan)
co++;
$("#tablelaporan tbody").append(row);
html += row;
})
$('#tablelaporan').DataTable({
dom: 'lrtip',
"autoWidth": false,
"scrollX": true
});
},
error: function(data) {
console.log(data);
}
});
}
the value in the table shows up but i got that error, and when i tried to remove the nested ajax and fill the col5 with 0 it works, anybody know what's happening here and how do i fix this issue?
i have it figured out by adding async:false to the second ajax like so:
$.ajax({
url: "services/get_penjualan_bulan.php",
method: "GET",
data: {
bulan: bulan,
tahun: tahun,
id_sales: id_sales
},
async: false, //<-----this is the solution
success: function(data2) {
penjualan = data2[0]['total'];
testing=data2[0]['total'];
console.log("2:"+testing);
if (data2[0]['total'] == null) {
penjualan = "0";
}
var col5 = $("<td>" + penjualan + "</td>");
col5.appendTo(row);
},
error: function(data2) {
console.log(data2)
}
});
i read this solution isn't really recommended, but it works

How to sort result in JavaScript

I'm getting success result in my ajax code and can return data in my view but i want to sort the results by their id in database,
Example
id => 3 , one
id => 5 , three
id => 2 , five
result should be:
five
one
three
Code
<script defer>
$(document).ready(function() {
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
$.each(result, function(key1, value1) {
var vvvid = value1.id;
// second data
$.ajax({
url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
type: "GET",
dataType: "json",
success:function(data) {
var my_row = $('<div class="row mt-20 ccin">');
var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_id" id="specification_id" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-6"><input id="text_dec" name="text_dec[]" placeholder="text field" class="text_dec form-control"></div>';
my_html += '<div class="col-md-2"><button type="button" id="custmodalsavee" class="custmodalsavee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
$('div#dataaa').append(my_row);
}
});
// second data
});
}
});
}else{
$('div#dataaa').empty();
}
});
});
</script>
PS: what I need is to return vvvid part by their id in database.
Question
How can I sort my output data?
Sort your result by the id in a one-liner shameless lifted from this answer.
Then $.each() it.
success:function(result) {
result.sort(function(a,b) {
return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
});
// console.log(result);
$.each(result, function(key1, value1) {
I believe that your ID is in your object like it
{
id: 1,
title: sample
}
Make a function like it
static compare(a,b) {
if (a.id > b.id)
return -1;
if (a.id < b.id)
return 1;
return 0;
}
Using
let array = [{},{},{}];
array.sort(this.compare);
To change the order by, just reverse > and < in the function

How to send selected values with ajax to controller to use as parameters in stored procedure

I am trying to collect selected values from two drop down boxes with multiselect. Then send the data with ajax as strings to a controller to use in stored procedure for a partial view. I can see that the strings are being sent, but the SQL is not running. Can anyone help please, I have trawled everywhere but can't find a similar problem. Thank you.
VIEW
#Html.AntiForgeryToken()
<div class="PropLandingGrid">
<div class="PLAND_A1">
<select name="SuburbDDL" id="SuburbDDL" multiple="multiple"></select>
</div>
<div class="PLAND_A3">
<select name="AreaDDL" id="AreaDDL" multiple="multiple"></select>
</div>
<div class="PLAND_D1"><button type="button" id="btnSearch" class="btn-det15035">Show</button></div>
</div>
<div id="PropContainer"></div>
$(document).ready(function ()
{
var SuburbDDL = $('#SuburbDDL');
var AreaDDL = $('#AreaDDL');
var AreaDet = null;
var AreaQ = null;
var SuburbDet = 1;
var SuburbQ = null;
AreaDDL.multipleSelect();
// suburb
$.ajax({
url: '/tProps/GetSuburbList',
method: 'post',
dataType: 'json',
success: function (data) {
SuburbDDL.append($('<option/>', { value: -1, text: "Select Suburb" }));
$(data).each(function (PropLanding2, item) {
SuburbDDL.append($('<option/>', { value: item.SuburbID, text: item.Suburb }));
});
$('select option:contains("Hout Bay")').prop('selected', true);
SuburbDDL.multipleSelect();
SuburbDet = 1;
}
});
// area
$.ajax({
url: '/tProps/GetAreaListJS',
method: 'post',
data: { SuburbID: '1' },
dataType: 'json',
success: function (data) {
AreaDDL.empty();
AreaDDL.append($('<option/>', { value: -1, text: "Select Area" }));
AreaDDL.attr("disabled", false);
$(data).each(function (PropLanding2, item) {
AreaDDL.append($('<option/>', { value: item.AreaID, text: item.Area }));
});
AreaDDL.multipleSelect();
AreaDet = null;
}
});
SuburbDDL.change(function () {
if ($(this).val() == '-1') {
AreaDDL.empty();
AreaDDL.append($('<option/>', { value: -1, text: "Select Area" }));
AreaDDL.val('-1');
AreaDDL.attr('disabled', true);
}
else {
AreaDDL.attr("disabled", false);
$.ajax({
url: '/tProps/GetAreaListJS',
method: 'post',
data: { SuburbID: $(this).val() },
dataType: 'json',
success: function (data) {
AreaDDL.empty();
AreaDDL.append($('<option/>', { value: -1, text: "Select Area" }));
AreaDDL.attr("disabled", false);
$(data).each(function (PropLanding2, item) {
AreaDDL.append($('<option/>', { value: item.AreaID, text: item.Area }));
});
}
});
SuburbDet = SuburbDDL.multipleSelect('getSelects');
}
});
AreaDDL.change(function ()
{
if ($(this).val() == '-1') {
AreaDet = null;
}
else
{
AreaDet = AreaDDL.multipleSelect('getSelects');
}
});
$("#btnDets").click(function () {
alert("Suburb: " + SuburbDet + ", Area: " + AreaDet)
});
$("#btnSearch").click(function () {
SuburbDet1 = (String(SuburbDet).replace(/,/g, "</SuburbId></Detail><Detail><SuburbId>"));
SuburbDet2 = "<Root><Detail><SuburbId>" + SuburbDet1 + "</SuburbId></Detail></Root>"
console.log(SuburbDet2);
AreaDet1 = (String(AreaDet).replace(/,/g, "</AreaId></Detail><Detail><AreaId>"));
AreaDet2 = "<Root><Detail><AreaId>" + AreaDet1 + "</AreaId></Detail></Root>"
console.log(AreaDet2);
$.ajax({
url: '/tProps/p_PropList2',
contentType: 'application/html',
type: 'GET',
data:
{
'SuburbData': SuburbDet2, 'AreaData': AreaDet2
},
dataType: 'html',
success: function (result) {
$('#PropContainer').html(result);
alert("success");
},
error: function () {
alert("something went wrong");
}
})
});
CONTROLLER
public PartialViewResult p_PropList2(String SuburbData, String AreaData, string sortBy)
{
String StringSQL = "DECLARE #SuburbXML VARCHAR(MAX) DECLARE #AreaXML VARCHAR(MAX) SET #SuburbXML = " + SuburbData + " SET #AreaXML = " + AreaData + " EXEC spPropertyListXML #SuburbXML, #AreaXML";
var datta = db.Database.SqlQuery<spPropertyListXML_Result>(StringSQL).ToList();
return PartialView("p_PropList2", datta.ToList());
}
STORED PROCEDURE
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spPropertyListXML]
#SuburbXML XML -- sd1: defined as xml
, #AreaXML XML -- sd1: defined as xml
AS
BEGIN
SET FMTONLY OFF
SET NOCOUNT ON
BEGIN TRY
-- create temp
CREATE TABLE #TempSuburb (SuburbId INT)
CREATE TABLE #TempArea (AreaId INT)
-- load temp
INSERT INTO #TempSuburb(SUburbId)
SELECT Suburb.ID.query('SuburbId').value('.','INT')
FROM #SuburbXML.nodes('/Root/Detail') AS Suburb(ID)
INSERT INTO #TempArea(AreaId)
SELECT Area.ID.query('AreaId').value('.','INT')
FROM #AreaXML.nodes('/Root/Detail') AS Area(ID)
-- use data in temp
SELECT tArea.Area, tArea.AreaID, tSuburb.SuburbID, tSuburb.Suburb, tProp.Erf, tProp.ErfSq, tProp.Num
FROM tprop
INNER JOIN tArea ON tArea.AreaID = tprop.area
INNER JOIN tSuburb ON tSuburb.SuburbID = tarea.SuburbID
WHERE (NOT EXISTS (SELECT TOP 1 1 FROM #TempSuburb)
OR tSuburb.SuburbID IN (SELECT a.SuburbId FROM #TempSuburb a)
)
AND (NOT EXISTS (SELECT TOP 1 1 FROM #TempArea)
OR tArea.AreaID IN (SELECT a.AreaId FROM #TempArea a)
)
-- drop temp
DROP TABLE #TempSuburb
DROP TABLE #TempArea
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0 ROLLBACK TRAN
DECLARE #ERROR_MESSAGE VARCHAR(MAX)
DECLARE #ERROR_SEVERITY INT
SELECT #ERROR_MESSAGE = ERROR_MESSAGE()
, #ERROR_SEVERITY = ERROR_SEVERITY()
RAISERROR(#ERROR_MESSAGE, #ERROR_SEVERITY, 1)
END CATCH
END

The parameter to the function is required but was not passed in

I am making a filter in order to drill down into a report. I have two fields that are dependent on the selection of another field (which is a multiselect list). When I make my selection(s) from that multiselect field, it looks like the parameter is being passed in as an array and ultimately not being recognized. It looks as if my parameter is being passed in as an array, which I'm thinking is the issue
Javascript Code:
function getMO()
{
var fa_code = $('#tslcFilterFA').val();
var ao_code = $('#tslcFilterAO').val();
var wq_code = $('#tslcFilterWQ').val();
var newOption = '';
$('#tslcFilterMO').empty();
$('#tslcFilterMO').append(newOption);
$('#TSLC_MO_Loading').css('display','inline');
$.ajax({
url: '../TSLC/getData.cfc',
type:"POST",
cache: false,
dataType: "text",
async:true,
data: {method: "getMO",
fa_code: fa_code,
ao_code: ao_code,
wq_code: wq_code
},
success: function(returnMsg)
{
try
{
var obj = JSON.parse(returnMsg);
$.each(obj.DATA, function(index,row) {
if (obj.DATA.length == 1)
{
var newOption = '<option selected="selected" value="' + row[0] + '">' + row[1] + '</option>';
}
else
{
if (row[2] == "1")
{
var newOption = '<option selected="selected" value="' + row[0] + '">' + row[1] + '</option>';
}
else
{
var newOption = '<option value="' + row[0] + '">' + row[1] + '</option>';
}
}
$('#tslcFilterMO').append(newOption);
});
try
{
$('#tslcFilterMO').multiselect('destroy');
}
catch(e) {}
$('#tslcFilterMO').multiselect({
selectedList: 4
}).multiselectfilter();
$('.ui-multiselect').css('width','225px');
$('#TSLC_MO_Loading').css('display','none');
}
catch(e)
{
alert('getMO Error parsing JSON');
}
},
error: function(httpRequest, textStatus, errorThrown)
{
alert("getMO status=" + textStatus + ",error=" + errorThrown);
}
});
}
I've tried to change this line:
var ao_code = $('#tslcFilterAO').val();
to this:
var ao_code = $('#tslcFilterAO').multiselect('getChecked').map(function () {return this.value;}).get();
I've also tried to wrap my ao_code variable in URLDecode() to see if it would pass the value as a string instead of an array, but neither works.
CF Code (from component):
<cffunction name="getMO" access="remote" returntype="any" returnformat="plain" hint="Get distinct Managing Orgs based on FA=ATT_IT and AO">
<cfargument name="fa_code" type="string" required="true">
<cfargument name="ao_code" required="true">
<cfargument name="wq_code" required="true">
<cfquery name="qMO" datasource="#request.dbdsn_ic4p#" username="#request.dbuser_m66266#" password="#request.dbpw_m66266#">
SELECT DISTINCT managing_org MANAGING_ORG, DECODE(managing_org,'*','*ALL*',managing_org) MANAGING_ORG_DISPLAY, DECODE(managing_org,'*',1,2) sortcol
<cfif #fa_code# NEQ "ATT_IT">
FROM HAS_TICKET_STATE_GUI_LOOKUP
WHERE client_id = '#fa_code#'
<cfelse>
FROM IT_TICKET_STATE_GUI_LOOKUP
WHERE 1=1
</cfif>
<cfif #ao_code# neq "">
AND active_org IN (<cfqueryparam value="#ao_code#" cfsqltype="cf_sql_varchar" list="true" />)
</cfif>
<cfif #wq_code# neq "">
<!--- !COM: is workaround for commas in listbox items! --->
AND work_queue IN (#replace(ListQualify(wq_code,"'",",","CHAR"),":COM!",",","all")#)
</cfif>
ORDER BY 3, 1
</cfquery>
<cfreturn serializeJson(qMO)>
</cffunction>
Change this line in your JS code
var ao_code = $('#tslcFilterAO').val();
to
var ao_code = $('#tslcFilterAO').val().join(",");
That should give you a list of string values from the multiple select field that you're expecting in your function in the CFC.
The join() method joins all elements of an array into a string. More on "join" here.
This article helped me solve my problem... https://christierney.com/2011/06/07/returning-multiple-value-elements-to-coldfusion-remote-method-via-jquery-ajax/
function getWQ()
{
var fa_code = $('#tslcFilterFA').val();
var ao_code = $('#tslcFilterAO').val();
if ($.isArray(ao_code))
var ao_code_array = ao_code.join(",");
else
var ao_code_array = ao_code;
var mo_code = $('#tslcFilterMO').val();
if ($.isArray(mo_code))
var mo_code_array = mo_code.join(",");
else
var mo_code_array = mo_code;
var newOption = '';
$('#tslcFilterWQ').empty();
$('#tslcFilterWQ').append(newOption);
$('#TSLC_WQ_Loading').css('display','inline');
$.ajax({
url: '../TSLC/cfcs/getData.cfc',
type:"POST",
cache: false,
dataType: "text",
async:true,
data: {method: "getWQ",
fa_code: fa_code,
mo_code: mo_code_array,
ao_code: ao_code_array
},
success: function(returnMsg)
{
Have you considered a combination of the jQuery serializeArray() function and the param() function? It creates a string similar to a query string which is easily parsed. You could send the whole form in.
Example: $.param($('#yourform').serializeArray(),false);
Or, perhaps, simply use the serializeArray function to send your function a JSON string?

Ajax Post method issue with passing huge data

folks
we are facing a strange issue with jquery ( 1.8.3) and we are using cakePHP
as per the image
Our assumption is we are sending the data( about 500 +) with ajax call in POST method.
we are having this issue in all the major browsers.
as above( in chrome) , we are getting this error in console we passed 618 destinations in ajax call.
let us know the work around to solve this problem.
My ajax call is as below
function validate_test() {
$("#btn1").empty();
var ele = document.getElementById('frm_searchDateFrom').value;
var ele2 = document.getElementById('frm_searchDateTo').value;
var sub_url = '<?php echo $this->Html->url('/', true); ?>';
var url = sub_url + "admin/reports/check_originator/" + ele +"/"+ ele2 +"/"+ $("#destination").val();
alert(url);
jQuery.ajax({
type: "POST",
datatype: "json",
url: url,
success: function(data)
{
var el = $("select#btn1").multiselect();
var d;
var results=data.split(",");
for(d=0;d<results.length;d++) {
var d;
var v = results[d], opt = $('<option />', {
value: v,
text: v
});
opt.appendTo( el );
el.multiselect('refresh');
}
}
})
}
In your JQuery Ajax method instead of posting all those details as url query para meter send by wrapping those details in a object.
function validate_test() {
$("#btn1").empty();
var ele = document.getElementById('frm_searchDateFrom').value;
var ele2 = document.getElementById('frm_searchDateTo').value;
var sub_url = '<?php echo $this->Html->url('/', true); ?>';
var url = sub_url + "admin/reports/check_originator/";
var formdata=ele +"/"+ ele2 +"/"+ $("#destination").val();//put form data's in an object
alert(url);
jQuery.ajax({
type: "POST",
datatype: "json",
data:formdata,//send the form data object in post
url: url,
success: function(data)
{
var el = $("select#btn1").multiselect();
var d;
var results=data.split(",");
for(d=0;d<results.length;d++) {
var d;
var v = results[d], opt = $('<option />', {
value: v,
text: v
});
opt.appendTo( el );
el.multiselect('refresh');
}
}
})
}
Also refer this fiddle(not mine):
http://jsfiddle.net/clickthelink/Uwcuz/1/

Resources