Can't call the webmethod using user control - javascript

I'm creating a modal when I click I will pass the id and action to the serverside to save a logs.
Here is my sample code but can't get it to work. I'm using a usercontrol.
$("a.modal_show2").click(function () {
$(this).each(function () {
if ($(this)) {
var storecheckid = $(this).attr("id");
$.ajax({
type: "POST",
url: "TalkTalk.aspx/saveLogs",
data: {
action: 'video_tag',
clickedlinktag: storecheckid
},
dataType: "text",
success: function (response) {
console.log(response);
}
});
}
});
});
[System.Web.Services.WebMethod]
public static string saveLogs(string action, string clickedlinktag)
{
DataHelper.InsertLogs("TalkTalk", Convert.ToInt16(clickedlinktag), Convert.ToInt16(TwwId));
return clickedlinktag;
}
Thanks

data: JSON.stringify({ action: 'video_tag', clickedlinktag: storecheckid })
// response is a wrapper for your data. your data is in `d`.
success: function (response) {
console.log(response.d);
}

Related

Yii2 302 Redirect jQuery AJAX request, redirecting entire page

I have an action:
public function actionAjaxLoadBasketSmall() {
$this->enableCsrfValidation = false;
return $this->renderPartial('#app/views/basket/_small');
}
Some JavaScript
function loadBasketSmall() {
$.ajax({
method: "POST",
url: "/basket/ajax-load-basket-small",
dataType: "html",
beforeSend: function () {
$('#basketSmall').addClass('loading');
},
complete: function (data) {
$("#basketSmall").replaceWith(data.responseText);
}
});
}
Called from this function for example:
function handleProductTileButton(e) {
e.preventDefault();
var input = $(this);
$('#basketSmall').addClass('loading');
$.ajax({
method: "GET",
url: "/basket/ajax-add-product",
dataType: "html",
data: {
productId: input.data('product-id'),
quantity: 1,
},
beforeSend: function () {
input.addClass('loading');
},
complete: function (data) {
$('.top-bar .search-results').html(data.responseText);
input.removeClass('loading');
loadBasketSmall();
}
});
}
Whenever the Ajax call is complete the entire page gets redirected to /basket/ajax-load-basket-small
These are the response headers. Note the 302 response code.
So it was down to the language detection that was making the server send redirect responses.
To solve this I added this code to my base controller class
public function init() {
parent::init();
$this->initJsLang();
}
public static function jsDefineLang() {
return "const LANG = '" . \Yii::$app->language ."';";
}
protected function initJsLang() {
$this->getView()->registerJs(static::jsDefineLang(), \yii\web\View::POS_HEAD);
}
And updated my JavaScript accordingly:
function handleProductTileButton(e) {
e.preventDefault();
var input = $(this);
$('#basketSmall').addClass('loading');
$.ajax({
method: "GET",
url: "/" + LANG + "/basket/ajax-add-product",
dataType: "html",
data: {
productId: input.data('product-id'),
quantity: 1,
},
beforeSend: function () {
input.addClass('loading');
},
complete: function (data) {
$('.top-bar .search-results').html(data.responseText);
input.removeClass('loading');
loadBasketSmall();
}
});
}
function loadBasketSmall() {
$.ajax({
method: "GET",
url: "/" + LANG + "/basket/ajax-load-basket-small",
dataType: "html",
beforeSend: function () {
$('#basketSmall').addClass('loading');
},
complete: function (data) {
$("#basketSmall").replaceWith(data.responseText);
}
});
}
So final solution after Muhammad's suggestion
LanguageAsset.php
<?php
namespace frontend\assets;
use yii\web\AssetBundle;
/**
* Language application asset bundle.
*/
class LanguageAsset extends AssetBundle
{
public function init() {
parent::init();
$view = \Yii::$app->controller->view;
$language = \Yii::$app->language;
$js = "const LANG='{$language}';";
$view->registerJs($js, $view::POS_HEAD);
}
}
In my layout files I added:
use frontend\assets\LanguageAsset;
LanguageAsset::register($this);

ajax success response change as #html.raw

I have following jquery code in my Razor viewpage
$(document).ready(function () {
var grouplistvalues = #Html.Raw(Json.Encode(Session["grouplist"]));
$("#nsline").click(function () {
alert(grouplistvalues)
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
alert(response)
},
error: function ()
{
}
});
});
$("#ewline").click(function () {
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
},
error: function ()
{
}
});
});
in above grouplistvalues its taking session as html raw
when I alert it on #nsline click function I can see it,
in above function I'm calling to ajax function and above grouplistvalues value updating
once I alert it on #nsline click function success response I can see a alert like folllowing
since this(grouplistvalues value) 1,2,.. changing as [1,2..] I cannot call to other ajax function in #ewline click function since parameter difference,
this is the above common ajax call
[HttpPost]
public JsonResult SetupGroups(long[] grouplist)
{
Session["grouplist"] = null;
List<long> groupList = new List<long>();
foreach (var groupitem in grouplist)
{
groupList.Add(groupitem);
}
long[] grouparray = groupList.ToArray();
Session["grouplist"] = grouparray;
return Json(grouparray);
}
}
Though I have two click functions its work with only the first click(ewline or nsline only the first time)
How to solve this
It was the dataType in your ajax request. It should be json:
dataType: "json"

Reloading a web page with ajax from a second web service url

i have a page which gets its data from a web service that have specific url ,
i'm doing some traitement (a checkbox multiple choices) , and i wanna make my same page reload and get its data from a second webservice from a second url recuper its data .
here is my js block of recupering data for the first time :
var find_freelance = {
page: [$('[data-page="mypage"]')],
route: {
getdata: back + 'api/webservice1',
},
block: {
resume: $(""),
},
init: function () {
console.log(find_freelance.page);
for (var i in find_freelance.page) {
if (find_freelance.page[i].length) {
this.getData();
}
}
},
getData: function () {
$.ajax({
method: 'GET',
url: find_freelance.route.getfreelance,
dataType: 'json',
success: function (data) {
matchDataHtml(data);
matchDataHtmlFor(data);
matchDataHtmIf(data);
customTraitement()
},
error: function (data) {
console.log(data);
}
});
},
Now i wanna that page reload after a custum action (customTraitement() )
from the second webservice of response.
" api/webservice2
how can i do it , any suggestions ??
Add at the final sentence in the ajax function "return false;"
getData: function () {
$.ajax({
method: 'GET',
url: find_freelance.route.getfreelance,
dataType: 'json',
success: function (data) {
matchDataHtml(data);
matchDataHtmlFor(data);
matchDataHtmIf(data);
customTraitement()
},
error: function (data) {
console.log(data);
}
return false;
});
},

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

Jquery Ajax and MVC5 httpPost no value received

I try to send values from my view to my controller.
The method in my controller is called but the value(s) still remain NULL.
Here is the Javascript part:
GUIRequests.prototype.SetNewItemDeliveryValues = function () {
var modelNumberID = this.GetValue('#ModelNumberID');
this.Request.GetPreOrderIDForModelNumberID(modelNumberID); //InventValueRequest
this.Request.GetShortfallAndOverdeliveryInNewItemDelivery(modelNumberID);
}
InventValueRequest.prototype.GetPreOrderIDForModelNumberID = function (_modelNumberID) {
this.CallAjax("/NewItemDelivery/GetPreOrderIDForModelNumberID", _modelNumberID, CallbackMethods.SetPreOrderID);
}
//Private
InventValueRequest.prototype.CallAjax = function (_url, _data, _successFunctionPointer) {
$.ajax({
type: 'POST',
url: _url,
contentType: 'application/json',
data: JSON.stringify(_data),
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
}
Asp.Net MVC5 (C#) part
[HttpPost]
public ActionResult GetPreOrderIDForModelNumberID(string _modelnumberID)
{
String preOrderID = "";
if (_modelnumberID == null)
{
preOrderID = "No value received";
}
else
{
//Do something
}
return Json(preOrderID);
}
What could be the problem with my code ? why don't I receive any values in my C# part ? It seems that the values get send correctly, at least the payload contains the values I would expect.
_data should have the property _modelnumberID like following.
_data = {'_modelnumberID': '1'}
try below code :
$.ajax({
type: 'POST',
dataType: 'text',
url: _url,
contentType: 'application/json',
data: "_modelnumberID=" + _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
The Ideal solution would be to use a view model.
public class Create
{
public string _modelnumberID{get;set;}
}
And your HttpPost action would be accepting an object of this
[HttpPost]
public ActionResult View(Create model)
{
// do something and return something
}
and ajax will be
$('.submit').click(function () {
var myData = {
_modelnumberID: _data
}
$.ajax({
url: '/Controller/Action',
type: 'POST',
data: myData,
processData: false
}).done(function () {
}).fail(function () {
});
});
$.ajax({
type: 'POST',
url: _url+"?_modelnumberID="+ _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
Try this.

Categories

Resources