downloadinga file using ajax and iframe - javascript

I am using the below code to get all the names of the checkboxes and passing them to download a file from the server, before my edited code i was using window.location.href and it was working well but with few checkboxes, if i send like 400+, it throws an 500 error
here is my code
jq(document).on('click','#downloadAnsdoc',function() {
var checkedVals = jq('.allchecks:checkbox:checked').map(function() {
return this.value;
}).get();
checkedVals.join(",");
var iframe = $("<iframe/>").attr({
src: 'doc/fetch.cfm?action=catAnsDownload&tx_ID='+checkedVals,
style: "visibility:hidden;display:none"
});
});
and my previous code was
jq(document).on('click','#downloadAnsdoc',function() {
var checkedVals = jq('.allchecks:checkbox:checked').map(function() {
return this.value;
}).get();
checkedVals.join(",");
location.href = 'doc/fetch.cfm?action=catAnsDownload&tx_ID='+checkedVals;
});
the above code was working but passing a big list was creating a problem.
now to solve this, i am trying to send the data as post and make an call to an iframe so it pass all the ids to the database and bring the records and download through an iframe, but my changed method, when i click my button, nothing happens, it does not display any kind of issue, not it does anything

Related

Browser network trace showing JSON post creating same file/link for every posting JQuery

I am using Json post method to get data from controller and display the data on Razor view page using dropdown list. When I am tracing browser network tab, I can see it is creating and keeping every post request and increasing the file size. I am new for JQuery. My question is, there are any way I can remove the previous post. Please see the image file below where I posted twice from dropdown list. I always want to keep the last post.
Please click to see the image
My JQuery code is -
$(document).ready(function ()
{
$('#ddl2').change(function (e)
{
e.preventDefault();
var data1 = {str_test: str_test };
var url = '#Url.Action("ddl_2")?id=' + id;
$.post(url, data1, function (data)
{
$('#nav_div').html(data);
});
});
});
Thanks
Either you're posting multiple time or you've called the same function with same selector each time. You could post your JS logic code here to debug correctly otherwise assumption answer aren't helpful.

onclick() function is not working with Jquery?

So yesterday, I added some Jquery code and it worked perfectly. Today I was adding some more for a new part of my website and it did not work. When I tried the code I added yesterday, that stopped working as well. The first thing I do is create a function to get anything from the url that I need. The first 2 inputs are for following users. The first input should send the id variable to the url bar and is retrieved in the php file called follow.php. The second input should do the same thing. Finally the last function is for liking peoples posts. It sends the type of like(like or unlike) to the php file named like.php and is retrieved there. And should post the retrieved data into a div called likes. However, none of which is occurring when the buttons are pressed. Even when I just send an alert to make sure the on click is working, nothing happens either.
Here is my code:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$('input#sub').on('click', function(){
var id = getParameterByName('id');
$.get('follow.php' , {id: id}, function(data){
location.reload();
});
});
$('input#sub1').on('click', function(){
var id = getParameterByName('id');
$.get('unfollow.php' , {id: id}, function(data){
location.reload();
});
});
function doAction(postid , type){
alert("Works");
$.post('like.php' , {postid: postid type: type} , function(data){
$('div#likes').text(data);
});
}
Let's try to sum things up. I'm gonna change most of your code simply because you don't need all of that, otherwise jQuery wouldn't be helpful at all.
Assuming your caller is this anchor:
<img id="like" src="Social/down.png"/>
After this you can manipulate the clicked object getting its attributes easily through:
$('.idsfromdb').click(function(){
var id = $(this).prop('id');
var another_id_obj = $('newselector').prop('id');
// more logic, ajax,...
});
You can attach this kind of functions to every click event and then manipulate the object, call a php file, and so on... I hope I helped you somehow with this.
open google developer tools > network and see if request is made and if it has all data you want as request and if there is anything in response.
if there is request with all parameters, you have problem on server side,
if parameters not same that you are trying to send with ajax, than prevent buttons default action, you must prevent it every time when using ajax especially when button submits form.
$('input#sub').on('click', function(event){
event.preventDefault();
//your ajax
}

jQuery function that call controller method from client side every 10 seconds mvc razor

I got a problem that i cannot solve cause of my incomplete knowledge of jQuery/Java syntax but which problem can be fast solved by someone with more experience than me.
I want to build a simple script to run on client side that will call a controller method every 10 seconds (method is responsible for receive data from message server)
all i do so far is search web and more i read more i get confused..
basic need are
use jQuery ( there was a tip that says it is best choice)
call method every 10 seconds
method i want to call is: "callGetMessagesFromClientSide" and it's in CoordinatorsController
<script src="~/Scripts/jquery-2.1.1.js" type="text/javascript"></script>
<script>
var callETs = setInterval(function () { callMessages() }, 10000);
function callMessages()
{
var url = #Url.Action("callGetMessagesFromClientSide", "Coordinators")
$.get(url);
}
</script>
You need to wrap generated URL in quotes.
Use
var url = '#Url.Action("callGetMessagesFromClientSide", "Coordinators")';
instead of
var url = #Url.Action("callGetMessagesFromClientSide", "Coordinators")
Rest of your code should work.
function callMessages() {
var url = '#Url.Action("callGetMessagesFromClientSide", "Coordinators")';
$.get(url, function(response) {
//Perform some operation in the callback if require
});
}
You're most of the way there, try this:
function callMessages()
{
var url = '#Url.Action("callGetMessagesFromClientSide", "Coordinators")';
var update = $.get(url);
update.done(function(response) {
//handle server response
});
}
depending on what the server returns (e.g. JSON, HTML etc) depends on how you handle it

Extract piece of ajax request using jquery get

I'm struggling to get this get request to cooperate. I would like to begin by saying that the PHP side flawlessly. I am now trying to use ajax and jQuery to make it look smooth.
Here is the js:
$(".controls a").click(function(e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
$(".schedule").fadeOut(200, function() {
$(this).html(data).fadeIn(200);
});
});
});
$(this).attr("href") refers to a URL that is passed in order to get information from a MySQL database (e.g. hours.php?week=2014-08-11). The value passed in week is updated via PHP every time a link is clicked.
Here is what I get from console.log(data) http://pastebin.com/bGpfjq6r
I've tried converting data (raw HTML) into a jQuery object by doing the following:
var $data = $.parseHTML(data);
However, this just coverts the HTML into an array. I can perform a find for the element:
console.log($($data).find(".schedule"));
but when I view the output of this the context is undefined.
I also tried the accepted answer in this question Extract part of HTML document in jQuery with no avail:
var foo = $(".schedule", $data);
console.log(foo);
This still has an undefined context.
Ideally, I want to grab just the information in .section and replacing the current in .section with the information captured from the GET request. .section is part of the document as well as what is returned from the request.
There are no errors in the console. jQuery version is 1.11.1.
My apologies if the question is poorly written. I tried to write it in a general way so it may apply to other people too. Let me know if you need additional information.
Try using jQuery filter() function.
$(".controls a").click(function(e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
$(".schedule").fadeOut(200, function() {
// apply filter function here to find new schedule div
var newSchedule = $(data).filter(".schedule").eq(0).html();
$(this).html(newSchedule).fadeIn(200);
});
});
});
Try wrapping the response so you can parse it...
$(document).ready(function() {
// Create named function to Initialize the on click event capture
function initAJAX() {
$(".controls a").click(function(e) {
e.preventDefault();
$.get($(this).attr("href"), function(data) {
var response = $('<div>' + data + '</div>');
var contents = response.find('.schedule').html()
$(".schedule").fadeOut(200, function() {
$(this).html(contents).fadeIn(200);
// After we get the content updated, we have to reinitialize those new anchors
initAJAX();
});
});
});
}
// We have to call this once to start or nothing will happen
initAJAX();
});

How to pass data from one HTML page to another HTML page using JQuery?

I have two HTML pages that work in a parent-child relationship in this way:
The first one has a button which does two things: First it requests data from the database via an AJAX call. Second it directs the user to the next page with the requested data, which will be handled by JavaScript to populate the second page.
I can already obtain the data via an ajax call and put it in a JSON array:
$.ajax({
type: "POST",
url: get_data_from_database_url,
async:false,
data: params,
success: function(json)
{
json_send_my_data(json);
}
});
function json_send_my_data(json)
{
//pass the json object to the other page and load it
}
I assume that on the second page, a "document ready" JavaScript function can easily handle the capture of the passed JSON object with all the data. The best way to test that it works is for me to use alert("My data: " + json.my_data.first_name); within the document ready function to see if the JSON object has been properly passed.
I simply don't know a trusted true way to do this. I have read the forums and I know the basics of using window.location.url to load the second page, but passing the data is another story altogether.
session cookie may solve your problem.
On the second page you can print directly within the cookies with Server-Script tag or site document.cookie
And in the following section converting Cookies in Json again
How about?
Warning: This will only work for single-page-templates, where each pseudo-page has it's own HTML document.
You can pass data between pages by using the $.mobile.changePage() function manually instead of letting jQuery Mobile call it for your links:
$(document).delegate('.ui-page', 'pageinit', function () {
$(this).find('a').bind('click', function () {
$.mobile.changePage(this.href, {
reloadPage : true,
type : 'post',
data : { myKey : 'myVal' }
});
return false;
});
});
Here is the documentation for this: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You can simply store your data in a variable for the next page as well. This is possible because jQuery Mobile pages exist in the same DOM since they are brought into the DOM via AJAX. Here is an answer I posted about this not too long ago: jQuery Moblie: passing parameters and dynamically load the content of a page
Disclaimer: This is terrible, but here goes:
First, you will need this function (I coded this a while back). Details here: http://refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/
It converts request parameters to a json representation.
function getParameterMap () {
if (window.location.href.indexOf('?') === (-1)) {
return {};
}
var qparts = window.location.href.split('?')[1].split('&'),
qmap = {};
qparts.map(function (part) {
var kvPair = part.split('='),
key = decodeURIComponent(kvPair[0]),
value = kvPair[1];
//handle params that lack a value: e.g. &delayed=
qmap[key] = (!value) ? '' : decodeURIComponent(value);
});
return qmap;
}
Next, inside your success handler function:
success: function(json) {
//please really convert the server response to a json
//I don't see you instructing jQuery to do that yet!
//handleAs: 'json'
var qstring = '?';
for(key in json) {
qstring += '&' + key + '=' + json[key];
qstring = qstring.substr(1); //removing the first redundant &
}
var urlTarget = 'abc.html';
var urlTargetWithParams = urlTarget + qstring;
//will go to abc.html?key1=value1&key2=value2&key2=value2...
window.location.href = urlTargetWithParams;
}
On the next page, call getParameterMap.
var jsonRebuilt = getParameterMap();
//use jsonRebuilt
Hope this helps (some extra statements are there to make things very obvious). (And remember, this is most likely a wrong way of doing it, as people have pointed out).
Here is my post about communicating between two html pages, it is pure javascript and it uses cookies:
Javascript communication between browser tabs/windows
you could reuse the code there to send messages from one page to another.
The code uses polling to get the data, you could set the polling time for your needs.
You have two options I think.
1) Use cookies - But they have size limitations.
2) Use HTML5 web storage.
The next most secure, reliable and feasible way is to use server side code.

Categories

Resources