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

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;
});
},

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);

Can't call the webmethod using user control

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);
}

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"

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);
}

AJAX: Pass a value to ajax method

Ive tried a couple out-of-the-box ways trying to get my value into my ajax but everytime I get js error's. Hopefully one of you can help.
I have the following JQuery Ajax:
$("#usertasklist").click(function () {
$('#basicModal4').modal('hide');
$.ajax({
type: "GET",
url: "/Home/GetAjaxUserTasksExecuted",
data: { filterdate: variable1 },
datatype: "html",
success: function (data) {
console.log("Succes!");
var $titleDiv = $('#Modal5Label');
$titleDiv.replaceWith("<h3><b>User Tasks Executed</b></h3>");
var $detailDiv = $('#superdatadivthing3');
$detailDiv.replaceWith(data);
},
error: function () {
console.log("Error!");
},
complete: function () {
$('#basicModal5').modal('show');
console.log("Complete!");
}
});
});
And a viewbag in my controller
Session["Usercode"];
How can I pass the value from my view bag to replace "variable1" in the data section of my ajax call?
How about getting the data from a container?
HTML-example
<table id="YOURDIVHERE">
<tr>
<td>
<span>data which i will use</span>
</td>
</tr>
</table>
Your Ajax-call
$("#usertasklist").click(function () {
$('#basicModal4').modal('hide');
var data = innerXHTML($('#YOURDIVHERE').attr('id'));
$.ajax({
type: "GET",
url: "/Home/GetAjaxUserTasksExecuted",
data: { filterdate: data },
datatype: "html",
success: function (data) {
console.log("Succes!");
var $titleDiv = $('#Modal5Label');
$titleDiv.replaceWith("<h3><b>User Tasks Executed</b></h3>");
var $detailDiv = $('#superdatadivthing3');
$detailDiv.replaceWith(data);
},
error: function () {
console.log("Error!");
},
complete: function () {
$('#basicModal5').modal('show');
console.log("Complete!");
}
});
});

Categories

Resources