in the jquery.get() function, the first parameter is URL, is that the url to the content I want to retrieve or to the Controller/action method.
The problem is I'm building an asp.net-mvc application and I'm not sure what to pass as this parameter. Right now I'm passing my partialview.cshtml but nothing is being returned, not sure if I'm doing this right or wrong.
Here's what I got
<div id="editor_box"></div>
<button id="add_button">add</button>
<script>
var inputHtml = null;
var appendInput = function () {
$("#add_button").click(function() {
if (!inputHtml) {
$.get('AddItem.cshtml', function (data) {
inputHtml = data;
$('#editor_box').append(inputHtml);
});
} else {
$('#editor_box').append(inputHtml);
}
})
};
</script>
also, what is the second parameter "function (data)" is this the action method?
You need to remove var appendInput = function () { from the script. You are defining a function but never calling it. Just use the following (update you action and controller) names
<script>
var inputHtml = null;
$("#add_button").click(function() {
if (!inputHtml) {
$.get('#Url.Action("SomeAction", "SomeController")'', function (data) {
inputHtml = data;
$('#editor_box').append(inputHtml);
});
} else {
$('#editor_box').append(inputHtml);
}
});
</script>
Edit
Based on your script you appear to be requiring the content only once (you then cache it and add it again on subsequent clicks. Another alternative would be to render the contents initially inside a hidden <div> element, then in the script clone the contents of the <div> and append it to the DOM
<div id="add style="display:none">#Html.Partial("AddItem")</div>
$("#add_button").click(function() {
$('#editor_box').append($('add').clone());
});
The first argument to $.get is the URL which will respond with the expected data. jQuery/JavaScript don't care what kind of server side architecture you have or the scripting language. Whether the URL looks like a file AddItem.cshtml or a friendly route like /User/Sandeep, it doesn't matter as far as the client side is concerned.
In the case of ASP.NET, your URL endpoint can be generated like so:
$.get('#Url.Action("SomeAction", "SomeController")', function (data) {
Related
I want to create a web app like google sheets in jQuery, but when I try to get a <select> value with $(select).val() I get `null.
I tried to put the code into $(button).click() and then it worked so I think the problem is that Javascript is executed before HTML, but I am not sure.
$(function() {
$.post("getTablesName.php", function(data) {
$("#tables_SCT").html(data);
});
var name = $("#tables_SCT").val();
$.get("getTable.php", { name: name }, function(data) {
$("#columns").html(data);
});
)};
I just want to get the $("#tables_SCT").val().
You will need to put the var name = $("#tables_SCT").val(); line inside the first AJAX callback. As it stands your code is trying to read content which doesn't yet exist in the DOM as the request which fills the option elements is asynchronous.
You will also need to make the second AJAX call from this point too, for the same reason. Try this:
$(function() {
$.post("getTablesName.php", function(data) {
$("#tables_SCT").html(data);
var name = $("#tables_SCT").val();
$.get("getTable.php", { name: name }, function(data) {
$("#columns").html(data);
});
});
)};
I have two scripts, first of them clicks on the button and after that browser opens a new window, where i should click on the other button by the second script, is it possible to run them both at the same time, I mean like unite those scripts together?
function run() {
var confirmBtn = document.querySelector(".selector,anotherSelector ");
}
after this new window appears and here`s the second part of my script
var rooms = document.querySelectorAll(" .btn-a-offers");
console.log(rooms);
for (var room = 0; room < rooms.length; room++) {
rooms[room].click();
}
var prices = document.querySelectorAll(" .li-right-side>strong");
console.log(prices);
for (var price = 0; price < price.length; price++) {
}
var prices = [];
document.querySelectorAll(".new-pa-hotelsoffers .li-right-side > strong").forEach(function(price) {
prices.push(parseFloat(price.innerHTML.replace(/[^0-9.]/g, "")))
})
console.log(
Math.min(...prices).toFixed(2)
)
My English is not that good so I want to be sure that I explained everything right, second script must be executed in the new window, that opens after first script
Depending on the logical dependancy of your application and the use of the functions, you could execute the second function in a document.ready function on the second page.
Example:
<script>
//jQuery
$( document ).ready(function() {
secondFunction();
});
//Pure JS
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
r(function() {
secondFunction();
});
</script>
However, if the page is to act independantly, and the second function is only to respond upon the execution of the first function, then that solution would not be the one you are looking for.
In the case where the function has to act entirely dependant on the use of the first function you could parse a value in the URL (better known as a GET variable) and check if that value is set.
Example:
<script>
functionOne() {
window.location.href = '/your_page.php?click=1';
}
</script>
Then on your second page you need to retrieve the GET variable.
<?php
$clicked = $_GET['click'];
?>
You can then perform a check to see if the variable has been set and fire your function upon that logic.
<?php
if($clicked != "") {
echo '
<script>
functionTwo();
</script>';
}
?>
Another way of doing it could be by the use of AJAX and have the other function execute in the AJAX' success function. That way you can eliminate the use of the GET variable, which is visible in the URL.
Example:
<script>
functionOne() {
$.ajax({
type : "POST", //or GET
url : "/your_page.php",
data : {
//parse your POST variable data if any
// variable : value,
// anotherVairable : anotherValue
// [....]
},
success: function (html) {
//Success handling
secondFunction();
}
})
}
</script>
Note that the AJAX used in the example is jQuery AJAX, so if you want to use some AJAX logic involving this structure, you'll need to include a jQuery library.
You should pass some parameter in the URL query like this:
// first-script.js
openNewWindow('http://example.com?run-second-script=1') // openNewWindow is fake function, just for demo
// second-script.js
if (window.location.search.includes('run-second-script=1')) { ... your code here ...}
I have a page displaying data from a json feed and I also have a button which loads more of the feed on click of a button. My aim is to append some content inside the page for each feed item. I have been able to create a function which does this on load of the page, but I am unsure how to make this work with the aysynchronous loading of more data.
I understand I need to use the .done() callback to make this work but need some guidance how to implement it correctly.
This function appends the new content initially:
function appendFeed() {
$('.feed__item').each(function (index) {
$feedItem = $('.feed__item', $(this));
$feedItem.append('<div class="feed-gallery"></div>');
for (var i = 1; i <= 5; i++) {
var $count = i;
if ($count > 1) {
$('.feed.gallery', $(this)).append('<div><img data-lazy="//placehold.it/50x50"></div>');
};
});
}
This is where the .done() callback is referred, on click of a button:
$('button').click(function(){
$.getJSON(uri, function (json, textStatus) {
// do stuff
}).done(function (json) {
// do stuff - in my case this would be appendFeed()
});
});
I have already called the appendFeed() function, but if I put it inside the .done() callback on click the button, then it appends the feed again. How do i prevent the duplication for the feed that is already on the page?
This is how you will write.
<script type="text/javascript">
$.getJSON("/waqar/file.php").done(function (data) {
$(".output").append(data);
});
</script>
I have a jQuery plugin in my layout page header:
<script src="#Url.Content("~/Scripts/js/kendo.web.min.js")"></script>
<script src="#Url.Content("~/Scripts/app/jsCommon.js")"></script>
<script src="#Url.Content("~/Scripts/app/Layout.js")"></script>
and my layout.js:
(function ($) {
var Layout = function (node, options) {
this.node = node;
this.options = $.extend({
url: ""
}, options);
$(this.node).find('.HButton').bind('click', $.proxy(this.HButtonClicked, this));
};
Layout.prototype = {
constructor: Layout,
_loadBackground: function () {
debugger;
//load second now 'Common.currentTarget' have been lost
$(Common.currentTarget).removeClass();
$(Common.currentTarget).addClass(".HButton_Selected");
},
HButtonClicked: function (e) {
debugger;
//load first
Common.currentTarget = e.currentTarget;
}
}
$.fn.Layout = function (options) {
return this.each(function () {
$(this).data('Layout', new Layout(this, options));
});
};
}(jQuery));
in the other side I have a share repository javascript object like this :
function common() {
}
common.currentTarget = null;
var Common = new common();
then in the other page I've triggered an event like following :
<script>
$(document).ready(function () {
var layout = $("#layout").data("Layout");
$(layout).trigger("_loadBackground")
});
</script>
when the HButton element click happened at the first I'm writing the object inside the "Common.currentTarget" and it saved successfully when I've watched variable but when another page loads completely and then trigger the event "_loadBackground" the value of "Common.currentTarget" have been lost, my question is how I can define a static variable like this to be permanent in whole of my pages?
You can set a cookie from javascript to store the data, and then access the cookie from another page. Cookies can persist just during the browser session, or you can give them an expiration. For HTML5, there is local storage.
All JavaScript data is unloaded when the page is changed or refreshed. There is no way around this in JavaScript itself. You will have to send data to the server instead. Probably the easiest way to do this is to store your data in a hidden field:
<input type="hidden" id="storable" />
....
document.getElementById("storable").value = // whatever value you want to store
Then on the server side you can transfer that data to the new page.
If you are redirecting client side, use a query parameter instead.
Is there anyway to reload just the AJAX request, so that it updates the content pulled from the external site in the code below?
$(document).ready(function () {
var mySearch = $('input#id_search').quicksearch('#content table', { clearSearch: '#clearsearch', });
var container = $('#content');
function doAjax(url) {
if (url.match('^http')) {
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var fullResponse = $(filterData(data.results[0])),
justTable = fullResponse.find("table");
container.append(justTable);
mySearch.cache();
$('.loading').fadeOut();
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
});
} else {
$('#content').load(url);
}
}
function filterData(data) {
data = data.replace(/<?\/body[^>]*>/g, '');
data = data.replace(/[\r|\n]+/g, '');
data = data.replace(/<--[\S\s]*?-->/g, '');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
data = data.replace(/<script.*\/>/, '');
data = data.replace(/<img[^>]*>/g, '');
return data;
}
doAjax('link');
});
Right now I have a button which reloads the entire page, but I just want to reload the AJAX request. Is this even possible?
Edit: I need to specify more. While it can easily call the AJAX again, can it also replace the info that is already there?
You just need to call the doAjax function again on button click...
$("#buttonID").on("click", function() {
doAjax("link");
});
Add that into the above document.ready code and set the button ID correspondingly.
Then change
container.append(justTable);
to
container.html(justTable);
In your doAjax function you append HTML onto an element. If you overwrite the element's HTML instead of appending to it then the HTML will be "refreshed" each time the doAjax function runs:
Simply change:
container.append(justTable);
To:
container.html(justTable);
And of-course you can bind a click event handler to a link (or any element) like the rest of the answers show. Make sure you bind the click event in the proper scope (inside the document.ready event handler) so the doAjax function will be accessible from the click event handler.