Simple jQuery / Ajax error - ajax

I have this code:
var custID = 1;
$.ajax({
url: 'php/viewCustomer.php',
type: 'GET',
data: '{custID: ' + custID + '}',
dataType: 'json',
cache: false,
beforeSend: function () {
$('#display').append('<div id="loader"> Lodaing ... </div>');
},
complete: function () {
$('#loader').remove();
},
success: function (data) {
//do something
},
error: function () {
alert('could not process');
}
});
there is an error and alerts the error message could not process, so I tried to debug it like this:
var custID = 1;
$.ajax({
url: 'php/viewCustomer.php',
type: 'GET',
data: '{custID: ' + custID + '}',
dataType: 'json',
cache: false,
beforeSend: function () {
$('#display').append('<div id="loader"> Lodaing ... </div>');
},
complete: function () {
$('#loader').remove();
},
success: function (data) {
//do something
},
error: function (jqXHR) {
alert('Error: ' + jqXHR.status + jqXHR.statusText);
}
});
which outputs:
200 OK
so if it is ok, why on earth is it executing the error: function. Confused, please help.

Your data string is incorrectly formatted, if you are intending it to be a JSON object. There was a previous question about this: Jquery passing data to ajax function
Instead, try:
data: JSON.stringify({custID: custID}),
The format is (key):(variable). My previous answer have placed quotes around the variable, which is not necessary.

Related

Ajax - Parse oData Response

I have an ajax call that gets data from a REST api.
$.ajax({
url: "http://localhost:52139/odata/WEB_V_CIVIC_ADDRESS",
data: { enteredText: "'" + $('#addressTextField').val() + "'" },
type: "GET",
dataType: 'json',
ContentType: "application/json",
success: function (data) {
alert(JSON.stringify(data));
response($.map(data.accountaddressList, function (item) {
return {
item: item.civicaddress,
value: item.accountNumber,
label: item.civicaddress
}
}));
},
error: function (data, xml, errorThrown) {
alert('Error loading address list: ' + errorThrown);
}
});
The odata returned from that call looks like:
{
"#odata.context":"http://localhost:52139/odata/$metadata#WEB_V_CIVIC_ADDRESS/AValues.Classes.Entities.AccountAddress","value":[
{
"#odata.type":"#AValues.Classes.Entities.AccountAddress","accountNumber":88887,"rowNumber":0,"civicaddress":"123 Fake St"
},{
"#odata.type":"#AValues.Classes.Entities.AccountAddress","accountNumber":88888,"rowNumber":0,"civicaddress":"321 Faker St"
}
]
}
So the current code throws an 'Undefined' error on the line: response($.map(data.accountaddressList, function (item) {
How do I map the 'civicaddress' and 'accountNumber' from each value in the odata response to 'item'?
Thanks.
I got it, needed to change it to response($.map(data.value, function (item)

How to add a body to the ajax request of select 2?

I would like to mimic a post to a URL with the body type of plain text (such as "select * from table") using a Select2 box, but where do i define the body that I want to post?
$("#sales_ids").select2({
placeholder: "Select your Partners",
multiple: 'multiple',
ajax: {
url: 'http://www.google.com/,
dataType: 'json',
type: 'post',
multiple: 'multiple',
allowclear: 'true',
processResults: function p(data){
var mapped = $.map(data, function(obj) {
obj.text = obj.text || obj.name;
obj.id = obj.id || obj.salesId;
return obj;
})
return {
results: mapped
}
$.ajax({
url: 'URL',
type: 'POST',
dataType: 'json',
async: false,
// Data Goes Here
data: 'select * from table'
contentType: 'test/plain'
success: function (data, textStatus, xhr) {
// Success Code
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Database');
}
});

display values returned by json

I have simple question to display data on html page. Following code displays array of json data on screen. but, I want to display it by each element such as "url", "img_url" and so on.
could you please let me know who to do it ?
ajax code
var dataString = 'url=' + pathname + '&img_name=' + img_name + "&tag=" + tag;
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
//handleError();
alert("error");
} else {
var data = xhr.responseText;
$('#tt').html("<div id='message'></div>");
$('#message').html(data);
}
}
});
json return
{"cid":"14","url":"http:\/\/localhost\/","img_url":"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg","img_name":"mat_173317134c.jpg","html":"<div id=\"hotspot-19\" class=\"hs-wrap hs-loading\">\r\n<img src=\"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg\">\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"95\" data-y=\"64\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nasdf\r\n<\/div>\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"168\" data-y=\"53\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nrere\r\n<\/div>\r\n<\/div>\r\n","jscript":""}
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
success: function (data) {
for(var item in data){
console.info(item);//print key
console.info(data[item]);//print value
}
}
});
I hope this is what you need.

AJAX Internal server error

I couldnt find out what is the error.
<script type="text/javascript">
$(document).ready(function () {
$("#btnsumbit").click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: '{"username":"' + $("input#txtuser").val() + '","password":"' + $("input#txtpwd").val() + '"}',
url: 'http://localhost:53179/hdfcmobile/WebService.asmx/Login_Data',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success:
function (data, textStatus, XMLHttpRequest) {
var status = data.Status;
alert(data.d);
},
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
});
});
</script>
I am getting 500 internal server error.How to call this webservice.I have passes the method with the url.Thanks for any help...
First thing, the way you are sending is wrong, send it like this
data: {
"username": $("input#txtuser").val(),
"password": $("input#txtpwd").val()
}
Next make sure, url: http://localhost:53179/hdfcmobile/WebService.asmx/Login_Data is returning JSON output.

ajax jquery pass null value

I get null values in the controller when I process the request using jquery ajax
Controller
[HttpPost]
public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
{
var replacetext=string.Empty;
if (answers.Length>0)
replacetext = answers.Replace("\n", ",");
_service.UpdateAnswers(eventid, replacetext, controlid);
return PartialView("CustomizedQuestions");
}
Jquery - Ajax Code
var test = "{ answers: '" + $("#answerlist").val() + "', question: '" + title + "', controlid: '" + controlid + "', eventid: '" + eventid + "' }";
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/html; charset=utf-8',
context: $(this),
// data: "{ answers: '"+$("#answerlist").val()+"' ,question: '"+ title +"', controlid:'"+ controlid +"',eventid:'"+ eventid+"'}",
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
Your contentType is wrong. Why did you set it to application/html when you pass JSON? Try like this:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/json; charset=utf-8',
context: $(this),
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
or using application/x-www-form-urlencoded which is the default:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
context: $(this),
data: test,
success: function (result) {
$(this).dialog('close');
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});

Resources