get selected item on autocomplete - javascript

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.

Related

Can't pass variable into ajax url in 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

Ajax Response throwing JavaScript Syntax Error

function fnValidatePCRHours(pcr, hoursEntered)
{
$.ajax({
type: "GET",
url : "/TMS/validatePCRHours.html?pcr="+pcr+"&hoursEntered="+hoursEntered,
cache: false,
success: function(data, textStatus, jqXHR)
{
alert(data);
return true;
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
return false;
}
});
return false;
}
As soon as i get response (IN) from server, i get script error. Can any one help me on this?

do something at unsuccessful jquery ajax request

My ajax request is hitting an api with rate limits.
$.ajax({
url:"https://api.themoviedb.org/xxx",
crossDomain: true,
dataType: "jsonp",
dataObj : index,
success: function (response, textStatus, xhr) {
console.log('success');
}
,error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
}
});
I would like to know when I hit the rate limit.
But for the requests showing this in the console :
Failed to load resource: the server responded with a status of 429 (OK)
I don't see 'success' or 'error'.
It's like success and error are not executed.
Is there a way to popup and alert e.g. ?
I tried complete but it does not work either.
Thank you
I could not find documentation for dataObj but removing it seemed to make the query run properly.
If you get rid of it the error callback gets executed and you will be able to see error in the console.
$.ajax({
url:"https://api.themoviedb.org/xxx",
crossDomain: true,
dataType: "jsonp",
success: function (response, textStatus, xhr) {
console.log('success');
}
,error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
}
});
edit:
turns out what you actually want to change is the datatype. Unless you are explicitly also passing a callback you should tell jQuery that you are getting json and not jsonp back.
$.ajax({
url:"https://api.themoviedb.org/xxx",
crossDomain: true,
dataType: "json",
dataObj: index,
success: function (response, textStatus, xhr) {
console.log('success');
}
,error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
}
});
Try using the jQuery statusCode object in the settings, like this:
$.ajax({
url:"https://api.themoviedb.org/xxx",
crossDomain: true,
dataType: "jsonp",
dataObj : index,
success: function (response, textStatus, xhr) {
console.log('success');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
},
statusCode: {
429: function() {
alert( "Exceeded request limit." );
}
}
});

How to work with Google Suggest queries using jQuery

I am trying to work with the Google API for suggest queries. But I am getting an error.
Here is my code:
$.ajax({
url:'http://suggestqueries.google.com/complete/search?client=chrome&q=sheikh+hasina',
type:"GET",
dataType: 'jsonp',
jsonp:function (data) {
console.log('yes');
},
async:'true',
success:function (data) {
console.log('yes');
},
error: function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
Assuming that you're trying to get JSONP data from a URL, try this instead.
$.ajax({
url: 'http://suggestqueries.google.com/complete/search?client=chrome&q=sheikh+hasina',
type: 'GET',
dataType: 'jsonp',
success: function (data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});

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']);
}
});

Categories