passing a parameter in url ajax - ajax

I have this code, how can I pass a parameter to data.php (data.php?q=) so when user digits something I can filter
the data and retrieve just a subset of records?
var company;
$(document).ready(function() {
$('.select-ajax').multiselect({
maxHeight: 400,
buttonWidth: '100%',
includeSelectAllOption: true,
enableFiltering: true
});
$.ajax({
type: 'GET',
url: '/data.php',
dataType: 'json',
success: function(data) {
$.each(data, function (i, item) {
company = item.company;
$('.select-ajax').append('<option value="' + item.company + '">' + item.company + '</option>');
console.log(item)
});
$('.select-ajax').multiselect('rebuild');
},
error: function() {
alert('error loading items');
}
});
$('.select-ajax').trigger( 'change' );
});
</script>```

Related

ajax() in Laravel 7

My AJAX code is like below
$('select[id="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/cities',
type: "GET",
data: { id: 7},
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error: function(xhr, status, error){
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
}else{
$('select[name="city"]').empty();
}
});
My route is like below
Route::get('/cities/{id}', 'LocationController#getSelectedCityajax');
My controller code is like below
public function getSelectedCityajax($id)
{
return response()->json([
'success'=>'get your data'
]);
}
But I am getting result like below
Error - 400: Bad Request
If your route is -Route::get('/cities/{id}', 'LocationController#getSelectedCityajax');
then ajax call should be-
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
})
$('select[id="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/cities/7',
type: "GET",
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error: function(xhr, status, error){
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
}else{
$('select[name="city"]').empty();
}
});
and if u want send data by post request then route should be -
Route::post('/cities', 'LocationController#getSelectedCityajax');
AJAX Request would be -
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
})
$.ajax({
url: '/cities',
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { id: 7},
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error: function(xhr, status, error){
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
And controller code -
public function getSelectedCityajax(Request $request)
{
$id = $request->get('id');
return response()->json([
'success'=>'get your data'
]);
}

jqGrid afterclickPgButtons bind?

I use jqGrid 4.9.3-pre - free(Oleg). I do not use navbar panel. How do I get at Ajax after afterclickPgButtons?
I found a lot of similar themes, but almost all the navbar to panel. similar question, but jqGridAddEditAfterClickPgButtons callback I not found
ondblClickRow: function (rowid) {
$(this).jqGrid("viewGridRow", rowid, {
beforeShowForm: function(form) {
$.ajax({
url: 'apt_data.php',
method: 'POST',
dataType: 'json',
data: {id: rowid},
success: function(data) {
$(html_var).insertBefore($('#trv_tm', form));
}
});
},
caption: "Details of the invice"
});
},
If you need to have some close to the code, but with viewGridRow, then you need just change the name of jQuery event to jqGridViewBeforeShowForm and jqGridViewAfterclickPgButtons. You can use jqGridViewClickPgButtons which will be triggered before jqGridViewAfterclickPgButtons, but it will be needed more seldom:
$("#list").jqGrid({
// ...
}).bind ("jqGridViewBeforeShowForm", function (e, $form, oper) {
alert("In jqGridViewAfterShowForm");
}).bind ("jqGridViewClickPgButtons", function (e, whichButton, $form, rowid) {
alert("In jqGridViewClickPgButtons: " + whichButton + ", rowid=" + rowid);
}).bind ("jqGridViewAfterclickPgButtons", function (e, whichButton, $form, rowid) {
alert("In jqGridViewAfterclickPgButtons: " + whichButton + ", rowid=" + rowid);
});
see https://jsfiddle.net/OlegKi/cnyon3tt/2/

Syntax Error JSON file read with AJAX

I am getting a syntax error for the square bracket '[' from my JSON file. Given below is the JSON.
[
{
"Product Name":"CPE 10281",
"Application":"Tyres",
"Weight":150,
"Cost to Produce":5000,
"Grade":"A",
"Cost to Sell":40000,
"Strength":100
},
{
"Product Name":"CPE 10282",
"Application":"computers",
"Weight":250,
"Cost to Produce":4000,
"Grade":"H",
"Cost to Sell":25000,
"Strength":90
}
]
I am trying to use AJAX to read my JSON file.
$.ajax({
url: "dataProductJSON.json",
dataType: 'json',
mimeType: "application/json",
success: function (data) {
var item = [];
$.each(data, function (key, val) {
item.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'interest-list',
html: item.join('')
}).appendTo('body');
},
});
I am running my html from Eclipse with Apache Geronimo as the server.
Please Help.
You are missing a { in the below line
success: function (data)
Make it
success: function (data) {
Edit
You are having parsing the data incorrectly , do it as below
$.ajax({
url: "test.html",
dataType: 'json',
mimeType: "application/json",
success: function (data) {
var item = [];
$.each(data, function (key, val){
$.each(val, function (innerKey, innerValue){
item.push('<li id="' + innerKey + '">' + innerValue + '</li>');
});
});
$('<ul/>', {
'class': 'interest-list',
html: item.join('')
}).appendTo('body');
},
});
You need to use 2 loop , one for the array and the other to loop through the object property
I tried things and it is working fine

A grid containing href link links to all the rows instead of a particular row

I have made a grid in which the last column contains a link resend. This link resends the mail to the party mentioned in the row. when I click on that link it resend the mail to all the parties in the grid instead of that particular row.. Below is my code
$(document).ready(
function(){
var lastselsignStatusGrid ;
var signStatusGridurl = $('#signatureStatus_ctxPath').val() + '/rest/retrieveSignStatus';
var maintainsignStatusGridurl = $('#signatureStatus_ctxPath').val() + '/rest/maintainSignStatus';
jQuery('#signStatusGrid').jqGrid({
url: signStatusGridurl,
datatype: "json",
mtype: 'GET',
altRows:true,
loadonce: true,
colNames:['Name','Role','Signature status','Due Date','Signed Date','Email','EmailId','PartyId'],
colModel:[
{name: 'name',index: 'name',sortable:true,search:true,sorttype: 'text', searchoptions:{sopt:['eq','ne','bw','cn']}},
{name: 'role',index: 'role',sortable:true,search:true,sorttype: 'text', searchoptions: {sopt:['eq','ne','bw','cn']}},
{name: 'signed',index: 'signed',sortable:false,search:false,sorttype: 'text'},
{name: 'dueDate',index: 'dueDate',formatter: 'date', formatoptions: {"srcformat":"m/d/Y","newformat":"m/d/Y"}, unformat: unformat, sortable:false,search:false,sorttype: 'date'},
{name: 'signedDate',index: 'signedDate',sortable:false,search:false,sorttype: 'text'},
{name: 'resend',index: 'resend',formatter: customLinksignStatusresend, unformat: unformat, sortable:false,search:false,sorttype: 'text'},
{name: 'emailAddress',index: 'emailAddress',hidden:true },
{name: 'partyId',index: 'partyId',hidden:true}
],
rowNum:10,
rowList:[10,20,30],
multiselect: false,
viewrecords: true,
emptyrecords: "No record present",
imagepath: "js/themes/redmond/images",
autowidth: true,
caption:''
});
function customLinksignStatusresend(cellValue, options, rowObject){
if (rowObject[2] == "Complete") {
return "";
} else{
//return rowObject[5];
//return '' + "Resend";
return '<a href="#Test">' + cellValue + '<a>';
}
}
$(document).delegate('#signStatusGrid .jqgrow td a[href="#Test"]', 'click', function ()
{
var localGridData = $("#signStatusGrid").jqGrid('getGridParam','data');
var postData = JSON.stringify(localGridData);
var rowDetails="";
var selectedRows = $('#signStatusGrid').jqGrid('getGridParam', 'data');
var rowsArray = new Array();
var rowId = '';
for(var i=0;i<localGridData.length;i++)
{
var rowData = localGridData[i];
var emailAddr = rowData.emailAddress;
var partyId = rowData.partyId;
rowDetails += partyId+":" +emailAddr+ ',';
$.ajax({
url: $('#signatureStatus_ctxPath').val()+'/rest/resendEmail?partyId='+ partyId,
datatype : "json",
contentType: "application/json; charset=utf-8",
type:"POST",
error : function(xhr, textStatus, errorThrown) {
alert(errorThrown);
},
success : function(response, textStatus, xhr) {
alert("email resent successfully");
}
});
HideLayer();
}
});
You are looping through all the rows in the grid which is why the mail is being sent to all the recipients.
The easy way to do what you are trying to achieve would be to use the onCellSelect function of jqGrid to send mail to the particular Row emailId. You can add additional conditions so that it gets called only when the link is clicked.
onCellSelect: function (id, iCol, cellContent, e) {
if (iCol == 'resend') {
var emailAddr = $('#signStatusGrid').getCell(id, 'emailAddress');
var partyId = $('#signStatusGrid').getCell(id, 'partyId');
var rowDetails += partyId + ":" + emailAddr + ',';
$.ajax({
url: $('#signatureStatus_ctxPath').val() + '/rest/resendEmail?partyId=' + partyId,
datatype: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
},
success: function (response, textStatus, xhr) {
alert("email resent successfully");
}
});
}
},
Another alternate solution seems to be to create a function with sending mail and setting a link which will call the same with respective partyId in the gridComplete function of jqGrid :
gridComplete: function () {
var ids = jQuery("#signStatusGrid").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
var partyId = $('#signStatusGrid').getCell(ids[i], 'partyId');
var be = "<a href='#Test' onclick='sendMail(" + partyId + ");' >View Contract</a>";
jQuery("#signStatusGrid").jqGrid('setRowData', ids[i], {
editct: be
});
}
},
var sendMail(partyId) {
$.ajax({
url: $('#signatureStatus_ctxPath').val() + '/rest/resendEmail?partyId=' + partyId,
datatype: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
},
success: function (response, textStatus, xhr) {
alert("email resent successfully");
}
});
}

Ajax Json multiple parameters

This code below sitting on a ASP.Net application on the Site.Mater....
I need to pass another two parameters from the default.aspx page, one asp:label and one asp:textbox
What is the easiest way to do that?
Thanks
<script type="text/javascript">
$(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "TestWebService.asmx/FetchList",
data: "{ 'testName': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
In your jQuery autocomplete, You need to change your data parameter to this:
data: "{ 'testName': '" + request.term + "' ,lbl: '" + $(".lblClass").text() + "' ,txt: '" + $(".txtClass").val() + "'}"
And then change your service method like this:
[WebMethod]
public List<string> FetchList(string testName, string lbl, string txt)
{
//...
}
Note:
.lblClass and .txtClass are classes for ASP:Lable and ASP:TextBox respectively.

Resources