syntaxerror missing } after property list - ajax

<script>
function changeProgram(val){
$.ajax({
type: "POST",
url: "getSemester?pro=NULL",
data: {pro: val, staff_id: $('#staff_id').val(),
success: function(data) {
var new_data = $.parseJSON(data);
if(new_data.length>0 ){
var dom ="<option value=''>SELECT</option>";
for(var index = 0; index < new_data.length; index++) {
dom += "<option value='"+new_data[index].SM_SEMESTER_CODE+"'>"+new_data[index].STOTAL+" - "+new_data[index].SM_SEMESTER_DESC+"</option>";
}
$(".semesterGroup").html(dom);
}else{
var dom ="<option value=''>SELECT</option>";
$(".semesterGroup").html(dom);
}
}
});
}
</script>

Easy fix.
Just a missing bracket on this line
data: {pro: val, staff_id: $('#staff_id').val()} <--- ,

You are missing } for data:
Here is the solution code -
function changeProgram(val){
$.ajax({
type: "POST",
url: "getSemester?pro=NULL",
data: {pro: val, staff_id: $('#staff_id').val()},
success: function(data) {
var new_data = $.parseJSON(data);
if(new_data.length>0 ){
var dom ="<option value=''>SELECT</option>";
for(var index = 0; index < new_data.length; index++) {
dom += "<option value='"+new_data[index].SM_SEMESTER_CODE+"'>"+new_data[index].STOTAL+" - "+new_data[index].SM_SEMESTER_DESC+"</option>";
}
$(".semesterGroup").html(dom);
}else{
var dom ="<option value=''>SELECT</option>";
$(".semesterGroup").html(dom);
}
}
});
}

Related

How to use for loop in ajax success function?

This is my alert output result:
The above picture array is my result that is get from table using ajax request.but i don't know how to use in for loop and i have tired in for loop the value is splitted one by one like
My code
<script type="text/javascript">
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
alert(data);
var result = data;
var arr = result;
for (var i = 0; i < arr.length; i++){
document.write("<br><br>array index: " + i);
var obj = arr[i];
for (var key in obj){
var value = obj[key];
document.write("<br> - " + key + ": " + value);
}
}
}
});
});
</script>
You can modify your script like this and then do whatever Logic you want for the response
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
myGoodFunctionToHandleResponse(data);
}
});
});
function myGoodFunctionToHandleResponse(data){
for(let i in data){
console.log(data[i]);
}
}
I have forgot to put JSON.parse() this function after success function and so i didn't get the correct result so far.
<script type="text/javascript">
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
var result = JSON.parse(data)
var mycars = result;
for (i in mycars)
{
if( mycars[i].dc == "C"){
var credit = mycars[i].Amt;
}
else{
var debit = mycars[i].Amt;
}
if(credit > debit)
{
var bal = credit - debit;
}
else{
var bal = debit - credit;
}
}
$('#bal').val(bal);
}
});
});
</script>

Leaflet markers duplicating, removeLayer problem

I have Ajax function in my Laravel project. I'm taking data from db and send them on Leaflet map.
When I have setInterval, markers starts to duplicate. Unfortunately removeLayer can not help me, or I'm ussing it wrong.
This is my code
function callAjax() {
$.ajax({
url: '/device_new',
type: 'GET',
dataType: 'json',
success: function(data) {
markerLayer.removeLayer();
var markerLayer = L.featureGroup().addTo(map);
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
marker.addTo(markerLayer);
}
}
map.fitBounds(markerLayer.getBounds());
},
});
setInterval(callAjax, 3000);
}
Any idea what could be a problem?
removeLayer(<Layer>) removes a single given layer from the featureGroup.
You need
markerLayer.clearLayers()
to remove all layers.
Change your code to:
function callAjax() {
$.ajax({
url: '/device_new',
type: 'GET',
dataType: 'json',
success: function(data) {
markerLayer.clearLayers();
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
marker.addTo(markerLayer);
}
}
map.fitBounds(markerLayer.getBounds());
},
});
setInterval(callAjax, 3000);
}
function loadMap() {
// Where you want to render the map.
var element = document.getElementById('osm-map');
// Height has to be set. You can do this in CSS too.
element.style = 'height:405px;', 'width:500px;';
// Create Leaflet map on map element.
map = L.map(element);
// Add OSM tile leayer to the Leaflet map.
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
map.pm.addControls({
position: 'topleft',
});
//********************** ADD HERE **************
var markerLayer = L.featureGroup().addTo(map);
}

where I shall give the parameter in ajax get?

this is my controller action that returns json
public ActionResult MapTest(string date)
{
var locations = _db.EMP_LOCATION.Where(m => m.CURRENT_DATE.Equals(date));
return Json(locations,JsonRequestBehavior.AllowGet);
}
My scrip is here
var script = {
callAction: function () {
$.ajax({
url: 'Home/MapTest',
type:'GET',
dataType: "json",
success: function (message) {
var count = message.length;
for (var i = 0; i < count; i++) {
$('#maplong').append(message[i].LATITUDE, " ", message[i].LONGITUDE," ");
}
},
complete: function () {
alert('completed');
}
});
}
}
Now my question is where i can give date parameter in $.ajax and how?
Just do something like:
var script = {
callAction: function () {
$.ajax({
url: 'Home/MapTest',
type:'GET',
data: JSON.stringify({ date: "your date" })
dataType: "json",
success: function (message) {
var count = message.length;
for (var i = 0; i < count; i++) {
$('#maplong').append(message[i].LATITUDE, " ", message[i].LONGITUDE," ");
}
},
complete: function () {
alert('completed');
}
});
}
}
Best Regards
You can pass the value in URL like below :
var script = {
callAction: function () {
var dateVal= "Your date";
$.ajax({
url: 'Home/MapTest?date='+dateVal,
type:'GET',
dataType: "json",
success: function (message) {
var count = message.length;
for (var i = 0; i < count; i++) {
$('#maplong').append(message[i].LATITUDE, " ", message[i].LONGITUDE," ");
}
},
complete: function () {
alert('completed');
}
});
}
}
var script = {
callAction: function () {
$.ajax({
url: 'Home/MapTest',
type:'GET',
dataType: "html",
data: { date : "03/25/2013" },
success: function (message) {
var count = message.length;
for (var i = 0; i < count; i++) {
$('#maplong').append(message[i].LATITUDE, " ", message[i].LONGITUDE," ");
}
},
complete: function () {
alert('completed');
}
});
}
}

Passing AJAX request in MVC3 environment

I was using MVC3 with AJAX. I was using AJAX within another AJAX. For the first AJAX request, it properly sends to the controller with data. But after returning from the AJAX request, I again posting the same data to another action. But second time the data comes null when coming to the controller. Please help me to fix this issue.
Code
$(document).ready(function () {
$('.deleteitems').live('click', function (e) {
var items = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items.push($(this).attr("Id"));
});
var json = JSON.stringify(items);
var perm = $("#Permission").val();
if (items.length != 0) {
if (perm == "True") {
$.ajax({
url: '/ItemControl/ItemControl/Catalogue_Check',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data == "S") {
DelBibsAlso();
}
else {
DelItemsonly();
}
}
});
}
else {
$("#divMes").removeClass("Success");
$("#divMes").addClass("Error");
showError("Sorry you dont have Permission!");
}
}
else {
alert("Select any Items to delete");
e.preventDefault();
}
});
});
function DelItemsonly() {
var items2 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items2.push($(this).attr("Id"));
});
var itemjson = JSON.stringify(items2);
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: { "id": itemjson, "DelBib": 0 },
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});
}
else {
e.preventDefault();
}
}
function DelBibsAlso() {
var items1 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items1.push($(this).attr("Id"));
});
var bibjson = JSON.stringify(items1);
var value = confirm("Do you also want to delete the catalogue record?");
var cond = 0;
if (value) {
var cond = 1;
}
else {
cond = 0;
}
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: { "id": bibjson, "DelBib": cond },
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});
}
else {
e.preventDefault();
}
}
Controller Code
public ActionResult Catalogue_Check(string[] id)
{
DeleteItem weed = new DeleteItem();
int[] ints = id.Select(x => int.Parse(x)).ToArray();
var Matched_BibID = (from asd in Db.Items
where ints.Contains(asd.Id)
select asd.BibId).ToList();
foreach (var idd in ints)
{
var bibid = (from bib in Db.Items where bib.Id == idd select bib.BibId).Single();
var checkbib = (from bibchk in Db.Items where bibchk.BibId == bibid && !ints.Contains(bibchk.Id) select bibchk.Id).Count();
if (checkbib == 0)
{
return Json("S", JsonRequestBehavior.AllowGet);
}
}
return Json("N", JsonRequestBehavior.AllowGet);
}
public JsonResult DeleteItems(string[] id, int? DelBib)
{
//var newid = id.Split(',');
DeleteItem weed = new DeleteItem();
int[] ints = id.Select(x => int.Parse(x)).ToArray();
foreach (var a in id)
{
int sel = Convert.ToInt32(a);
Item item = Db.Items.Single(i => i.Id == sel);
int Sess = Convert.ToInt16(Session["AccId"]);
string AdminName = User.Identity.Name;
bool Exist = Db.RouteOuts.Any(itm => itm.ItemId == item.Id);
if (!Exist)
{
weed.DeleteIt(item, Sess, AdminName);
var bibid = (from bib in Db.Items where bib.Id == item.Id select bib.BibId).Single();
var checkbib = (from bibchk in Db.Items where bibchk.BibId == bibid && !ints.Contains(bibchk.Id) select bibchk.Id).Count();
if (checkbib == 0)
{
Db.ExecuteStoreCommand("update Bibs set Status= 'D' where Id={0}", item.BibId);
Db.SaveChanges();
}
}
}
return Json("S", JsonRequestBehavior.AllowGet);
}
function Test() {
var items1 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items1.push($(this).attr("Id"));
});
//var bibjson = JSON.stringify(items1); **** Loose this line ****
var value = confirm("Do you also want to delete the catalogue record?");
var cond = 0;
if (value) {
var cond = 1;
}
else {
cond = 0;
}
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ "id": items1, "DelBib": cond }), // **** Items are stringified before posting ****
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});enter code here
}
else {
e.preventDefault();
}

Looping over ajax requests in a chrome extension, not working

I was trying loop over the ajax request continuously but it was doing the ajax thing only for the last loop.
while(i<3){
var query = site_url+keywords[i]+'"' ;
$.ajax({
url: query,
type: "GET",
dataType: "html"
success: function(html) {
var el = $(html).find("#tagID");
if(el.length) {
console.log("Element exists");
var cont = 1;
}
else{
console.log("Element doesnt exist");
var cont = 0;
}
}
});
console.log(cont);
i=i+1;
}
Something along those lines:
processKeyword(0);
function processKeyword(i) {
if(i < keywords.length) {
var query = site_url+keywords[i]+'"' ;
$.ajax({
url: query,
type: "GET",
dataType: "html"
success: function(html) {
var el = $(html).find("#tagID");
if(el.length) {
//found, stop processing
result(i);
} else{
//not found, process next
processKeyword(i + 1);
}
}
});
} else {
//all processed, nothing found
result(-1);
}
}
function result(i) {
//i contains keyword index if was found, -1 otherwise
}

Resources