Is it possible to make JqGrid send a JSON QueryString to server? - javascript

Is it possible to tell jqGrid to send all search options in JSON format ? Hence I won't have to reformat it on the backend side.

There is no direct function like that mentioned in the documentation, so you will probably have realize that manually in the beforeSubmit method of the jqGrid. I would spontaneously use jQuerys serializeArray method for the form and a JSON Serializer. Then you will have to submit the serialized Form via Ajax. Just make sure, that you return success : false, so that jqGrid doesn't submit the form.
beforeSubmit : function(postdata, formid) {
var formarray = $('#' + formid).serializeArray();
var httpbody = JSON.stringify(formarray);
// Send accordingly via AJAX
$.ajax(...);
// This looks kind of weird, but we don't want jqgrid to continue cause it was sent already
return { success : false, message : "Successffully saved" };
}
Doesn't seem like the nicest sollution though but the beforeSubmit Event is probably the only place to dig into it.

I don't know how helpful this will be, but I found that I can return true here as long as I set my editurl to '#' ....
beforeSubmit : function(postdata, formid) {
if (isValid) {
$.ajax({
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
url: "/RateIQ/Main.aspx/Accessorial/AccessorialDetailSave",
data: JSON.stringify(postdata),
dataType: "json"
});
}
return [isValid, ""];
}
and I've experienced no side effects so far...

Related

Node.js endpoint ampersand is getting appended when making an ajax call

I've the below code which I'm using to hit a node.js endpoint. However when it is getting hit, the endpoint URL appends an & to it like this,
http://localhost:3004/expenses/?q=&12/02/2014
Hence I'm not getting the desired result back.
Here is how my code looks like,
$('#myForm').on('submit', (e)=>{
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://localhost:3004/expenses/?q=',
processData: false,
data: $('#startDate').val(),
contentType: 'application/json',
success:(data, status)=>{
// alert(status);
},
error:()=>{
alert('problem');
}
})
})
Can someone shed some light?
The issue is most likely related to the processData: false telling jQuery to not format the data for the request, and the GET url already containing ? in it. Given that you are not giving the request json, I would suggest reducing your call to simplify the issue.
$.ajax({
type: 'GET',
url: 'http://localhost:3004/expenses/',
data: { q: $('#startDate').val() },
success:(data, status)=>{
// alert(status);
},
error:()=>{
alert('problem');
}
});
If you do not give the processData in the options, it will convert the data you give it to a query param for the request. Given that this is a GET request, it will generate the ?q=<value> for you. And as mentioned in the comments, you do not need contentType: application/json on the options as that is telling jQuery to put the content type on the request so the server knows you are sending it json in the body. Which you are not, :)

Equivalent code without the library

I used a tutorial to get the following ajax code. In the tutorial, they have the library jquery.form.js. Here is the code:
function onsuccess(response,status){
$("#onsuccessmsg").html(response);
alert(response);
}
$("#uploadform").on('change',function(){
var options={
url : $(this).attr("action"),
success : onsuccess
};
$(this).ajaxSubmit(options);
return false;
});
What if I don't want to have jquery.form.js implemented. What would be the equivalent code with normal ajax (without the library)?
Update
I tried the following code:
$("#uploadform").on('change',function(){
$.ajax({
url: $(this).attr("action"),
context: document.body,
success: function(){
$("#onsuccessmsg").html(response);
alert("asdf");
}
});
return false;
});
and it doesn't do anything now.
It would be something more like: (apologies for the formatting, I'm on my mobile)
$("#uploadform").on('submit',function(e){
e. preventDefault() ;
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response, status, jqxhr){
$("#onsuccessmsg").html(response);
alert("asdf");
}
});
return false;
});
The data var will need to be built up manually by you by running through the form fields. You may also want to check out jquery post, which is a shorthand way of writing the above.
You can use this previously answered question to get the form data that you need to pass in to the ajax data field:
How can I get form data with Javascript/jQuery?
It's also worth noting that if you are posting a file from your form, your form must have enctype="multipart/form-data".
When submitting your form using ajax you need to set contentType: false, processData: false. See this post for reference.
I have updated the code snippet above to reflect this.
If this has answered your question please mark it as the correct answer.

Ajax do not pass data to method using GET

I have a method which Is accesed using Get
[HttpGet]
[AdminAuthorization]
public ActionResult MakeReservation(ReservationModel m)
{
return PartialView(m);
}
here Ajax Code:
$.ajax({
url: "/DeviceUsage/MakeReservation",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({ data: Ids }),
error: function (data) {
alert("Dodanie nie powiodło się Jeden lub wiecej numerów seryjnych nie są unikalne " + data);
},
success: function (data) {
$('#ProperModal.modal-body').html(data);
$("#Modal").modal('show');
//if (data === "sukces") {
}
});
If I change method description and ajax type to POST function works. How should I modify this code to make it work wiht GET calls?
You need to use JsonRequestBehavior.AllowGet in your controller. For more information you could read this answer on SO
And I think it is good practise to return Json (not PartialView) in your action (for ajax). If you want to return PartialView, you could use this technique
You don't need to explictly tell the HttpGet, By Default, it takes it as HttpGet, but if you put HttpPost attribute, then it does not work on Get Requests.
Same is the case for Jquery ajax, if you don't tell it, its get or post request, it by default makes a get request to server
Remove contentType and dataType: 'json' (this indicates you are returning json, but your code returns a partial view). And Remove JSON.stringify as jQuery accept your JS object directly. Haven't tested it, but it should work.

JQuery Ajax function return

I've defined a file availability.php that return "yes" or "no", well i have a form that must check availability of a form before subscribe a user, and i do this using this ajax function, but the compare line seems not work ?
availability: function(element, value) {
$.ajax({
type: "GET",
url: "/tunnel/availability.php",
data: "username="+element,
dataType: "html",
success: function(data){
$("#response").html(data);
var $response = data;
if ($response == "yes")
alert("found");
}
});
}
Try this:
availability: function(element, value) {
$.ajax({
type: "GET",
url: "/tunnel/availability.php",
data: "username="+element,
success: function(data){
if (data == "yes"){
alert("found");
}
}
});
}
Why do you think it's not working? If you're expecting your function to check and return a value before a form is submitted, it is likely that the availability function is returning before the ajax check is performed, allowing your form to submit and nullifying the alert -- i.e., the page is already unloaded and the new request is being processed. If you want to use this to check availability before submitting a form you'll need to:
Return false from availability (or otherwise stop the form submission)
Do the form submission from the availability success function.
(maybe) Indicate that you're expecting a text response instead of html.
You can also simplify the check -- there's no need to put "data" in a variable before you check it. I'm also not sure why you are adding it to the page, but that could be reasonable. I'd also suggest a name change for the function (if you modify it to do this) and handling the form submission via AJAX -- if not, you can remove the handler and simply trigger a submit on the form.
submitIfAvailable: function(form, element, value) {
$.ajax({
type: "GET",
url: "/tunnel/availability.php",
data: "username="+element,
dataType: 'text', // I think it should work without this, but...
success: function(data){
if (data == "yes"){
$form = $(form);
$.post( $form.attr('action'), $form.serialize(), function(result) {
// process the result of form submission
});
}
}
});
return false;
}
I'm making some assumptions -- modify as appropriate if this doesn't fit in with how the availability function is used. The key thing to remember is that the function will return before the AJAX call completes and you can't use any return value from the function that comes from the AJAX call. This is true, at least, if you don't force the AJAX call to run synchronously by setting the option aSync to false.
You need to confirm what the availability page is actually returning.
Debug the callback using Firebug (or your favourite JS debugger) to see what sort of object is returned as data. You might find that your return value is wrapped, eg you might have to check data.value or something similar.

ASP.NET MVC submitting json array to controller as regular post request (nonajax)

All the examples of json I can find online only show how to submit json arrays w/ the jquery command $.ajax(). I'm submitting some data from a custom user control as a json array. I was wondering if it's possible to submit a json array as a regular post request to the server (like a normal form) so the browser renders the page returned.
Controller:
[JsonFilter(Param = "record", JsonDataType = typeof(TitleViewModel))]
public ActionResult SaveTitle(TitleViewModel record)
{
// save the title.
return RedirectToAction("Index", new { titleId = tid });
}
Javascript:
function SaveTitle() {
var titledata = GetData();
$.ajax({
url: "/Listing/SaveTitle",
type: "POST",
data: titledata,
contentType: "application/json; charset=utf-8",
});
}
Which is called from a save button. Everything works fine but the browser stays on the page after submitting. I was thinking of returning some kind of custom xml from the server and do javascript redirect but it seems like a very hacky way of doing things. Any help would be greatly appreciated.
This is an old question but this might be useful for anyone finding it --
You could return a JsonResult with your new titleId from the web page
public ActionResult SaveTitle(TitleViewModel record) {
string tId = //save the title
return Json(tId)
}
and then on your ajax request add a success function:
function SaveTitle() {
var titledata = GetData();
$.ajax({
url: "/Listing/SaveTitle",
type: "POST",
data: titledata,
contentType: "application/json; charset=utf-8",
success: function(data) { window.location = "/Listing/Index?titleId=" + data; }
});
}
That would redirect the page after a successful ajax request.
I just saw that you mentioned this at the end of your post but I think it is an easy and quick way of getting around the issue.
Phil Haack has a nice post discussing this scenario and shows the usage of a custom value provider instead of an action filter.
I don't understand why you would want to post Json if you're wanting to do a full page post. Why not just post normal form variables from the Html form element?

Categories