I use Jquery-ajax calls to post information to a page and display the returned info. The problem I encounter is the following:
When a user makes the first ajax call everything seems normal. When a user does not reload the page and makes the same request for a second time the post-call is made 2 times and the get-call as well. The 3th time there are 4post+4get requests. 4th time 8Post/8Gets. And so on.. until the browser (firefox latest v.) freezes for a while.
I'm a beginning programmer and I don't know what the cause might be. I don't know where to look inside my code. Prehaps you guys can give me a hint. My other ajax requests are fine and only post+get once.
Firebug log:
This is a piece of my code:
$(document).ready(function() {
$('#datepicker').change(function()
{
sendDate($('#datepicker').val());
});
});
function sendDate(str)
{
$.ajax(
{
type: "POST",
url: "manage_processor.php",
data: { chosendate: str },
success: function(data)
{
$('#printdiv').html(data);
}
});
}
Hope anyone can shine some light on this situation.
If I might venture a guess, I suspect the returned data contains a script tag referencing your javascript file. This would explain the GET request you are seeing. Every time the request data is put into #printdiv your script is loaded again and an identical javascript handler would be bound to the same event. This would explain the number of handlers doubling after every request.
Quick test: put console.log( 'script loaded' ); at the top of manage_functions.js. If I'm right it will log after every request.
Related
I am new to AJAX here. How can i replace the initial php function after the action of ajax is execute? I have found that the page will not refresh after the action is execute.
Here is the code:
javascript
function set_ddm(another_data) {
var result = $.ajax({
url: '../display/ea_form_header.php',
type: 'POST',
data: {
action: 'set_ddm',
Data_store: another_data,
},
success: function(data) {
console.log(data);
}
}).responseText;
}
php code
<td>
<?php
//initial function (customized drop down)
print ddm_jsfunc_employee("employee_list",$employee_list)
set_ddm(data);
if($_POST['action'] =='set_ddm') {
$employee_list=$_POST['Data_store'];
$employee_list_decoded = json_decode($employee_list,true);
//expected this function to replace the initial function after ajax was called
print ddm_jsfunc_employee("employee_list",$employee_list_decoded);
} ?>
</td>
I expect the function will replace the initial function and show in the main page but it only show in console after ajax(page aren't refresh to show it). Is there any wrong with the code or any solution for this? (the ddm_jsfunc_employee must be there to print the drop down)
thanks in advance
From ajax success callback you have to set that response in the html to view on web page.
like this:
$('.elementClass').html(response);
i hope this will works for you.
I think you have a slight misunderstanding about what AJAX is, it is not something to replace your PHP code with, but to asynchronously get data and update your webpage without reloading.
Let's first take a look at the .ajax function specifically interesting for us now is the .done() callback method, because JavaScript does the request realtime (async) JavaScript does not know when the request is done. But it allows us to specify a function inside the .done for it to call when it is done.
A really simple example would be:
$.ajax('https://stackoverflow.com')
.done(function(data) {
// We can do what we want with the data here.
console.log(data);
});
Now when the request is done the function we defined in .done will be called, in this case a simple log. But you would want to change this to a function that updates your HTML.
I also see you are calling JavaScript functions in your PHP, this will not work as PHP runs on your server but JavaScript runs in your browser. (Unless you use node or the likes)
Just a tip; it is advised to place JavaScript at the bottom of your HTML page as JavaScript is blocking content. (proper link explaining needed here)
Meaning your browser will stop parsing the HTML and run the JavaScript as it finds it.
Long story short, if you want to replace the PHP code, you would have to remove it. Make a PHP script which gives you your data. AJAX call it and then use .done or success and update your webpage from there.
I've got a TinyMCE implementation that works somewhere around 80-90% of the time, but for that last percent, the content of the editor fails to populate - for lack of better phrasing.
Effectively, upon page load, a jQuery AJAX call reaches out to a PHP page that grabs some content from my database. Upon retrieval, I set the value of the TinyMCE instance to the content of the response. I've gone a few rounds with this, first with a custom AJAX build, and recently a jQuery build. In both cases I get about the same results - that the editor loads, the content comes back from the server, and every once in a while, the text area ends up blank.
The latest attempt at this is much shorter than the earlier ones, but either way, I still end up with effectively the same result. I've also tried repainting the TinyMCE instance after the content is loaded to no avail.
The result of the two console logs are identical - and the expected response from my server - even in the case of a failure. So the value IS getting set, but the content is not visible.
function LoadAgenda()
{
$.ajax(
{
url: 'http://www.example.com/agenda.php?AgencyID=' + AgencyID + '&date=' + AgendaDate,
cache: false,
dataType: 'html'
})
.done(function(Response)
{
console.log(Response);
$('#AgendaContent').val(Response);
tinyMCE.execCommand("mceRepaint");
console.log($('#AgendaContent').val());
});
}
And finally, for the record, I'm using TinyMCE 4.1.6.
If anyone needs more information than this, I'm happy to oblige.
What happens first? The editor getting loaded or the ajax call completing? If your ajax call is happening after the editor is loaded, I don't think .val() is going to work, since it's no longer a simple textarea after TinyMCE initializes it. Try this:
Make the ajax call only after the editor is initialized
Change .val() to setContent()
Preface
For this question, I have a MVC partial view. The view has a section which displays a list of documents. Each document has a hyperlink: when clicked, the hyperlink takes the user to a second page view displaying additional information.
The link is inside an unordered list:
<a style="text-decoration:underline;" onclick="sendToDocketSearch('#currentDocument.DktYear','#currentDocument.DktSequence','#currentDocument.DktSubActionID');">#currentDocument.DktYear.ToString().PadLeft(2, '0') - #currentDocument.DktSequence.ToString().PadLeft(5, '0')</a>
When the user clicks the link, it takes them to a sendToDocketSearch javascript function (to prepare to search for the document):
var sendToDocketSearch = function (yearOfDocket, sequenceOfDocket, dktSubActionIDOfDocket) {
jQuery.ajax({
type: "POST",
url: "#Url.Action("DocketSearchOnDemand")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ docketYear: yearOfDocket,
docketSequence: sequenceOfDocket,
DktSubActionID: dktSubActionIDOfDocket,
userIsAuthorized: '#Model.userIsAuthorized' }),
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
submitForm();
}
Note that the page/view/form is submitted after the following controller method is run:
public ActionResult DocketSearchOnDemand(string docketYear, string docketSequence, decimal DktSubActionID, bool userIsAuthorized, PortalIndexView viewmodel)
{
System.Web.HttpContext.Current.Session.Add("userIsAuthorized", userIsAuthorized);
string docketSearch = docketYear + "-" + docketSequence;
System.Web.HttpContext.Current.Session["DocketSearchOnDemand"] = docketSearch;
if (DktSubActionID > 0)
{
System.Web.HttpContext.Current.Session["DktSubActionID"] = DktSubActionID.ToString();
System.Web.HttpContext.Current.Session["searchingCustomID"] = true;
}
else
{
System.Web.HttpContext.Current.Session["DktSubActionID"] = "1";
System.Web.HttpContext.Current.Session["searchingCustomID"] = false;
}
return View(viewmodel);
}
The above controller method runs; then, because the form is submitted, the HttpPost action for the page takes place. When running it on my local PC, the link is clicked and the next page is loaded without drama.
Problem
The problems start when I upload the code to the dev/test server. I don't know how to use breakpoints while troubleshooting an active website, so I follow along with the browser developer tool to monitor network traffic.
When clicking the link when running the website on my localserver, the process continues:
the hyperlink takes me to a method where I pass information to be searched
the page/view/form is submitted
the controller redirects where I have to go.
When I click the link on the site and it's on the server, the first click is completely ignored - network traffic shows that it tries to navigate to the controller via the javascript function above, but the failure happens so fast I can't even take a screenshot of it. The page reloads a second time at this point.
When I click on the same link a second time, it works without fail.
I believe the view/javascript/controller code works because it works the second time (and on subsequent attempts). It just flagrantly fails the first time on the server; after that, the user is fine. I'd like to prevent that "first-time" failure, however, and I'm wondering what the problem could be...
Bad timing
I may be passing the information too early (or too late for my website/server to process it properly). The page does it correctly the second time, so maybe I'm just "jumping the gun" by not waiting a little longer for page-loading processes to sort themselves out. (Maybe I can fiddle around with the $(document).ready() javascript portion of the first page to "delay" allowing people to click a link.)
Code error
I'll be glad to admit bad code if I'm genuinely messing something up. Maybe it's my javascript function, or maybe it's the code in my controller; at any rate, something is making the first pass of that function call be rejected. Maybe my code is bad because the problem doesn't happen the second time, and I'm getting a false sense of security (i.e. there are problems with my code that the system is willing to forgive after the page has thoroughly loaded).
Server problem/miscellaneous
I'm wondering if I missed something when I uploaded my latest changes, or if I should have contacted my network team in case there are permissions that need to be activated for the site to work smoothly. I'm already in touch with them regarding something else, so I might take advantage of the opportunity today.
There is an alternative in place that could help me prevent this problem from happening, but I want to find out why the "first-time" failure happens. Other similar actions fail the first time on the site, and I'd like to apply the insights from fixing this issue to them.
Thank you for looking at this issue. Have a great day.
Are you sure you want to call submitForm(); before your jQuery.ajax has finished? your ajax call is async so it will hit submitForm(); before it has had time to finish. should submitForm(); be in your success event instead?
This question already has answers here:
Fire Greasemonkey script on AJAX request
(2 answers)
Closed 3 years ago.
I'm using greasemonkey with Firefox to alter what content is displayed when I visit a particular domain. One of the pages contains a dropdown with two elements, let's call them element0 and element1. Whenever it detects a switch from one to the other, it performs an ajax query that alters the page content depending on which one you've selected. So it looks something like this:
$(".dropdown").change(function(){
if($(this).val()=='element0'){
$.ajax({
// fetch some html
});
}
else{
$.ajax({
// fetch some other html entirely
});
I'm happy with what is displayed when element0 is selected - it's element1's associated content I want to alter. So I need a way to trigger my own userscript function only in the second case. I also somehow need it to execute only after the ajax query is complete of course. How do I do this?
I have some basic experience with programming, but know absolutely nothing about jquery, ajax, json etc etc. A friend helped me locate the above ajax for that page so that I could even post a meaningful question. Please bear my level of experience in mind, because I'd really really like to move forward with whatever knowledge/wisdom you guys can offer, but will only be able to do so if I understand it.
Many thanks!
EDIT: The above is javascript that the host is running. I accessed it by saving the page and looking around manually. I am writing userscripts on the client side to alter what my browser displays. So I want to write my own function that responds to their js in the way I described.
AJAX
In ajax you have a tow useful method,
success & compleate
success: with execute if ajax request are work truth
complete: are work when finished ajax function, so you can use this method
example:
complete: function(){
// call another ajax, hide somthing, do any somthing
},
another example:
var all_data = {'user':txtuser,'pass':txtpass};
$.ajax ({
url:"ajax.php",
type:"post",
data:all_data,
beforeSend:function(){
// do somting before send a data
},
statusCode:{
404:function(){
$("#ma").html("Page not found");
},
401:function(){
$("#ma").html(".....");
}
},
success:function (data) {
$("#ma").html(data);// if sucsess
},
complete:function(){ // when complete
$("#user").hide(2000);
$("#pass").hide(2000);
$(".q").hide(2000);
}
});
I have a situation where I need to increase the number of time article has been read.
Once someone opens an article it should be reflected in the database by incrementing number of reads by one. Simple.
Sending POST request to the server increments the number of reads by one. The article in question is supplied via URL parameter.
Doing it manually by typing the URL in a browser works as expected. So server side is not at fault.
My problems start with the javascript side of it or rather jquery. I hook the event to the article link. So every time a user clicks on the article link it increments the number of reads like so:
$('#list-articles .article-link').click(function(e){
var oid = $(this).parent().parent().attr('data-oid').toString(); //Get the article id
$.post( "/articles/viewed/" + oid );
});
Now this does not work! Number is not increased.
I don't prevent default action since I need the link to actually open and display the article.
Now if I put an alert right after the post like this:
$('#list-articles .article-link').click(function(e){
var oid = $(this).parent().parent().attr('data-oid').toString(); //Get the article id
$.post( "/articles/viewed/" + oid );
alert(oid);
});
This variant works. After I dismiss the alert window, the number is incremented. Why is this so?? How can I fix this to actually work without the alert event present?
UPDATE
Thank you for helping to solve this. All answers are great and help one way or another. The only variant that works so far is disabling async on ajax call. It would be great if someone could elaborate on why switching the async mode off in ajax fixed it. So the post request in the original was never executed? If I was simply checking too early and the number increase was not visible upon page load, it should be still visible on the next page reload, right? SInce it wasn't updated on the database at all I assume that post was not run at all. Why is this so? I want to understand the issue so I do't get into this problem again. Thanks.
Your problem could be due to $.post being asynchronous and you checking this too soon and try posting synchronously:
$.ajax({
type: 'POST',
url: "/articles/viewed/" + oid,
async:false
});
Prevent default. Wait for the response from the server to say incrementing article reads by 1 was successful, then redirect to the article.
If it works with the alert in place it sounds like a race condition.