i am using asp.net mvc 3. in one my of page. i need to get a list of string from a list object.
so i do this:
#{
var orderIds = from s in Model.Orders
select s.id;
}
and from one of my ajax call, i will need "orderIds "
$("#renderBtn").click(function () {
var inputData = {
'orderIds': need to get the order ids here
};
$.ajax({
url: '/Order/ExtraData',
data: inputData,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
....
},
error: function () {
...
}
});
});
any idea how can i get orderIds and use in javascripts?
Thanks
Your code aboce defining orderIds is a server-side variable; what you need us a client-side variable. You'll need to define that variable at the creation of the view, in a script block near the bottom of the page.
#{
var orderIds = string.Join(",", Model.Orders.Select(s => s.id).ToArray());
}
<script>
var orderIds = [#orderIds]
</script>
Caveat: The code may not be perfect, and may not compile, but that should give you an idea how to proceed.
If you aren't (or don't want to) using inline javascript and keep it all separated you could do something like this:
#{
var orderIds = string.Join(",", Model.Orders.Select(s => s.id).ToArray());
}
<input type="hidden" id="orderIds" value="#orderIds" />
And then in your javascript/jQuery:
orderIds = $('#orderIds').val();
Related
I am new to jQuery and I am trying to iterate through a list of strings after making an ajax call to a controller. In this controller, I am returning a list of strings and I want to iterate over this list in jquery and present it to the screen. Here is my code.
This is my controller
[HttpPost]
public ActionResult GetComments() {
var cmts = ex.GetComments(psts, psons);
var lstCmt = ex.GetCommentsList(cments, psons);
return Json(lstCmt);
}
This is my view:
<div>
<button id="ldBtn" class="btn btn-primary">Load</button>
</div>
<div id="cments">
</div>
<script src="~/Scripts/jquery-3.2.1.js"></script>
<script>
$(document).ready(function() {
$("#ldBtn").on('click', function(evt) {
$("#cments").empty();
$.ajax({
type: "POST",
dataType: "html",
url: '#Url.Action("GetComments")',
data: {},
success: function(lists) {
//Something needs to be fixed here
$.each(lists, function(i, name) {
$('#comments').append('<p>' + name.Value + '</p>');
});
}
});
});
});
</script>
When I return the list, I am getting a huge string. How do I fix this?
Thanks in Advance
There's a couple of issues in your JS code. Firstly you're telling jQuery to expect a HTML response in the dataType setting. This is why you see the response as a string. This should be changed to JSON instead, that way jQuery will deserialise the response for you.
Secondly you're attempting to concatenate a Value property on each item in the list, yet they are strings (as you state you're returning a List<string> from your action), and will not have that property. You can simply append the name itself. Try this:
$("#ldBtn").on('click', function(evt) {
$("#cments").empty();
$.ajax({
url: '#Url.Action("GetComments")',
type: "POST",
dataType: 'json',
success: function(comments) {
$('#cments').append('<p>' + comments.join('</p><p>') + '</p>');
}
});
});
I assume the #comments/#cments discrepancy is only due to amending parts of your code when creating the question.
Also note that I simplified the append() logic so that it appends all comments in a single call, which should be slightly faster.
Alright guys I'm trying to make a filter system for posts using ajax and a select box. I am able to get the value from the select box no problem. But my issue is that when I try to include the selected value in my PHP file it doesn't do anything. I have a file called public_wall.php. This file contains PHP, Javascript, and HTML. How can I refresh this div whenever a user selects a different filter option? Basically I need the selected value to be passed onto my public_wall.php file and then I want to plug it into the PHP function that fetches the posts thats's in the same file and then I want to refresh that same file to display the filtered results. Here is my Javascript code.
$("#postRatings").on("click", function(e) {
selectedRatingFilter = $("#postRatings option:selected").val();
var dataString = "timeFilter="+selectedRatingFilter;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response){
hideSpinner();
jQuery('#postsPagingDiv').remove();
jQuery('#wsc_midbox').html(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
jQuery('#paging_in_process').val(0);
}
});
});
When the dataType is set to "json" nothing happens. But when it is set to html it prints some javascript code. Please help. The PHP file is too large to include here, but it basically contains PHP, HTML, and Javascript and some PHP functions that do sql queries. What is the best way to achieve a filter mechanism for my setup?
And on the public_wall.php file I want to get the value like so:
$ratingFilter = isset($_REQUEST['timeFilter']) ? intval($_REQUEST['timeFilter']) : 0;
And then plug it into the PHP function that fetches the posts which is in the public_wall.php file also so that I can filter the posts based on the selected value. And then finally I want to refresh the public_wall.php file with the new results. I hope that makes sense. Please help.
This is the output when I set my dataType to "html"
<script>
function refreshPosts() {/* only posts comments likes and count updated. */
var posts = jQuery("#all_post_id").val();
var arrays = posts.split(',');
var dataString = "postids="+posts;
jQuery.ajax({
type: "POST",
url: site_url+"includes/update_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
var x = response;
//############ skip posts whose comments are being read by users
var ExemptedPostsIDs = jQuery("#exemptedPostsID").val();
var ExemptedArray = ExemptedPostsIDs.split(',');
ExemptedArray = ExemptedArray.sort();
//////////////
for (i=0; i<arrays.length; i++) {
var val = 'row'+arrays[i];
if(x[val]) {
if(!inArray(arrays[i], ExemptedArray))
jQuery("#ajax_wall_"+arrays[i]).html(x[val]);
} else {
jQuery('#PostBoxID'+arrays[i]).parent().fadeOut(500);
}
}
}
});
}
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
function refreshWall() {/* loads new posts real time */
var posts = jQuery("#all_post_id").val();
var pageUsing = jQuery('#pageUsing').val();
var dataString = "update_posts=1&postids="+posts+'&pagex='+pageUsing;
jQuery.ajax({
type: "POST",
url: site_url+"public_wall.php",
data: dataString,
dataType: "json",
cache: false,
success: function(response) {
if(response.all_post_id) {
jQuery('#wsc_midbox').prepend(jQuery(response.htmls).fadeIn(400));
setpost_ids(response.all_post_id);
}
}
});
}
</script>
I suggest you keep the form with select element and any JavaScript on the outer frame.
Via ajax, only load the results to a seperate DIVision below that.
When you put an Ajax response to a div, any JavaScript inside it will not be executed.
For the best throughput with Ajax, you should consider loading a json response via Ajax and create HTML elements on the client side. That way it becomes much easier to pull additional variables to front-end JS from server side along with the same request/response.
But that becomes bit difficult when you have a template engine in the back-end. You can still send the HTML content in a json value, so you can easily pass the "all_post_id" as well..
I'm trying to get and display a field in a SharePoint list
using a Content Editor Web Part. This is just proof of concept, I want the CWP to display the Title (the currency) and the Currency Description. I think I just need a tweak and want to understand what I'm doing wrong. The var query URL displays the title fine.
Ultimately what I want to do is to store the returned value from the Exchange Rate column so that when a user selects a drop don in a separate list and an amount it will convert by the Exchange rate.
Any help is appreciated. Code below:
<script type="text/javascript">
DisplayExchangeRate();
function DisplayExchangeRate()
{
var listName = "Currency Exchange Rates";
var titleField = "Title";
var rateField = "Currency Description";
var query = "http://collaboration-dev.norgine.com/sites/it/Tools/IT- Contracts/_vti_bin/listdata.svc/CurrencyExchangeRates?
$select=Title,ExchangeRate&$filter=Title eq 'Dollars'";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function (i, result) {
$("#CurrencyExchangeRatesTitle").text(result.Title);
$("#CurrencyExchangeRatesCurrencyDescription").html
(result.CurrencyDescription);
});
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving Tips: " + jqXHR.responseText);
});
}
</script>
I don't believe you can put JavaScript directly in a Content Editor Web Part. Try using a Script Editor Web Part instead (housed in the same category of web parts as the CEWP), or pointing your CEWP to a local HTML page with the JavaScript.
http://info.summit7systems.com/blog/dont-script-in-the-wrong-web-part
Also, it looks like you're using JQuery. Do you have a reference to that library elsewhere that is loading successfully?
Below is my Working code , I have saved this code in a text file, and uploaded that file in "Site Assets" library and pointed my CEWP to this code file.
<script type="text/javascript" src="https://test.sharepoint.com/sites/devsite/SiteAssets/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var i,result;
$('#getEmployee').click(function () {
var dispalyResults="";
$.ajax({
url: "https://test.sharepoint.com/sites/devsite/_api/web/lists/getbytitle('Employee')/items",
method: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function (data) {
var jsondata = JSON.stringify(data);
result = JSON.parse(jsondata).d.results;
for (i = 0; i < result.length; i++) {
dispalyResults+="<p><h1>"+ result[i].ID + " " + result[i].Title +"</h1></p>";
}
$('#displayResults').html(dispalyResults);
},
fail: function () {
alert("Response fails");
}
})
})
})
</script>
<input type="button" value="GET" name="GET" id="getEmployee"/>
<div id="displayResults"></div>
I have created a button and a DIV tag. When i click the button , it will display the list item Title and ID inside the DIV tag.
I need to get current page id or name from ajax request callback. Initially at loading a page i made an ajax request. In its callback method i need to get the current page id or name. I used following code for ajax request.
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "notes_select_page"
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
I took the request from action hook.
add_action('wp_ajax_nopriv_notes_select_page', 'Notes::select_page');add_action('wp_ajax_optimal_notes_select_page', 'Notes::select_page');
And the callback i used several code but doesn't work. Try 1.
public static function select_page(){
global $pagename;
die($pagename);
}
Try 2
public static function select_page(){
global $wp_query;
$pagename = get_query_var( 'pagename' );
if ( !$pagename) {
$post = $wp_query->get_queried_object();
$pagename = $post->post_name;
}
die($pagename);
}
Try 3
public static function select_page(){
global $post;
die($post->ID);
}
But unfortunately any of them doesn't work to get current page ID or name. Callback is working fine with other values.
Thanks in advance.
function get_current_page_id() {
var page_body = $('body.page');
var id = 0;
if(page_body) {
var classList = page_body.attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item.indexOf('page-id') >= 0) {
var item_arr = item.split('-');
id = item_arr[item_arr.length -1];
return false;
}
});
}
return id;
}
You don't need ajax for this.
Add this function to your code.
You can now get the page id by using:
var id = get_current_page_id();
To retrieve the post details you have to send the data yourself
data:{
action: "notes_select_page",
post_id: current_post_id, //current_post_id should either parsed from DOM or you can write your ajax in PHP file
}
You can either use a hidden box for current post id and get in the Js file using class or id or write the ajax in you php file itself.
Then you can retrieve via POST
public static function select_page(){
$post_id = $_POST['post_id'];
}
I'm getting post ID from the default WordPress post editing form, like so :
var post_ID = jQuery('[name="post_ID"]').val()*1;
Tje *1 converts the ID into an integer, otherwise it's interpreted as a string.
First take page id by this function
either
<div id="current_page_id"> <?php get_the_ID(); ?> </div>
or
<body page-id="<?php get_the_ID(); ?>">
Now In jquery ajax take following
var page_id = $('current_page_id').html();
OR
var page_id = $('body').attr("page-id");
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "pageid="+page_id,
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
There is a solution to solve the issue in Wordpress. Adding ajax code in wp_footer hook, where using php code current page id can be retrieved and pass as ajax value.
You can obtain alternatively by the hidden field the post/page id in the following manner. This code is inserted in the template file (and then the value will be send to your ajax action hook as indicated above):
<?php
echo '<input type="hidden" name="activepost" id="activepost"
value="'.get_the_ID().'" />'
;?>
Check out this for reference: https://developer.wordpress.org/reference/functions/get_the_id/
Is there a method to include more than one value at a time. Firstly, here is the script:
$(document).ready(function() {
$('.edit_link').click(function() {
$('.text_wrapper').hide();
var data=$('.text_wrapper').html();
$('.edit').show();
$('.editbox').html(data);
$('.editbox').focus();
});
$(".editbox").mouseup(function() {
return false
});
$(".editbox").change(function() {
$('.edit').hide();
var boxval = $(".editbox").val();
var dataString = 'data=' + boxval;
$.ajax({
type: "POST",
url: "update_profile_ajax.php",
data: dataString,
cache: false,
success: function(html) {
$('.text_wrapper').html(boxval);
$('.text_wrapper').show();
}
});
});
$(document).mouseup(function() {
$('.edit').hide();
$('.text_wrapper').show();
});
});
I want to have more than one field. I want to edit more than one entry at a time, instead of simply re-writing the code for each different value. Is there a way I can include them in the code? I tried this but had no luck:
$('.edit_link','.edit_link2','.edit_link3').click(function() {
$('.text_wrapper','.text_wrapper2','.text_wrapper3').hide();
var data=$('.text_wrapper','.text_wrapper2','.text_wrapper3').html();
Hopefully you get what I mean by this, I want to include more values but cannot achieve this, does anyone have some advice or a simply way to do this?
Put all in one string, for example:
$('.text_wrapper, .text_wrapper2, .text_wrapper3').hide();
But you can't read out the values with html() on multiple elements at the same time.
So for example use:
data = $('.text_wrapper').html();
data += $('.text_wrapper2').html();
data += $('.text_wrapper3').html();
But this depends on how you wanna have your data in the end.