Can't pass variable into ajax url in javascript - javascript

I'm basically trying to delete an item in mongodb. But I just can't seem to pass the id into the url in the ajax call. Here's my code:
$(".delete-item").on('click', function(e, id) {
var deleteName = $('p.nameLink').text();
// Get ID first
$.ajax({
type: "GET",
url: "/items",
dataType: 'json',
})
.done(function(result) {
// searches mongodb for the clicked name and saves the result in the var
var newResult = $.grep(result, function(e){ return e.name === deleteName; });
var id = newResult[0]._id;
})
.fail(function (jqXHR, error, errorThrown) {
console.log(jqXHR);
console.log(error);
console.log(errorThrown);
});
// Then delete
console.log("ID to DELETE:", id); // I can see id
function itemDelete(id) {
$.ajax({
type: 'DELETE',
url: '/items/' + id,
dataType: 'json',
})
.done(function(result) {
console.log("ID to DELETE:", id); // Can't see the id
})
.fail(function (jqXHR, error, errorThrown) {
console.log(jqXHR);
console.log(error);
console.log(errorThrown);
});
}
itemDelete(id); // pass the id to the function
});
I'm just learning at the moment, so I could be going about this the wrong way. If anyone can help me out, I'd appreciate it.
The error message is:
DELETE https://www.someplace.com/items/undefined 500 (Internal Server Error)

As ajax calls are asynchronous, you should call itemDelete(id) from inside the first .done callback.
Try moving
itemDelete(id);
just after
var id = newResult[0]._id;
This way you will execute your second ajax call only after the first has terminated, and the id variable will be defined.
After the change your code should look like this:
$(".delete-item").on('click', function(e, id) {
var deleteName = $('p.nameLink').text();
$.ajax({
type: "GET",
url: "/items",
dataType: 'json',
})
.done(function(result) {
var newResult = $.grep(result, function(e){
return e.name === deleteName;
});
var id = newResult[0]._id;
itemDelete(id);
})
.fail(function (jqXHR, error, errorThrown) {
console.log(jqXHR);
console.log(error);
console.log(errorThrown);
});
function itemDelete(id) {
$.ajax({
type: 'DELETE',
url: '/items/' + id,
dataType: 'json',
})
.done(function(result) {
})
.fail(function (jqXHR, error, errorThrown) {
console.log(jqXHR);
console.log(error);
console.log(errorThrown);
});
}
});

This one should work for you.
$(".delete-item").on('click', function(e, id) {
var deleteName = $('p.nameLink').text();
// Get ID first
$.ajax({
type: "GET",
url: "/items",
dataType: 'json',
})
.done(function(result) {
// searches mongodb for the clicked name and saves the result in the var
var newResult = $.grep(result, function(e){ return e.name === deleteName; });
var id = newResult[0]._id;
itemDelete(id); // pass the id to the function
})
.fail(function (jqXHR, error, errorThrown) {
console.log(jqXHR);
console.log(error);
console.log(errorThrown);
});
console.log("ID to DELETE:", id); // I can see id
function itemDelete(id) {
$.ajax({
type: 'DELETE',
url: '/items/' + id,
dataType: 'json',
})
.done(function(result) {
console.log("ID to DELETE:", id); // Can't see the id
})
.fail(function (jqXHR, error, errorThrown) {
console.log(jqXHR);
console.log(error);
console.log(errorThrown);
});
}
});
Thanks

The undefined in https://www.someplace.com/items/undefined suggests that the id is undefined. Note that the get and delete requests happen asynchronously, so id is not guaranteed to be set when you make the delete request, since it depends on when the request completes. In other words, try deleting after you get the id. This would require you to make the DELETE request in the success callback of the GET request.

Please try This one
$.ajax({
type: 'get',
dataType : 'html',
url: 'your_url',
data:{variablname:id,type:'DELETE'}
dataType: 'json',
})
In your url page or action get the value as its type is get so the data type will be GET
if(isset($_GET['variablename'],$_GET['type'])){
if($_GET['type']=='DELETE')
delete record from database where id= $_GET['variablename']
}
I hope it will help you Thanks

Related

Handle undefined data in ajax request

I have the below ajax call and sometimes the request stops the page from loading as the data being passed is undefined.
I there a way to put a condition to handle the request if it has values that are undefined?
Can it be wrapped with a if condition?
newuser is not defined
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
Simplest way would be to use a pipe:
$.ajax({url: 'sample.aspx',
data: newuser || {},//continue here...
If your variable was not initialized, empty object will be sent instead.
That's if and only if you can handle empty "newuser" for some reason.
I'm assuming that not closed URL is just a mistake in copy-paste, and not actually part of your code.
how about
if(newuser)
{
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
}
If you are unable to handle an empty newuser you can try something like this:
if (newuser) {
$.ajax({
url: 'sample.aspx',
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data) {
...
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}

Error occurs when i use jQuery Ajax

$('#deviceLoadMore') is a link. When this link is being clicked, it will trigger a ajax to the web service I have created.
The problem I'm having now is it keeps on throwing this error in the console.log
Uncaught TypeError: Converting circular structure to JSON. But when I just paste the ajax part in the console.log, it able to retrieve the data back. I have checked that all the value is just a normal string and integer.
I was wondering why i can trigger in console log without having any issue and couldn't if i just click on the link?
var currentContextSection = '<%=currentSection %>';
var currentTemplateIds = '<%=templateIds %>';
var currentItemPerPage = <%=itemPerPage %>;
var currentPageIndex = <%=currentPage %>;
var arguments = { templateIds:'<%=templateIds %>' , currentSection:'<%=templateIds %>', currentPage:currentPageIndex, itemPerPage:currentItemPerPage };
$(document).ready(function () {
$('#deviceLoadMore').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/AJAX/WS.asmx/GetItems",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(arguments),
dataProcess: false
}).done(function (data) {
test = data;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
});
});
------ EDIT -------
If I have this:
var arguments = {"templateIds":currentTemplateIds ,"currentSection":currentContextSection,"currentPage":currentPageIndex,"itemPerPage":currentItemPerPage};
and executing with the ajax data:JSON.stringify(arguments), i will get the following errror:
Converting circular structure to JSON.
When I console.log the "arguments", it displays:
Object {templateIds: "963C1D18A93849309D6014CE2135173C", currentSection: "Personal", currentPage: 1, itemPerPage: 8}
And it displays this when I console.log JSON.stringify(arguments):
"{"templateIds":"963C1D18A93849309D6014CE2135173C","currentSection":"Personal","currentPage":1,"itemPerPage":8}"
After google around for some successfully implemented ajax sample, I changed my code to the following, and it works! And I have no idea why it works this way.
$(document).ready(function () {
$('#deviceLoadMore').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/AJAX/WS.asmx/GetItems",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({"templateIds":currentTemplateIds ,"currentSection":currentContextSection,"currentPage":currentPageIndex,"itemPerPage":currentItemPerPage}),
dataProcess: false
}).done(function (data) {
test = data;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
});
});
try after removing, JSON.stringify from
data: JSON.stringify(arguments),

get selected item on autocomplete

Sorry about this answer, i found a lot of results but anything works on my code.
I want to get the selected item and call another function to work with this. The script is:
<script type="text/javascript">
$(document).ready(function() {
$("input#autoText").autocomplete({
source: function(request, response) {
$.ajax({
url: "UserControllerServlet?action=Autocompletar",
dataType: "json",
data: request,
success: function(data, textStatus, jqXHR) {
console.log(data);
var items = data;
response(items);
alert($("#autoText").val(ui.item.id));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
}
});
});
</script>
The alert not works, and i try to use select and nothing.
Thx.
Use the select event
$(document).ready(function () {
$("input#autoText").autocomplete({
source: function (request, response) {
$.ajax({
url: "UserControllerServlet?action=Autocompletar",
dataType: "json",
data: request,
success: function (data, textStatus, jqXHR) {
console.log(data);
var items = data;
response(items);
alert($("#autoText").val(ui.item.id));
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
},
select: function (e, ui) {
console.log('s', ui.item);
//here ui.item will refer to the selected object
}
});
});
Demo: Fiddle
Instead of
alert($("#autoText").val(ui.item.id));
use
$("#autoText").data("autocomplete").selectedItem
This will allow you to access the selected item as an object.

Unable to access json data retrieved from php page using jquery $.ajax

How to access this json data in JavaScript.
when I alert it the result is undefined
Here is jQuery code
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Here is the problem
alert(data[0]['Result']);
}
});
This is PHP code
$data=array($no);
for($i=0;($i<$no && ($row=mysql_fetch_array($result)));$i++)
{
$data[$i]=array();
$data[$i]['Result'] = $row['Result'];
$data[$i]['TestCode'] = $row['TestCode'];
$data[$i]['TestStatus'] = $row['TestStatus'];
$data[$i]['SrNo'] = $row['SrNo'];
}
$data1=json_encode($data);
echo $data1;
exit;
I have tested the PHP file independently,
The json data is output as follows:
[{"Result":"1","TestCode":"22","TestStatus":"0","SrNo":"1"},{"Result":"1","TestCode":"23","TestStatus":"1","SrNo":"2"}]
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = jQuery.parseJSON(data)
alert(data[0]['Result']);
}
});
You can access to your data by doing
data[0].Result
It's an Object, not an array.
so data[0]['Result'] it's not the proper way
EDIT:
Since you have more objects, you have to do a loop this way:
$.each(data, function(key, val){
console.log(val.Result);
console.log(val.TestCode);
//...
});
When you see something like
{
"foo":"bar",
...
}
you can access to it the same way as above:
name_of_the_object.foo
that will have the value "bar"
Try to add parse JSON. I have added. Now it may be work.
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = $.parseJSON(data)
alert(data[0]['Result']);
}
});

Where I should place return statement

I use Backbone.js and jQuery 1.7 in my application and I have some problems in building collection. In collection I have the method, which should return some object. I do "return" in $.ajax(...) success() function.
In this case i receive "undefined" instead of expected object. I understand, that the problem is in the "return" - it make success() function return some value. But I need getDomainZones() method do a return. How can I do it?
window.DmnList = Backbone.Collection.extend({
model: DmnItem,
localStorage: new Store("hosting.WhoIs"),
destroyAll: function (options) {
while (this.models.length > 0) {
this.models[0].destroy(options);
}
},
getDomainZones: function(){
$.ajax({
url: 'http://hosting/rest/getDomains',
type: 'GET',
dataType: 'json',
cache: 'false',
timeout: 5000,
success: function(data) {
console.log(data);
return data;//problem here
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[getDomainZones]: " + textStatus);
console.log(jqXHR);
},
});
}
});
"Where I should place return statement"
Nowhere. You can't return the result of an asynchronous AJAX request.
Any code that relies on the data, must be called inside the success callback.
One possibility is to have your getDomainZones method receive a function that will be called when the response is received.
getDomainZones: function( callback ){
$.ajax({
url: 'http://hosting/rest/getDomains',
type: 'GET',
dataType: 'json',
cache: 'false',
timeout: 5000,
// success: callback, // alternative if there's no other work to do.
success: function(data) {
console.log(data);
callback( data ); // invoke the function received
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[getDomainZones]: " + textStatus);
console.log(jqXHR);
},
});
}
So then you'd pass a function to getDomainZones, and when the response is received, getDomainZones will invoke the function you passed, passing it the data.
getDomainZones( function( d ) {
// do something with the data
console.log( d );
});

Categories