jQuery and Rails ajax request and response - javascript

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!");
}
});

Related

Change 'src' attribute of images by AJAX response

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.

Ajax Request: Json Data Not Being Passed to Controller

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

ASP.Net MVC Resource Cannot be found error after upload on server

I have used ajax calling to get details from database this ajax calling works fine in local but after uploading on server I always get error Resource Cannot be found I have tried many things depend on the solution on the web but no one succeed I even use to create details view and works fine on local but the same error after upload
i have tried
url: '/MobileS/Get/' + MobileSID
url: '~/MobileS/Get/' + MobileSID
url: '../MobileS/Get/' + MobileSID
and also i have tried despite its wrong but i think it may be work
url: '../../MobileS/Get/' + MobileSID
url: '~/~/MobileS/Get/' + MobileSID
url: 'MobileS/Get/' + MobileSID
this is the main function
function getbyID(MobileSID) {
$('#Name').css('border-color', 'lightgrey');
$.ajax({
url: '/MobileS/Get/' + MobileSID,
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
async: true,
processData: false,
cache: false,
success: function (data) {
//var obj = JSON.parse(data)
// alert(data);
$('#Name').val(data.MobileSerial);
$('#myModal').modal('show');
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}

AJAX request sometimes out of order

I'm having trouble with POST and GET request. On my server side right up until the moment before I send I have what I expect but then on my client side I get things out of order. For example these two should be in the reverse order I have here:
Sending from server{"grid":["","","","","","","","",""],"winner":""}
Received at server: {"grid":["X","","","","","","","",""],"winner":""}
function sendData(json) {
$.ajax({
type: "POST",
url: "/ttt",
data: json,
dataType: "json",
success: receiveData()
});
}
function receiveData() {
var response = $.ajax({
type: "GET",
url: "/ttt",
dataType: "json",
success: function(){
grid = response.responseJSON;
console.log("Receved at client: " + JSON.stringify(grid));
}
});
console.log("Also after receiving " + JSON.stringify(grid));
}
gives me:
Also after receiving {"grid":["X","","","","","","","",""],"winner":""}
Receved at client: {"grid":["X","O","","","","","","",""],"winner":""}
I think this may two different problems. One for getting things out of order and another for why my grid doesnt reflect the changes after my success clause function in my GET request.
You're making a common mistake. You need to use a function reference without the parens here for receiveData. Change this:
function sendData(json) {
$.ajax({
type: "POST",
url: "/ttt",
data: json,
dataType: "json",
success: receiveData()
});
}
to this:
function sendData(json) {
$.ajax({
type: "POST",
url: "/ttt",
data: json,
dataType: "json",
success: receiveData // no parens here
});
}
When you include the parens, it calls the function IMMEDIATELY and puts the return value from the function as the success handler and thus you see them run out of order. You want to pass a function reference to it can be called later. A function reference is the function's name without the parens.
It also appears like you have another mistake in receiveData(). You are using the wrong thing for the response. The response is not returns from $.ajax(). The response is passed to the success handler.
I don't know exactly what your response is supposed to look like, but change this:
function receiveData() {
var response = $.ajax({
type: "GET",
url: "/ttt",
dataType: "json",
success: function(){
grid = response.responseJSON;
console.log("Receved at client: " + JSON.stringify(grid));
}
});
console.log("Also after receiving " + JSON.stringify(grid));
}
to something like this:
function receiveData() {
$.ajax({
type: "GET",
url: "/ttt",
dataType: "json",
success: function(response){
grid = response.responseJSON;
console.log("Received at client: " + JSON.stringify(grid));
console.log("Also after receiving " + JSON.stringify(grid));
}
});
}
And, because your ajax calls are asynchronous, you also had this statement console.log("Also after receiving " + JSON.stringify(grid)); in the wrong place. If you want to see the results of the grid after you've modified it, then you have to put that inside the success handler.
Summary of Fixes
Change success: receiveData() to success: receiveData.
Use response as it is passed to the success handler.
Put console.log() to see final results inside the success handler.
It appears that you may not fully understand how ajax calls are asynchronous and what that really means for your programming. I'd suggest doing some searching and reading on that topic. Learning that now will save you a lot of agony as you develop.

Show Ajax error response as a webpage

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);

Categories