Receiving json via ajax asp.net - javascript

My variable data in function ShowFavorits is undefined even do that my ajax call do return a json string.
<script type="text/javascript">
$(document).ready(function () {
ShowFavorits();
function AjaxGet() {
var param = "{'_userID': '1337'}";
$.ajax({
type: "POST",
url: "/webservices/MinSide.asmx/GetFavorits",
data: param,
contentType: "application/json;",
dataType: "json",
success: function (data) {
if (data.hasOwnProperty("d")) {
return (data.d);
}
},
error: function (data) {
//error
}
});
}
function ShowFavorits() {
var data = AjaxGet();
$("#addedList").html(
$("#addedTemplate").render(data)
);
}
});
[WebMethod]
public string GetFavorits(string _userID)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.MaxJsonLength = int.MaxValue;
string JsonData = string.Empty;
var db = new ModelDataContext();
var list = db.table.Where(x => x.userID == _userID).OrderBy(x=> x.TimePin).ToList();
JsonData = jss.Serialize(list);
return (JsonData);
}
Why cant i return the result from my ajax?
Hope someone can help me, have been stuck for hours now debugging this.
Thanks in advance.

The call to $.ajax in AjaxGet is asynchronous: the function returns undefined because the ajax call hasn't finished.
You should move the call to ShowFavourits into the ajax success function so that it executes once the ajax call is complete/successful
<script type="text/javascript">
$(document).ready(function () {
// Kick-off the ajax request
AjaxGet();
function AjaxGet() {
var param = {_userID: '1337'};
$.ajax({
type: "POST",
url: "/webservices/MinSide.asmx/GetFavorits",
data: param,
dataType: "json",
success: function (data) {
if (data.hasOwnProperty("d")) {
ShowFavorits(data.d); // Pass the data to the template
}
}
});
}
function ShowFavorits(data) {
$("#addedList").html(
$("#addedTemplate").render(data)
);
}
});

Related

Calling method in PHP file from separate JavaScript file

I have a javascript file from which I am trying to make a ajax call to execute method of a different php file.
Javascript file - a.js
function update() {
$.ajax({
url:"abcd.php",
type: "POST",
dataType: 'json',
data: {"updateMethod()"}
success:function(result){
console.log(result);
}
});
}
PHP file - abcd.php
<?php
class abcd {
public function updateMethod() {
//execute this part of the code
}
public function insertMethod() {
}
public function deleteMethod() {
}
}
I am not able to make a call to the PHP method. What is wrong with my AJAX query or what do I need to do in PHP file side to call the method.
I don't know what you try to do, but you can do it this way:
function update() {
$.ajax({
url:"abcd.php",
type: "POST",
dataType: 'json',
data: {methodName: "updateMethod"},
success:function(result){
console.log(result);
}
});
}
On server side:
<?php
class abcd {
public function updateMethod() {
//execute this part of the code
}
public function insertMethod() {
}
public function deleteMethod() {
}
}
$abcd = new abcd();
$method = $_POST['methodName'];
$result = $abcd->$method();
Remove this line
dataType: 'json',
and send data without json
If you sending json in php must be:
$data = file_get_contents('php://input');
PHP "php://input" vs $_POST
Or beter jquery:
var methodName = "YourMethodName";
var y = "Cymbal";
$.post( "test.php", { methodName: methodName, lastname: y })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Maybe something like this is more secure and I think you also need function arguments for CRUD actions(Not tested):
backend:
class CRUD
{
public function update($args)
{
$input = $args['exampleInput'];
// sanitize input
// prepared query
// $stmt->execute($input);
}
}
function access($class, $method, $args)
{
if (method_exists($class, $method)) {
return call_user_func_array([$class, $method], [$args]);
}
}
$data = file_get_contents('php://input');
access('CRUD', $data->method, json_decode($data->args));
js:
function handleAction(methodName, arguments) {
$.ajax({
url: "crudFile.php";
type: "POST",
data: { method: methodName, args: arguments },
dataType: 'json',
success: function (result) {
console.log(result);
}
});
}
var inputs = {
exampleInput: function () {
return document.getElementById('your-div-id').textContent();
},
};
// usage
handleAction('update', inputs);

How to set serialization in Asp .Net Core

Im getting the following error on my Ajax post back {"readyState":0,"status":0,"statusText":"error"}
on my first ajax call but the second one returns data I want.
My C# method (UserSelect) JsonResults shows the data when I put break point
My C# code :
public IActionResult OnPostAreaSelect(string Id)
{
//Generating list for Areas
Guid ModelId = new Guid(Id);
List<ModelArea> modelAreas = _context.ModelArea.Distinct()
.Where(w => w.ModelId == ModelId).OrderBy(o => o.AreaColumn.Name).Include(i => i.AreaColumn).ToList();
return new JsonResult(modelAreas);
}
public IActionResult OnPostUserSelect(string Id)
{
//Generating list for Users
Guid ModelId = new Guid(Id);
List<UserModel> userModels = _context.UserModel
.Where(w => w.ModelId == ModelId).OrderBy(o => o.User.FullName)
.Include(i => i.User)
.ToList();
return new JsonResult(userModels);
}
My JavaScript :
<script type="text/javascript">
$(document).ready(function () {
$("#RepfocusModelDropdown").change(function () {
var Id = $(this).val();
if (Id != null) {
$.ajax({
async: true,
type: "POST",
url: "./Create?handler=UserSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
crossDomain: true,
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
$.ajax({
type: "POST",
url: "./Create?handler=AreaSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
}
})
})
The second ajax call on my script works fine only the first one returns the error
How can I solve the error
When you work with EntityFramework (or other ORM) there may be problems with serialization because an entity could have some circular references. To avoid this problem a solution is to set serialization settings:
services.AddMvc().AddJsonOptions(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
or:
Newtonsoft.Json.JsonConvert.DefaultSettings = () => new Newtonsoft.Json.JsonSerializerSettings {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

How to call a codeigniter function in ajax?

In controller I have a _remap() for routing.
My controller is as follows:
public function _remap($id)
{
$this->index();
}
public function index()
{
$this->accesscontrol->can_or_redirect('view', 'translation');
$this->output->view('translation/language');
}
function process(Request $request){
// if(Response::ajax()) return "OK";
return json_encode(array('ok'));
}
My view is as follows:
$('#lang_choice1').each(function() {
$('#src_trans_lang').val($("#lang_choice1 option:selected").val());
var msg = $(this).val();
$.ajax({
type: "POST",
url: '<?=site_url('translation/language/process')?>',
data: msg,
success: function(data){ }
});
return false;
});
I am trying to call the function process in ajax and its not getting called. How do I need to modify the _remap function to call ajax calls as well?
Try This
Script part
$('#lang_choice1').each(function () {
$('#src_trans_lang').val($("#lang_choice1 option:selected").val());
var msg = $(this).val();
$.ajax({
type: "POST",
url: '<?= site_url('language/process') ?>',
data: {"msg":msg},
dataType:"json",
success: function (data) {
console.log(data);
}
});
return false;
});
Controller process function
function process() {
$data = $this->input->post();
$result['status'] = "ok";
$result['response'] = $data;
echo json_encode(array($result));
exit(0);
}
Check response in console

How to combine multiple call to Ajax Data base from different JS files

I have some code on a file that makes Ajax calls. This file is being called as a function by multiple other files that creates a new instance each time.
This is the JS code that is being called:
define(["underscore", "homeop", "domReady!"],
function (_, homeop, domready) {
var timeout = 500;
return function (opUrl, opList, onCallback) {
// IRRELEVANT CODE
var getFetch = function (optionName) {
$.ajax({
url: optionsUrl,
data: { optionNames: [optionName] },
type: "POST",
dataType: "json",
async: false,
traditional: true,
success: function (data) {
_.each(data, function (optionData, optionName) {
if (homeop.globalCache[optionName] === null) {
homeop.globalCache[optionName] = optionData;
}
});
},
error: function (message) {
console.error(message.responseText);
}
});
};
self.getInfo = function (optionName) {
if (homeop.globalCache[optionName] === undefined) {
if (!_.contains(homeop.getOption(), optionName)) {
getFetch(optionName);
}
// MORE IRRELEVANT CODE GOES HERE
In other JS files, I call the get function; for example
var these = new getOptions(optionsUrl, optionsList, onLoadCallback);
var getOpt = these.get(OptionsUrl);
The problem is I am making multiple calls to the get information from the database causing multiple call to my JS file. Each new instance of the JS file will create a ajax call.
Is there a way to wait for all the calls to be done and then get data from the database? In other words how can I somehow combine all the call to my 'getOption.js'?
Thanks
Try this.. You can also implement queue in place of stack
var optionStack = [];
var isAvailable = true;
var getFetch = function (optionName) {
if(isAvailable){
isAvilable = false; // function not available now
}
else {
optionStack.push(optionName)
return;
}
$.ajax({
url: optionsUrl,
data: { optionNames: [optionName] },
type: "POST",
dataType: "json",
async: false,
traditional: true,
success: function (data) {
_.each(data, function (optionData, optionName) {
if (homeop.globalCache[optionName] === null) {
homeop.globalCache[optionName] = optionData;
}
});
},
error: function (message) {
console.error(message.responseText);
},
done: function (){
isAvailable = true;
if(optionStack.length > 0){
getFetch(optionStack.pop());
}
}
});
};

Ajax jquery sending Null value to Mvc4 controller

I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>

Categories