NET WEB API and I have searched form who get data in JSON format, actually the response data I show it in the same page.
I want to to send this data to another page with ajax, if it is possible, and show the results there.
This is the AJAX Code:
function AJAX_search_Profile(data) {
//alert('Ajax1');
if (!false)
//alert('Ajax2');
ajaxRequest = $.ajax({
type: "POST",
url: "../../api/Controllers/Manage_Search/search_Profile_by_Many_criterion",
contentType: false,
processData: false,
data: data
});
ajaxRequest.done(function (responseData, textStatus) {
AJAX_CallBack_search_Profile_by_Name(responseData, textStatus);
});
}
//Callback method
function AJAX_CallBack_search_Profile_by_Name(responseData, textStatus) {
if (textStatus == 'success') {
if (responseData != null) {
if (responseData.Key) {
// alert(responseData.Value);
var JsonData = jQuery.parseJSON(responseData.Value);
fill_in_Data(JsonData.docs);
//window.location.replace("./Home/Members");
// with this methode i print search result in the same
//page ,what i would is to redirect to another page and send this data with it
//in ajax
} else {
alert(responseData.Value);
}
}
} else {
alert(responseData.Value);
}
}
Related
I have some AJAX code in my JavaScript which is not showing any success or failure alert.
function AttemptHouseViewingAppointment(house) {
var imgOfHouse = $(house).attr("value");
$.ajax({
type: "POST",
url: '#Url.Action("AttemptHouseViewingAppointment", "Viewing")',
dataType: "json",
data: ({
userId: #Model.UserId,
appointmentKey: '#Model.Key',
chosenHouse: imgOfHouse
}),
success: function (data) {
alert(data);
if (data.success) {
alert(data.message);
} else { alert(data.Message) }
},
error: function (xhr) {
alert(xhr.responseText);
}
});
};
The above function is called when I click an image on the screen. This part works fine as I have set a breakpoint on my ASP controller and I can see the relevant action being called. C# code below:
public ActionResult AttemptHouseViewingAppointment(int userId, string appointmentKey, int chosenHouse)
{
string selecteHouseName = $"./house-code-icons/{chosenHouse}.png";
var house =
_ctx.houses.Where(x => x.HouseID == userId && x.Icon == chosenHouse)
.FirstOrDefault() ?? null;
if(house != null)
{
var member = _ctx.User.FirstOrDefault(x => x.Id.Equals(userId));
_ctx.Appointments.Add(new ViewingModel
{
House = chosenHouse,
UserId = userId
});
_ctx.SaveChanges();
return Json(new { success = true, message = "Appointment Confirmed!" });
}
else
{
return Json(new { success = false, message = "Sorry, a booking has already been made!" });
}
}
Even though, the return Json lines are being hit and returned to the page, there is no alert popup on my page to let user know if success or not. Please let me know if any questions.
Thanks
Add the done function to the end of Ajax
$.ajax({
.
.
.
}).done(function( response ) {
alert(response);
...
});
My case like this :
if(window.location.pathname == '/shop/payment/checkout' || window.location.pathname == '/shop/detail' || window.location.pathname == '/shop') {
alert('Your data has been removed')
localStorage.removeItem("cartCache")
var _token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: baseUrl+'/shop/delete-cache',
data: {_token: _token},
success: function(response){
if(response.success==1)
window.location = "/shop";
},
error: function(request, status, error) {
console.log('error')
}
});
}
If the url accessed meets the condition of if then it will delete session by ajax and redirect to the url /shop
My problem is if redirect to url /shop, it will check again and display alert message again. So on and on
I want if the alert message appears and reload to the url /shop, it does not check anymore and displays the alert message
How can I do it?
EDIT:
After the answer given, I wrapped my code like this:
if (localStorage.getItem("cartCache") !== null) {
...
}
else {
alert('Your data has been removed')
localStorage.removeItem("cartCache")
var _token = $('input[name="_token"]').val();
$.ajax({
type: 'POST',
url: baseUrl+'/shop/delete-cache',
data: {_token: _token},
success: function(response){
if(response.success==1)
window.location = "/shop";
},
error: function(request, status, error) {
console.log('error')
}
});
}
}
It does not work as intended.
Before removing, you could first check if the local storage data is still there. Put this before the alert:
if (localStorage.getItem("cartCache") === null) return;
... assuming this code is within a function. But you get the idea. Or you can combine it with the if you already have (a bit improved):
if(['/shop/payment/checkout', '/shop/detail', '/shop'].includes(window.location.pathname)
&& localStorage.getItem("cartCache") !== null) {
// ...etc.
I have basically the same problem as the one described in the link below, but I dont find the solution to be very clear. I want my ajax success function to wait until the window function is finished executing, THEN modify the divs. Instead, it modifies the divs of the current page, then redirects. AJAX: on success redirect then modify new page
main.js
$("#form").submit( function(e) {
e.preventDefault();
var id = $('#searchbar').val(); // store the form's data.
$.ajax({
url: '/search',
type: 'POST',
data: {id:id},
dataType: 'text',
success: function(data) {
//Redirect to the page where we want to display the data
window.location.href = '/test';
data = JSON.parse(data);
console.log(data);
$("#count").text("we analyzed...");
$("#result1").text(data.county);
$("#totals").text("with a score of..");
$("#result2").text(data.totalSentiments);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("error")
alert(textStatus, errorThrown);
}
});
});
I Will Suggest you Javascript Local Storage .
main.js
$("#form").submit( function(e) {
e.preventDefault();
var id = $('#searchbar').val(); // store the form's data.
$.ajax({
url: '/search',
type: 'POST',
data: {id:id},
dataType: 'text',
success: function(data) {
//Redirect to the page where we want to display the data
window.location.href = '/test';
data = JSON.parse(data);
console.log(data);
// Store
localStorage.setItem("count", "we analyzed...");
localStorage.setItem("result1", data.county);
localStorage.setItem("totals", "with a score of..");
localStorage.setItem("result2", data.totalSentiments);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("error")
alert(textStatus, errorThrown);
}
});
});
On Ready on same page:
jQuery(document).ready(function(){
if (localStorage.count) {
$("#count").text(localStorage.count);
}
if (localStorage.result1) {
$("#result1").text(localStorage.result1);
}
if (localStorage.totals) {
$("#totals").text(localStorage.totals);
}
if (localStorage.result2) {
$("#result2").text(localStorage.result2);
}
});
Local Storage Store Data in Browser Storage. You Also Can Remove Data From Local Storage.
setting the value of location.href will cause a full page refresh.
Therefore all your scripts will be wiped out.
If you REALLY wants to use the result of a ajax call to a redirected page, you should store this response data somewhere, then reuse it on your new page.
//save "data" in localSotorage
localStorage.myAjaxResponse = data; //if data is JSON then use: JSON.stringify(data) instead.
Then on your "/test" page, create a script to check for the value on the localStorage then display it.
data = JSON.parse(localStorage.myAjaxResponse);
console.log(data);
$("#count").text("we analyzed...");
$("#result1").text(data.county);
$("#totals").text("with a score of..");
$("#result2").text(data.totalSentiments);
Although, there are other better ways to accomplish what you want.
You can do something like this:
On your ajax success:
data = JSON.parse(data);
console.log(data);
window.location.href = '/test?county='+data.county+'&sentiment='+totalSentiments;
Then on your test page write in javascript block:
var params={};
window.location.search
.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
params[key] = value;
}
);
if (params.length > 0) {
$("#count").text("we analyzed...");
$("#result1").text(params['county']);
$("#totals").text("with a score of..");
$("#result2").text(params['sentiments']);
}
I have one form ,when i click submit button am saving those values and on button click am calling "SaveData() " method.
So when i try to add data and click on submit button and nothing is happening am getting following errors in my browser log.
My onclick function code
function requestReferral() {
var nameperson = $("#namefield").val();
var contact1 = $("#contact").val();
//Till this part working i mean alert is printing .
$.ajax({
url: '/mycontroller/myfunction',
data: 'name='+nameperson+'&contact='+contact1,
type: 'post',
success: function(result){
data = jQuery.parseJSON(result);
if(data.result == "SUCCESS"){
clearMyFormData();
} else {
showMessage();
}
}
});
}
my error is
Failed to load resource: the server responded with a status of 500 (Internal Server Error) with my controller url www.example.com/mycontroller/myfunction
First of all, check if your url is ok, for example, if you are using php with codeigniter your url need to be like this:
url: <?php echo base_url()?>mycontroller/myfunction
and second, when I used ajax, I send data like this
postData = {
name: nameperson,
contact: contact1
}
$.ajax({
url: '/mycontroller/myfunction',
data: postData
type: 'post',
success: function(result){
data = jQuery.parseJSON(result);
if(data.result == "SUCCESS"){
clearMyFormData();
} else {
showMessage();
}
}
I am new to .NET MVC so please bear with me.
I wrote a function that gets triggered when there is a blur action on the textarea control:
function extractURLInfo(url) {
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
complete: function (data) {
alert(data);
},
success: function (data) {
alert(data);
},
async: true
})
.done(function (r) {
$("#url-extracts").html(r);
});
}
jQuery(document).ready(function ($) {
$("#input-post-url").blur(function () {
extractURLInfo(this.value);
});
});
This works fine and will hit the controller:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
I get the intended results if the URL is valid; it will return a partialview to the .done() function and I just display it in code. However, if the URL is not valid i want it to hit either complete, success, or done (I have been playing around to see which it will hit but no luck!) and do something with the returned data. I had it at some point trigger either complete or success but the data was 'undefined'. Can someone help me out on this?
Thanks!
In both cases your controller action is returning 200 status code, so it's gonna hit your success callback:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
if (data.message) {
// Your controller action return a JSON result with an error message
// => display that message to the user
alert(data.message);
} else {
// Your controller action returned a text/html partial view
// => inject this partial to the desired portion of your DOM
$('#url-extracts').html(data);
}
}
});
But of course a much better and semantically correct approach is to set the proper status code when errors occur instead of just returning some 200 status code:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
Response.StatusCode = 400;
Response.TrySkipIisCustomErrors = true;
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
and then in your AJAX call you would handle those cases appropriately:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
$('#url-extracts').html(data);
},
error: function(xhr) {
if (xhr.status == 400) {
// The server returned Bad Request status code
// => we could parse the JSON result
var data = JSON.parse(xhr.responseText);
// and display the error message to the user
alert(data.message);
}
}
});
Also don't forget that you have some standard way of returning your error messages you could subscribe to a global .ajaxError() handler in jQuery instead of placing this code in all your AJAX requests.