Setting string in javascript function in ASP.NET MVC give NullReferenceException - javascript

Inside my MVC view I have javascript that is executed by a button click. I'm trying to set a string to a random set of characters which I can get to work fine but when I try and set that string to 'randomchars' string inside the javascript I get a NullReferenceException when I try and run the view.
Below is the code snippet, the CreateRString is where the model parameter (RString) is set to the random string.
<script type="text/javascript">
function showAndroidToast(toast) {
var url = '#Url.Action("CreateRString", "Functions")';
$.ajax({ url: url, success: function (response) { window.location.href = response.Url; }, type: 'POST', dataType: 'json' });
var randomchars = '#(Model.RString)';
}
</script>
Is the syntax correct? I'm not too sure why it's getting the NULL.

The javascript is executed after the page been delivered to the client (i.e. web browser). Your razor code here is executed on the server before the page is sent to the client. Therefore, the ajax method will execute after you try to access Model.RString
To fix this you can either call CreateRString on the server, or you can set randomchars by using the response in the success callback.
To explain option 2 a bit further. You could do something like this:
//Action Method that returns data which includes your random chars
public JsonResult CreateRString()
{
var myRandomChars = "ABCDEF";
return new JsonResult() { Data = new { RandomChars = myRandomChars } };
}
//The ajax request will receive json created in the CreateRString method which
//contains the RandomChars
$.ajax({ url: url, success: function (response) {
var randomchars = response.Data.RandomChars;
window.location.href = response.Url;
}, type: 'POST', dataType: 'json' });
More specifically, the razor calls #Url.Action("CreateRString", "Functions") and #(Model.RString) execute first on the server.
Then showAndroidToast executes in the client's browser when you call it.

Related

How to send a Javacript variable to an ASP.NET controller using Ajax?

So I have created a method on another page of my web app that uses $.Ajax in the Javascript section of my page to retrieve data being returned from a function in my ASP.NET controller for that page/view, and now I am trying to create a new section that will take a parameter being given to the ASP.NET controller from the Javascript script and it will return some data based on the parameter being given.
Here is my Ajax query so far:
function testFunction(){
let selectedDateJS = getSelectedDate()
let customGraphData = $.ajax({
type: "POST",
url: '#Url.Action("GetCustomGraphData", "Graph")',
success: console.log("success: "+success),
})
}
And then here is my controller function in ASP.NET:
public async Task<JsonResult> GetCustomGraphData(string selectedDate)
{
DateTime selectedDateDT = Convert.ToDateTime(selectedDate);
// if selectedDate is NOT a working day:
if (!bh.IsWorkingDay(selectedDateDT)){
// Do something if the date being selected on the form IS NOT a working day.
return Json(null);
}
else// else, if it IS a working day :
{
CustomGraphVM selectedDatedata = await GetCustomData(selectedDateDT);
return Json(selectedDatedata);
}
}
I tried using a data: 'myDate', addition to the Ajax query under the url part but it didn't send anything (null was returned on the string selectedDate parameter of my ASP.NET controller function, but it was returned as null.
Also if it makes it easier, I am parsing a date to the controller from Ajax, and the date is in the format 'yyyy-mm-dd'.
The reason why I am doing this in $.Ajax and with Javascript as opposed to doing it with the ASP.NET is because I am trying to make a dynamic update on the view - and this worked great previously with my GET request that just returned a fixed value from the controller.
If you are passing data via AJAX then you want to match the name you gave your parameter.
function testFunction(){
let selectedDateJS = getSelectedDate();
let customGraphData = $.ajax({
type: "POST",
url: '#Url.Action("GetCustomGraphData", "Graph")',
data: {
selectedDate: selectedDateJs
}
success: console.log("success: "+success),
});
}

A part of AJAX response storing in PHP variable

I need to store a piece of data, into PHP variable, which is received through AJAX response in an input box. How can I do this?
<script type="text/javascript">
$(document).ready(function() {
$("#user_id").change(function() {
var id = $(this).val();
var dataString = 'user_id='+ id;
$.ajax({
type: "POST",
url: "wmat_details.php",
data: dataString,
cache: false,
success: function(result) {
var data = result.split(",");
$('#name').val(data[0]);
$('#email').val(data[1]);
$('#ref_id').val(data[2]);
$('#candidature_start').val(data[3]);
$('#candidature_end').val(data[4]);
$('#default_attempts').val(data[5]);
$('#existing_complimentary').val(data[6]);
$('#wmat_start').val(data[9]);
$('#wmat_end').val(data[10]);
$('#attempts_taken').val(data[11]);
}
});
});
});
</script>
As shown in above code, I want to store $('#attempts_taken').val(data[11]); this value to a PHP variable. Any insight is appreciated.
Unfortunately you can't.
PHP is server side while jQuery (JS) is client side. They are two separate layers of abstraction that interact only when the client call the server.
I don't have enough informations about what you need to do with data[11] but it seems that you have only one option: make a consecutive AJAX call to the php file that will manipulate data[11].
The consecutive AJAX call must be executed from inside the first call success callback; something like this:
success: function(result){
// Your on success logic
// ...
// Prepare the object to send to the server
var objData = {};
objData.attemptsTaken = data[11];
// Execute the second AJAX call to the server
$.ajax({
type: "POST",
url: "second_call_destination_file.php",
data: objData,
success: function(result){
// Do something on success
},
error: function(){
// Do something on error
},
complete: function(){
// Do something on complete (executed after success and error)
}
}
You cannot store ajax response into a php variable.
way 1 :
You can make another ajax call.
way 2 :
you can set session.

Ajax url is undefined

I'm making a function to get a xml file and edit it. I've never done that before so I searched a good way to get an xml file. I decided to use ajax, but the file is never returned because the url is undefined.
EDIT :
I edited the code and made the treatment in the success function. Now there is no problem with this file.
Here is the update of the ajax part :
$.ajax({
type: 'GET',
url: 'allrtp.xml',
dataType: 'xml',
success: function(xml) {
//file = $.parseXML(xml);
// Editing the file to have the good dates
$(xml).find('StartDateTime').text(start);
$(xml).find('EndDateTime').text(end);
var strFile;
if (window.ActiveXObject) {
strFile = xml.xml;
} else {
strFile = (new XMLSerializer()).serializeToString(xml);
}
var encoded64 = Base64.encode(strFile); // Encoded in base64
var encodeURL = encodeURIComponent(encoded64); // Encoded URL
var AR = urlAR + encodeURL; // The URL to open
window.open(AR, '_blank');
}
})
Now all is working well about the xml file, I have a little problem with the window.open, which open my url but with %31 at the beggining, but it's another problem.
Thank you for your help !
file is undefined because you are declaring it inside a ajax success function
function openRecords(start, end) {
// Extraction of the xml file
var file;
$.ajax({
type: 'GET',
url: 'allrtp.xml',
dataType: 'xml',
success: function(xml) {
file = $.parseXML(xml);
},
error: function(ex) {
console.log(ex);
}
})
// Test
var start = '2016-02-15T12:57:00+01:00';
var end = '2019-02-16T13:57:00+01:00';
setTimeout(function(){
// Editing the file to have the good dates
file.find('StartDateTime').text(start);
file.find('EndDateTime').text(end);},1500);
}
Add an error callback:
error: function (ex) {}
Many things can be happening, you will get more info with the error callback. Probably you are querying an incorrect url. Do not trust that undefined upon url, see what returns your jquery ajax function. Maybe you should be querying something like '\files\xxx.xml'.
can you give me a picture of Network in your broswer? I want to know the URL is send or not:
1. F12 open your console
2. select the Network tab
3. refresh the broswer
4. check the request is send or not

AJAX call using IIFE? Can't seem to get .done to work the same as a regular function

I currently have an AJAX call out to a PHP file that works, that is the following:
//Load map from database
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
dataType: 'JSON',
});
};
getMap().done(function(r) {
if (r) {
loadedMap(JSON.parse(r.mapArray), JSON.parse(r.mapProperties)); //call loadedMap(r) if loading a map from DB
} else {
console.log("No data");
}
}).fail(function(x) {
console.log("error");
});
That works within a single javascript file that successfully passes r.mapArray and r.mapProperties to my main loadedMap function.
I'm trying to learn about the IIFE Javascript Module model, and split my work up into separate files.
So, I currently have main.js:
(function() {
// let's get our map
var gameMap = mapGen.getMap().done();
console.log(gameMap);
})();
and mapGen.js:
var mapGen = function() {
return {
getMap: function() {
return $.ajax({
url: "getMap.php",
type: "POST",
dataType: 'JSON',
});
}
};
}()
If I console.log(gameMap), I see the responseText JSON object with my data. I just can't seem to access it. console.log(gameMap.responseText) is undefined. as is gameMap.responseJSON (though I see both of them in the console).
Looking the code over it looks as the the separation of the files was not the issue and that looks to be implemented correctly. The issue is with how you are handling the AJAX request. The function mapGen.getMap() actually returns a jqXHR Object as opposed to the response that you are trying to access.
Just as you had in your previous file, you will need handle the response of your request.
(function() {
// let's get our map request
var gameMap = mapGen.getMap();
gameMap.done(function(r){ ... }).
fail(function(x){ ... });
})();
You will be able to access the response data you are looking for within the done() function.

What am i doing wrong with this dynamic query?

i've never used AJAX or JQuery before, but here's my attempt at dynamic loading(pulled from various examples here at stackoverflow)
this is the script i have in my view:(edited to comply with mayabelle's code.) doesn't throw either alert, and the breakpoint on DRequest never trips, but drequest produces results if called directly.
<script type="text/javascript">
$(document).ready(function () {
alert("testing123");
$response = DRequest;
alert("good at response");
$.ajax({
url: "request/drequest"
type: "GET",
dataType: "json",
success: function ($response) {
alert("I am an alert box2!");
// Do something with your response
var $tr = $('<tr>').append(
$('<td>').text($response.NeededByDate),
$('<td>').text($response.RequestedBy),
$('<td>').text($response.Username),
$('<td>').text($response.RequestedPCID),
$('<td>').text($response.RequestType_ID),
$('<td>').text($response.Division_ID),
$('<td>').text($response.ReqTypeIcon)
).appendTo('#requestTable');
console.log($tr.wrap('<p>').html());
}
});
setInterval(function () {
var url = '#';
$('body').load(url);
}, 300000);
});
</script>
is supposed to dynamically append one row at a time (until there are no more rows to add) from the DRequest JsonResult (this is producing results when called directly by way of the addressbar). this should reload the whole page every 5 minutes(300000 seconds).
the JsonResult looks like this
Public Function DRequest() As JsonResult
Dim Reqs = _db.dRequestGetAll
Return Json(Reqs, JsonRequestBehavior.AllowGet)
End Function
where "_db.dRequestGetAll" returns a collection of dRequest rows like so:
Public Function dRequestGetAll() As IEnumerable(Of DRequest)
Return From r In _PITcontext.Requests Where r.CompletedDate Is Nothing Select r
End Function
so. what did i miss?
EDIT: i replaced the javascript from the original post with the most current version since comments can't handle more than 600 characters.
Try like this:
$(document).ready(function () {
$.ajax({
url: url to your controller action,
type: "GET",
dataType: "json",
success: function (response) {
// Do something with your response
}
});
}
Also, in your code above you are calling your variable $response but then in your each loop you are trying to access response (no $ prefix).
I think you should be using $.map() instead of $.each(). It returns an array of your elements. Differences are discussed here.

Categories