from an Ajax call that was build up like this:
function GetData() {
$.ajax({
type: "POST",
url: "#Model.RouteForAjaxLastValue",//"/RCharts/AjaxMethod",//
data: "{Id: " + lastID+ "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
})
I sometimes get responses like this:
I can see that this is meant to be displayed as a webpage since its an entire page html formatted.
But is there a way to display that directly as a new page mabye?
It cuts of the rest of the message in the alert before I can even get to read what the error may be...
Use $("html").html(response.responseText); inside your success function .
success : function(response){
$("html").html(response.responseText);
}
You should probably use console.log()
but this should append it to the body:
$('body').append(response.responseText);
Related
I'm trying to change src attribute of image by ajax request,
$.ajax({
url: "/l/"+id1,
type: "get",
dataType: "json",
success: function (data) {
$data = $(data);
$("#like" + id1).attr("src",$data");
}
});
Response is something like /uploads/like.png
Without dataType: "json" , I receive error:
Syntax error, unrecognized expression: /uploads/like.png
(So Ajax works and response is received) , after adding dataType:"json" error gone but nothing more happens.
HTML part (produced by server):
(every image has different id1, e.q id1=33 , so response goes to each selected image.)
<img id="like33" src="/uploads/default.png" />
You could do something like this:
$.ajax({
url: "/l/"+id1,
type: "get",
dataType: "json",
success: function (data) {
$("#like" + id1).attr("src", data);
}
});
If you are receiving the string /uploads/like.png in the ajax response, you can just pass it into the attr() method.
Hope it helps.
I'm building a program that searches documents in ASP.NET Core. I'm passing the search data from a text box to the controller through an Ajax request but the controller isn't receiving the string.
I've tried changing how the ajaxData field is defined, adding quotations around 'search' and even turning the whole thing into a string but I can't get it to pass to the controller.
This is the code for the request:
ajaxData = {search: $("#textSearchBox").val()}
console.log(ajaxData);
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: ajaxData,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});
And this is the top of the Controller's GetDocuments function:
[Route("GetDocuments")]
public async Task<IActionResult> GetDocuments(string search)
{
No error messages anywhere. The Console shows an Object that contains 'search: "Test"' but when I hit the breakpoint in GetDocuments 'search' is null.
I think is more elegant way to use GET in this case then you should change your code to
var ajaxData = $("#textSearchBox").val();
url: "#Url.Action("GetDocuments", "DocumentSearchApi")"?search=ajaxData
and remove data: ajaxData
Because you want to get something from the search. Using the post is when you want to modify the data from API
you need use JSON.stringify() when sending data to a web server, the data has to be a string not a object
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: JSON.stringify(ajaxData),
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});
In this SO post I learned how to get a return value from an AJAX call:
function CallIsDataReady(input) {
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
else {
//Continue as data is ready
callUpdateGrid(input);
}
}
});
}
$(document).ready(function () {
var input = { requestGUID: "<%=guid %>" };
CallIsDataReady(input);
});
This function calls its web service wich does return true. The problem is that inside the following callUpdateGrid, the logging shows that that web service method is not getting called from the $.ajax call:
function callUpdateGrid(input) {
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
var mtv = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
console.log(data);
mtv.set_dataSource(data.d.Data);
mtv.dataBind();
}
});
}
Anyone know what is wrong?
It is always a good idea to include an error handler function as one of the options passed to $.ajax. For example, add this code after your success functions:
,
error: function(jqXHR, textStatus, errThrown) {
console.log("AJAX call failed");
console.log(errThrown);
}
That will log at least a bit of information if the $.ajax call doesn't succeed.
EDIT
According to your comment, this logs
SyntaxError: Invalid character
And in fact, I now see that you are giving a plain JavaScript object as the data option passed to $.ajax, but indicating that it is a JSON object in the dataType field. You need to actually convert the input object into JSON yourself, like so:
data: JSON.stringify(input),
dataType: 'json',
Alternatively, you could simply format input as a JSON object in first place, like so:
var input = { "requestGUID": "<%=guid %>" };
The quotes around the field name requestGUID are sufficient, in this case, to give you a JSON object.
Trying the basic stuff,
request with data and response with data and print it with jQuery and Rails
This is the front code.
$("#internal_btn").click(function() {
//window.alert("clicked internal btn!");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/room/test",
//data: "{'data1':'" + value1+ "', 'data2':'" + value2+ "', 'data3':'" + value3+ "'}",
data: {name:"ravi",age:"31"},
dataType: "json",
success: function (result) {
//do somthing here
window.alert("success!!");
},
error: function (){
window.alert("something wrong!");
}
});
});
in here, if the user clicks internal_btn this event happens and goes to the servide
room/test action.
ok this is fine. But I'm not sure how to send the data.
If i run this, i have an error like this.
MultiJson::LoadError
795: unexpected token at 'name=ravi&age=31'
Can i know what the problem is?
Also, is there are good example with this request and response with json format?
I googled a lot, but not satisfied with the result :(
Try to use stringify your data or use GET method like,
data : JSON.stringify({name:"ravi",age:"31"}),
Full Code,
$.ajax({
type: "POST",// GET in place of POST
contentType: "application/json; charset=utf-8",
url: "/room/test",
data : JSON.stringify({name:"ravi",age:"31"}),
dataType: "json",
success: function (result) {
//do somthing here
window.alert("success!!");
},
error: function (){
window.alert("something wrong!");
}
});
I have a mobile app using mostly JQuery Mobile. I have an ajax function using POST and I can't seem to get anything to effect the UI when I fire the click event. I tried setting
$('#cover').show();
as the very first thing in the function then I do some basic things like document.getElementById('user') etc to set some variables and check input, but as long as the ajax function is there it won't show the div or even the spinner from JQ Mobile. Unless I debug and step through the code then the spinner and div show up fine. I tried setTimeout and putting it in the beforeSend area of the ajax call. Everything works fine otherwise. It seemed to work a little better with GET I'm not sure if that has anything to do with it or not.
$.ajax({
cache: false,
type: "POST",
async: false,
url: urlString,
data: jsonstring,
contentType: "application/json",
dataType: "json",
success: function (data) {
JSONobj = JSON.parse(data);
},
beforeSend: function(xhr){
//console.log('BeforeSend');
},
complete: function (xhr) {
//console.log('Complete');
},
error: function (xhr, status, error) {
console.log(error);
}
});
You could use the Ajax Global handlers to handle this:
$(document).
.ajaxStart(function(){
$('#cover').show();
})
.ajaxStop(function(){
$('#cover').hide();
});
This way you don't have to worry about showing/hiding the overlay on individual Ajax calls.
Try this
$("#someButton").click(function(e){
e.preventDefault() //if you want to prevent default action
$('#cover').fadeIn(100,function(){
$.ajax({
url: "someurl",
data: "Somedata",
contentType: "application/json",
dataType: "json",
},
success: function (data) {
JSONobj = JSON.parse(data);
$('#cover').fadeOut(100);
},
complete: function (xhr) {
$('#cover').fadeOut(100);
}
});
});
});