Form post warning message after upgrading jquery - javascript

I have upgraded to jquery 1.10.2. I am using jquery migrate and I am having the warning message "jQuery.parseJSON requires a valid JSON string"
I have not understood how I can correct that. Can anyone help me out with the best solution of how I can remove the warning message
The javascript is as follows:
function Search() {
$.ajax({
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "html",
url: "#Url.Action("Search")",
data: JSON.stringify({myModel: $("#DateFrom").val()}),
success: function (data)
{
$("#NewDiv").html(data);
},
error: function (request, status, error)
{
DisplayError(ParseErrorFromResponse(request.responseText, "Unknown error"), true);
}
});
}
In the Controller:
public PartialViewResult Search(myModel myModel)
{
return PartialView("SearchResult", myModel);
}
ParseErrorFromResponse:
Function ParseErrorFromResponse(responseText, defaultError)
{
var text = responseText.replace("<title>", "TitleStart");
var startIndex = text.indexOf("TitleStart");
var endIndex = text.indexOf("TitleEnd");
return (startIndex == -1 || endIndex == -1) ? defaultError : text.substring(startIndex + 10, endIndex);
}

You need to send your data as JSON.
Where you have data: $("#DateFrom").val(), replace it with data: JSON.stringify({$("#DateFrom").val()}).
EDIT: You may need to send it as JSON.stringify({(myModel: $("#DateFrom").val()}).

The error may be related to "" or false values that used to convert to null in versions of jQuery prior to 1.9.0 per THIS PAGE
Here it the relevant excerpt including the suggested solution:
JQMIGRATE: jQuery.parseJSON requires a valid JSON string
Cause: Before jQuery 1.9.0, the $.parseJSON() method allowed some
invalid JSON strings and returned null as a result without throwing an
error. This put it at odds with the JSON.parse() method. The two
methods are aligned as of 1.9.0 and values such as an empty string are
properly not considered valid by $.parseJSON().
Solution: If you want to consider values such as "" or false
successful and treat them as null, check for them before calling
$.parseJSON(). Since falsy values such as an empty string were
previously returned as a null without complaint, this code will
suffice in most cases:
var json = $.parseJSON(jsonString || "null");
If your own code is not
calling $.parseJSON() directly, it is probably using AJAX to retrieve
a JSON value from a server that is returning an empty string in the
content body rather than a valid JSON response such as null or {}. If
it isn't possible to correct the invalid JSON in the server response,
you can retrieve the response as text:
$.ajax({
url: "...",
dataType: "text",
success: function( text ) {
var json = text? $.parseJSON(text) : null;
...
}
});

Remove content-type attribute and do like this:
function Search() {
$.ajax({
cache: false,
url: "#Url.Action("Search","ControllerName")",
dataType:"html",
data:
{
myModel: $("#DateFrom").val()
},
success: function (data)
{
$("#NewDiv").html(data);
},
error: function (request, status, error)
{
DisplayError(ParseErrorFromResponse(request.responseText, "Unknown error"), true);
}
});
}
and in action:
public PartialViewResult Search(string myModel)
{
return PartialView("SearchResult", myModel);
}

I think it's because you're missing double quotes around key myModel in line
...
data: JSON.stringify({myModel: $("#DateFrom").val()},
...
and not because of jquery version upgrade.try using
data: JSON.stringify({"myModel": $("#DateFrom").val()},

Try like this.. You have to return Json as result from your Search().
public JsonResult Search(myModel myModel)
{
return Json(result);
}
and also in you Script, try like this..
$.ajax({
type:"POST"
cache: false,
contentType: "application/json; charset=utf-8",
url: "#Url.Action("Search","ControllerName")",
dataType: "json",
data: JSON.stringify({"myModel": $("#DateFrom").val()}),
success: function (data)
{
$("#NewDiv").html(data);
}
});
Also check $("#DateFrom").val() is having correct value and put an
alert(data)
in success and check the returned data.
I have updated the url.

Related

Parse a json reply from a jquery result in php

I have a simple search form which query an external server for result with jquery
$("#formsearch").on("submit", function (event) {
// everything looks good!
event.preventDefault();
submitFormSearch();
});
function submitFormSearch(){
// Initiate Variables With Form Content
var searchinput = $("#searchinput").val();
$.ajax({
type: "GET",
url: "https://external-server/api/",
headers: {"Authorization": "xxxxxxxxxxxxxx"},
data: "action=Search&query="+searchinput,
success:function(json){
console.log(json);
$.ajax({
type: "POST",
url:'search_func.php',
data: "func=parse&json="+json,
success:function(data) {
console.log(data);
$('#risultato_ricerca').html(data);
}
});
}
});
}
The first GET ajax works properly and I get correct data but trying to send this json data to my php script in post I can't get data.
This is the code in search_func.php
if(isset($_POST['func']) && !empty($_POST['func'])){
switch($_POST['func']){
case 'parse':
parse($_POST['json']);
break;
default:
break;
}
}
function parse($json) {
$obj = json_decode($json,true);
var_dump($obj);
}
... it displays NULL
Where I'm wrong ?
EDIT:
SOLVED
changing:
data: "func=parse&json="+json,
to:
data: { func: 'parse', json: JSON.stringify(json) },
json code is correctly passed to search_func.php
Changed function parse in php file to:
function parse($json) {
$data = json_decode(stripslashes($json),true);
print_r($data);
}
Thank you.
Is the javascript json variable correctly filled (i.e. what does your console show you?) Possible you must encode the json variable to a string before posting.
i.e: instead of data: "func=parse&json="+json, use data: "func=parse&json="+JSON.stringify(json),
See this: http://api.jquery.com/jquery.ajax/
The correct syntax is: data: { func: 'parse', json: my_json_here }
If this doesn't works is probably that you have to encode the JSON to a string (see JSON.stringify())

passing an array of int to MVC controller using ajax javascript

What am I doing wrong here?
I can successfully pass 4 bool params to a controller. Now I want to pass an array of int to my controller but it doesn't work - I've left my working code in the example(commented out) so you can see I'm not changing that much - I think I'm missing something simple (it is 17:44 afterall!!!). I can see the array is populated using the alert(rolesChecked); statement:
var rolesChecked = [];
$('[type="checkbox"].role-checkbox').each(function () {
if (this.checked)
{
rolesChecked.push($(this).val());
}
});
alert(rolesChecked);
//var administrator = $('#cbAdministrator').is(":checked");
//var manager = $('#cbManager').is(":checked");
//var technician = $('#cbTechnician').is(":checked");
//var transcriber = $('#cbTranscriber').is(":checked");
if (rolesChecked.count > 0){//administrator || manager || technician || transcriber) {
$.ajax({
url: '#Url.Action("GetFutureHolidays", "Employee")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: {
roleIdXXXs: rolesChecked
//includeAdministrator: administrator,
//includeManager: manager,
//includeTechnician: technician,
//includeTranscriber: transcriber
},
success: function (data) {
//do something...
}
});
}
Controller Action:
public string GetFutureHolidays(List<int> roleIdXXXs)//bool includeAdministrator, bool includeManager, bool includeTechnician, bool includeTranscriber)
{
//do something
}
with the old code, the controller action would be hit... with the array, it never gets hit... What am I missing here...
also, I think List<int> roleIdXXXs should be fine, but I also tried List<string>, int[] and string[] in case it isn't!!!
You need to add the traditional: true ajax option to post back an array to the collection
$.ajax({
url: '#Url.Action("GetFutureHolidays", "Employee")',
type: 'GET',
dataType: 'json',
cache: false,
data: { roleIdXXXs: rolesChecked },
traditional: true, // add this
success: function (data) {
}
});
Refer also the answer to this question for more detail on what the options does and the form data it generates.
In your if statement, instead of rolesChecked.count, use rolesChecked.length
You can't submit a list like this from Ajax, the quickest fix in the process you are using is to use serialization-desalinization process, you can send it as
roleIdXXXs: JSON.stringify(rolesChecked)
on Action:
public ActionResult GetFutureHolidays(string rolesChecked)
{
var test = new JavaScriptSerializer().Deserialize<List<int>>(rolesChecked);
}
You should use JSON.stringify() on you AJAX call lice this:
data: {
roleIdXXXs: JSON.stringify(rolesChecked)
//includeAdministrator: administrator,
//includeManager: manager,
//includeTechnician: technician,
//includeTranscriber: transcriber
}

jquery -ajax not check the boolean value from controller

i have a controller action which is return a boolean result to the jquery.
[HttpGet]
public ActionResult IsVoucherValid(string voucherCode)
{
bool result = false;
var voucher = new VoucherCode(voucherCode);
if(voucher.Status==0)
{
result = true;
}
return Json(result);
}
and call this controller using ajax code
$.ajax({
url: '/Account/IsVoucherValid?voucherCode=' + code,
type: 'Get',
contentType: 'application/json;',
success: function (data) {
alert("success");
if (data) {
//if result=true, want to work this
$("#person-data").css({ "display": "block" });
}
},
error:alert("error")
});
in the success of ajax the json result is true then want to work the css. but this is not working please help me.
result is a variable name that only exists in that action method. It will not be included in the JSON.
I'm pretty sure that your boolean value will be stored in data since you are only sending back a single value:
$.ajax({
url: '/Account/IsVoucherValid?voucherCode=' + code,
type: 'Get',
contentType: 'application/json;',
success: function (data) {
if (data) { //if result=true, want to work this
$("#person-data").css({ "display": "block" });
}
}
});
If in doubt, do console.log(data) to see what it contains. You should at least be doing minimal debugging before you bring the question to us.
Also, as #Stephen Muecke points out below, if you are retrieving this data with GET, you need to use:
return Json(result, JsonRequestBehavior.AllowGet);

Why we use data.d while get response from ajax json call?

I am using AJAX call from my Html page to call a method from my asmx.cs file, using below code:
<script type="text/javascript">
function ajaxCall() {
var UserName = $("#<%=lblUsername.ClientID %>").text();
$("#passwordAvailable").show();
$.ajax({
type: "POST",
url: 'webServiceDemo.asmx/CheckOldPassword',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ UserName: UserName }),
success: function (data) {
if (JSON.parse(data.d) != "success") // Why we need to use "data.d" ??
{
$("#passwordAvailable").attr("src", "App_Themes/NewTheme/images/deleteICN.gif");
$("#<%=txtOldPwd.ClientID %>").css({ 'border': '1px solid red' });
}
else {
$("#passwordAvailable").attr("src", "App_Themes/NewTheme/images/signoff.gif");
}
}
});
}
</script>
So my Question is why do we need to use data.d ? Why does all data is being stored in .d and what is .d?
Because when I use only data it's not giving me correct return values but when I used data.d it does.
please give me suggestions.
Server side code C#
[WebMethod]
public string CheckOldPassword(string UserName)
{
// code here
string sRtnValue = "success";
return sRtnValue;
}
so d is not property or variable but still I got value in .d
Thanks
C# 3.5 and above will serialize all JSON responses into a variable d.
When the server sends a JSON response it will have a signature similar to this:
{
"d" : {
"variable" : "value"
}
}
With a console.log(data) inside the ajax success function you'll see the responses data structure in the browser console.

JSON pass null value to MVC 4 controller in IE9

I got some problem while posting JSON data into MVC 4 controller.
Below method is working fine in Firefox but unfortunately failed in IE 9
The JavaScript :
var newCustomer = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '#Url.Content("~/CustomerHeader/CreateCustomerHeader")',
cache: false,
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(newCustomer),
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
and this is my controller :
public JsonResult CreateCustomerHeader(CustomerHeader record)
{
try
{
if (!ModelState.IsValid)
{
return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
}
RepositoryHeader.Update(record);
return Json(new { Result = "OK", Record = record});
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
the "data" variable as in public JsonResult CreateCustomerHeader(CustomerHeader **data**) is getting NULL but while using FireFox it holds the correct value.
UPDATE : New method trying using $.post
function CreateNewCustomer(newCustomer) {
$.post("/CustomerHeader/CreateCustomerHeader",
newCustomer,
function (response, status, jqxhr) {
console.log(response.toString())
});
}
Based off the bit that you've shown, this is a simplified variation that may work more consistently, using jQuery.post() (http://api.jquery.com/jQuery.post/):
var data = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.post({
'#Url.Action("CreateCustomerHeader", "CustomerHeader")',
data,
function(response, status, jqxhr){
// do something with the response data
}).success(function () {
$("#message").html("Success");
}).error(function () {
$("#message").html("Save failed");
});
$.post() uses $.ajax as it's base, but abstracts some of the details away. For instance, $.post calls are not cached, so you don't need to set the cache state (and setting it is ignored if you do). Using a simple JavaScript object lets jQuery decide how to serialize the POST variables; when using this format, I rarely have issues with the model binder not being able to properly bind to my .NET classes.
response is whatever you send back from the controller; in your case, a JSON object. status is a simple text value like success or error, and jqxhr is a jQuery XMLHttpRequest object, which you could use to get some more information about the request, but I rarely find a need for it.
first of all I would like to apologize #Tieson.T for not providing details on JavaScript section of the view. The problem is actually caused by $('#addCustomerHeaderModal').modal('hide') that occurred just after ajax call.
The full script :
try{ ..
var newCustomer =
{
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '/CustomerHeader/CreateCustomerHeader',
cache: false,
type: "POST",
dataType: "json",
data: JSON.stringify(newCustomer),
contentType: "application/json; charset=utf-8",
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
}
catch(Error) {
console.log(Error.toString());
}
//$('#addCustomerHeaderModal').modal('hide')//THIS is the part that causing controller cannot retrieve the data but happened only with IE!
I have commented $('#addCustomerHeaderModal').modal('hide') and now the value received by controller is no more NULL with IE. Don't know why modal-hide event behave like this with IE9.
Thanks for all the efforts in solving my problem guys :-)

Categories