How to get value from MVC controller action on page asynchronously - javascript

I have a page with cascad downloaded areas (select something in first area -> downloaded specific data to second area).
And I need to hide some content depending on data from the first area.
I need something like this (in javascript):
var result = getDataFromController(controllerName:"Quotes",
actionName:"IsQuoteOrdered",
param: quoteId);

Consider using jquery to simplify the ajax calls.
If you go that route the following would allow you to replace the dd2 element portion of the page with the result of a controller action call upon change of selection in dd1 :
$(document).ready(function() {
$('#dd1').change(function() {
$.ajax({
type: "POST",
cache: false,
data: 'firstDropdownSelectedValue=' + $('#dd1').val(),
url: 'YourControllerName/YourActionName',
success: function (data) {
$('#dynamicDivPortionOfThePageReturnedByYourView').replaceWith(data);
}
});
});
});

Related

JQuery - Send inputs via ajax (which were obtained by ajax)

I have an application that after performing a search, returns me multiple "fieldsets" with some hidden inputs (via AJAX!).
I want to use these inputs to send information to the server (again) via AJAX.
The names of these inputs are automatically listed with a prefix:
"video_url_1", "video_url_2", etc.
When the user clicks the button, the value of "video_url_1" or "video_url_2" will be sent via AJAX depending on the button to which it has clicked. To solve this I got the name of the button that was clicked and then I cut the name so that I only have one number, this number I put in a variable and then use it in the "data" section of AJAX.
I did the test by sending a locally stored input and it worked but when trying to send the inputs that were previously obtained by an ajax, it does not work.
What can be wrong? This is my code:
$(document).ajaxComplete(function(){
$('a.report_video').click(function() {
var idbutton = $(this).attr('id');
var idreport = idbutton.replace('report_video_', '');
//I'm still not using these variables, can they be used to pass the input data to ajax?
var videourl = $("#video_url_" + idreport).val();
var videoid = $("#video_id_" + idreport).val();
var videoserver = $("#server").val();
///////////
$.ajax({
type : 'POST',
url : 'https://example.com/script/script.php',
data : $($("#video_url_" + idreport)).serialize(), //It doesn't work
//For example, data: $("#server").serialize()
//Work fine, this input is stored locally.
beforeSend: function(){
$('#video_report_' + idreport).html('<img src="'+pluginUrl+'./assets/img/loading.svg" />');
}
}).done(function(data) {
$('#video_report_' + idreport).html(data);
});
return false;
});
});
Edit:
I just did some tests as suggested by Kevin B and I see that the problem I have is in the syntax when trying to send two dynamic ID's by Ajax.
The problem is that I do not know how to write them correctly, I know that is the problem because when I tried to send them separately they did work...
data : $($("#video_id_" + idreport), $("#video_url_" + idreport)).serialize(),
I'm not sure I completely understand your problem, but this might help.
You call your second AJAX call in the .success() method of the first AJAX call. Essentially chaining the responses.
$('#btn').click(function() {
$.ajax({
type: "POST",
url: 'someURL',
data: someData
}).done(function(firstCallData) {
// This OPTIONAL method fires when the AJAC call succeeded
// You can also put another AJAX call in here with the data returned from the first call
$.ajax({
type: "POST",
url: 'someURL',
data: firstCallData
}).done(function(data) {
// Do something with second AJAX call with data
}).fail(function(data) {
// Second AJAX call failed, handle error
});
}).fail(function(data) {
// This OPTIONAL method fires when the first response failed
}).always(function(data) {
// This OPTIONAL method fires regardless if the first call succeeded or failed.
});
});

AJAX - Calling a function that directs to another page

I have this javascript functions,
This View function is a simple function that lets me go to my view page.
function View(URLPath) {
$.ajax({
url: URLPath,
type: "get",
dataType: "text"
}).done(function(data) {
$('#viewcontainer').html(data);
});
}
The other one is a simple function that let me add.
function Add(URLPath) {
var data = $("#Form").serialize();
$.ajax({
type: "post",
data: data,
url: URLPath,
complete: function(responseData){
View(ROOT_URL + '/view');
}
});
}
After I add data I want it to return to my view page. This will show that the data has been added.
So in the complete part of the Add function, I call the View function.
complete: function(responseData){
View(URL + '/view');
}
The problem is it will not load. It will return me to my home page.
I think it is because the add function is in another page and when I call the View function in the complete part, It will not find the id = #viewcontainer.
The view page will look like this
<div id="viewcontainer">
HERE IS THE VIEW
</div>
add will look like this
<p>THIS IS ADD</p>
EDIT
The files are already included.
If your viewcontainer is in view.html and you are trying setting $('#viewcontainer').html(data); which is in your home.html page; then it will not work as its not in the scope and unknown to the context.
You should include View function where it is called. If this a script file include or simple copy/paste function in same page where call.
Javascript required function on same page when finally render on browser.
If View(ULR) function not found you will received an error on console like function not defined
If you function exist on same page and div id not found you will also receive an error on console.

From AJAX var to PHP variable getting the success code right

I have been working on this for a while and posted several related topics about it, but this is slightly different question. I have the following AJAX code with some html forms below it with in #container and .myselect is the class of a drop-down box. When I change the value in the box I want to be able to then use that value on other fields below the select. The AJAX code kinda works in that the alert shows the right value when changed but as you can see I have tried lots of success functions but no luck. The closest is
$('#reloadtest').html(data); which will show the value in my PHP and every time I change the value from then on it will change alot, but it reloads the page within the container.
Basically I want to know how I can reload the data but not the whole html/page so I can use the value of the drop down in my PHP.
$(document).ready(function(){
$('#container').on( 'change', '.myselect', function() {
var orderidVal = $(this).val();
alert(orderidVal);
$.ajax({
type: "POST",
data: { orderidType : orderidVal },
success: function(data) {
//$('#container').reload('#container', function() {});
//$('#quoteselect').reload('#quoteselect', function() {});
//$('#container').load('orders.php #container', function() {});
//$('#quoteselect').load('orders.php #quoteselect', function() {});
//$('#testreload').reload('#testreload', function() {});
//location.href = "test2.php"
$('#reloadtest').html(data); //this allows me to use the variable but reloads the whole page within the page
}
})
});
});
If you are doing an ajax-request you have to allocate an URL where to send the request.
If you don't Request anything jQuery reloads the page. As you can see here in the jquery-api-docu the URL is the very first and most important parameter of the request.
$.ajax({
url: "/url/to/the/php/script.php",
success: function(data){
//do something ... with data parameter
}
});
would be the simple way of using ajax-request with javascript.
use two divs - one in which you can put ajax response and in other the remaining HTML code
it reloads your page because you have not specified what page to request.
use the code below and replace /path/to/script to your actual script path
$(document).ready(function(){
$('#container').on( 'change', '.myselect', function() {
var orderidVal = $(this).val();
alert(orderidVal);
$.ajax({
cache: false,
async: true,
type: "POST",
url: '/path/to/script',
data: { 'orderidType' : orderidVal },
success: function(data) {
$('#reloadtest').html(data);
}
});
});
});

table positioning with AJAX to PHP post

I have a jQuery script that sends POST data via AJAX to a php file that then creates a table. I have used firebug to check the console and everything gets created properly. On the success: I reload the window and the table isn't displayed.
I know the table html was created properly from the php file because I commented out the reload so I could see exactly what it created) I have lots of things displayed on my page and would like the table in a particular spot. How can I get the table to actually display where I want it to?
<script>
$(document).ready(function () {
$("#stayinfobutton").click(function () {
var id = $('#id').val();
var dataString = {
id: id
};
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/table_auto_guests.php",
data: dataString,
cache: false,
/*success: function(html)
{
window.location.reload(true);
}*/
});
});
});
</script>
The window.location call will reload a new page in the browser window, this will loose the data returned to the ajax call by the server.
Usually the response to Ajax calls is loaded directly into your page, something like:
success: function(html)
{
$('#guestsTable').html(html);
$('userForm').hide();
}
I made up the guestsTable div and userForm names, ;).
The return data may need some coercing to make it into html (I'm assuming your using JQuery), hopefully the php script will set it to html/text in the header, also dataType: html can be passed in the $.ajax({...}) call.
Alternatively, if the classes/table_auto_guests.php returns a full page which you want to load in the browser, Ajax may not be what you are looking for. This post contains code on how to submit the data as a form, and load the result as a new page.

Wanting to load image and some text for the selected option in a dropdown list using Ajax

I can't find a decent example of this anywhere.
Basically have a dropdown list, each option value is the productID and text is the Product name.
I want to post all the selected option values to an action method that will return the respective images on document ready. Image data will the be passed to a function which will update the DOM and then execute the same function everytime a different option from dropdown list is selected to retrieve and change the selected options/product image only.
The action method will return the image for this option/value to the client in an AJAX response, I also want to return the product description too.
Should the response data-type be JSON or do I have to return it in some other way i.e HTTP response with image MIME type?
Something like the below collects all the selected values in an array:
$(document).ready(function () {
var arr = new Array();
$('select option').each(function () {
arr.push($(this).val());
});
// This below will post it off:
$.ajax({
type: "POST",
url: "/System/GetProductImages",
data: { arr: arr },
traditional: true,
success: function (data) {
mydata = data;
OnSuccess(data) // <--- The function that will load/update the images
},
dataType: "json" //<--- ?
});
});
I am not sure how to form the AJAX request correctly so I can request both an image and some text, or is it best to make separate calls when requiring different data types? Maybe I can pack them all in into an array of some sort? Also not to sure how the function that will update the DOM with the retrieved images will look.
I would say that your response should be JSON having and Image ID(a value to identify your image from DB) and Product description. Then using that construct dynamic image elements in HTMl and set their src tag to a URL by passing that image ID as parameter and on server side there should be a handler for your request(like servlet, which reads the Image ID and fetches image stream and returns as response). So, browser make a request for each image and get it rendered on browser. hope it will help you!
You can retrieve the new data using the change event on the select box:
$(document).ready(function(){
$('select').change(function(){
$.ajax({
type: "POST",
url: "/System/GetProductImages",
dataType: 'json',
data: { 'id': $('select').selectedIndex.val() },
traditional: true,
success: function (data) {
mydata = data;
OnSuccess(data) // <--- The function that will load/update the images
}
});
});
});
Additionally, if you're more comfortable with PHP, you could echo out the results from the PHP script and call the load function on change of the select option like so:
/* JQuery code */
$(document).ready(function(){
$('select').change(function(){
$.load("/System/GetProductImages", function(){
// The script to run when a successful load operation takes place
});
});
});
/* PHP Code */
echo "<script>$('tag name').html('value you want to set'); $('img').attr('src','new image src');</script>";
Though I'm not sure calling the script from within PHP is the best solution. You should also keep in mind that the Content-Type response header should be set to "application/json".
If you're using PHP, you can use the json_encode function to return a JSON result. You can read more about the PHP JSON options here - http://php.net/manual/en/function.json-encode.php
Hope this helps.

Categories