I am building a messaging system for my site. The mailbox is flat, i.e. accessing the inbox, or sending a new message does not move to another page, it just toggles divs. When a user clicks a message, an AJAX call replaces the inbox div with the chosen thread. Inside the thread view, there is a form to reply to the message.
A few problems:
From inside this thread_view, which sends an AJAX response to a div nested inside the entire mailbox div, I don't have access to document objects outside of it. So, I can't manipulate divs outside of this view, such as the one that receives the AJAX beforeSend and Success messages. I think this may be accomplished with some kind of .load(), though I'm not sure exactly how.
My AJAX doesn't fire. I am using the Ajax.Form() plugin. I think this problem might be related to the first, but I can't say for certain. I'm not sure how to begin troubleshooting the Ajax request because I get no errors in the console.
I wonder if the problem has to do with the fact that I am trying to send an ajaxRequest from a view that is itself a response from a previous ajaxRequest, i.e. the entire view for the thread is a result of the following, in the same js file as the next request:
// compose a message function
$('#send_message').on("click", function(e) {
var send_message_options = {
type: 'post',
url: "/users/new_message",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#message').html(response);
}
};
$('#message_form').ajaxForm(send_message_options);
});
My new AJAX request, which does nothing:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
console.log("trying for reply");
var reply_options = {
type: 'post',
url: "/users/reply",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#reply_message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#reply_message').html(response);
}
};
$('#reply_in_thread').ajaxForm(reply_options);
});
I couldn't say why the ajaxForm() plugin failed, but a jquery $.post was successful. The code that worked below:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
var data = $(this).serialize();
$.post('/users/reply',data,function(response){
$('#reply_message').html(response);
})
});
Related
Creating a 'refresh' button via jQuery, AJAX and PHP.
This particular one I'm having control two DOM instances (divs) - #sold-container, and also #totalorderswidget.
$(document).ready(function() {
$(function() {
$('#orderfeed').on('click', function() {
var orders;
$.ajax({
type: 'POST',
url: 'liveorderwidget.php',
beforeSend: function() {
$('#sold-container').html('<div class="page-loader"></div>');
$.ajax({
url: "totalorderswidget.php",
beforeSend: function() {
$('#totalorderswidget').html('<div class="page-loader"></div>');
},
success: function(orderdata) {
// $('#totalorderswidget').html(orderdata);
orders = orderdata;
}
});
},
success: function(solddata) {
$('#sold-container').html(solddata);
$('#totalorderswidget').html(orders);
}
})
});
});
});
I didn't like how each DIV was updating and showing my page-loader CSS at different times, so I thought I'd try and grab the data to pass and display them both at the same time (get data from the first ajax call, display both on the second).
This is working as two normal AJAX calls, and each appends the success html to each id on it's own. (uncommenting // $('#totalorderswidget').html(orderdata); works),
but initializing a variable like var orders; outside the functions and trying to put the data in the success call (orders = orderdata;) does not work.
Doing a console.log on the first AJAX success call (orderdata) brings back the expected response, but trying to use it in the second AJAX call ($('#totalorderswidget').html(orders);) does not work and a console.log brings back undefined for the order variable.
What must I change in order to grab data from the first success call function and bring this data into the second/final ajax success call?
I have a PHP page which fetches data from a MYSQL database and generates HTML content based on rows returned from the database.
I am adding a new row in database on click of a button using AJAX, Jquery and PHP. After adding the new row, I am using window.location.reload(true); to reload the page. But the HTML elements corresponding to new row are not shown when I click the button. However, if I manually refresh the page using F5, the newly added content is shown.
Anyone knows why this could happen?
Below is the function which I call on click of a button. The page increaseCount.php updates database to increase the count of actors. But the HTML elements corresponding to new count are not shown until I refresh the page using F5.
function increaseCountOfNewActor(characterName) {
var actorName = document.getElementById("txt_actor_"+characterName).value;
var actorImage = document.getElementById("img_actor_"+characterName).src;
$.ajax( {
url: "increaseCount.php",
method: "POST",
data: {
name: actorName,
image: actorImage,
character: characterName
},
success: function( data ) {
alert("Vote received");
}
} );
window.location.reload(true);
}
The problem is that you are mixing ajax with a complete page reload.
The $.ajax call by default is asynchronous (the first a from ajax...). Therefore it sends a request to increasepostcount.php and then immediatelly reloads the page - not waiting for increasepostcount.php to process the request. By the time you manually refresh the page, increasepostcount.php will have completed the processing of the ajax call, therefore its result are reflected on the page.
If you use ajax, you should not use page reloading. Use javascript to update that part of the page where these records are displayed based on the results returned by the ajax call.
You need to be sure that the ajax call has done to do what you want, in your case "window.location.reload(true);" is running before the ajax response, due to asynchronous communication between Client and Server to avoid "freezing" on the screen and an unresponsive user experience.
You have to put your refresh code on Success ajax response or on done :
function increaseCountOfNewActor(characterName) {
var actorName = document.getElementById("txt_actor_"+characterName).value;
var actorImage = document.getElementById("img_actor_"+characterName).src;
$.ajax( {
url: "increaseCount.php",
method: "POST",
data: {
name: actorName,
image: actorImage,
character: characterName
},
success: function( data ) {
alert("Vote received");
// to do here
//window.location.reload(true);
}
} ).done(function () {
// or to do here
window.location.reload(true);
});
}
in your page increaseCount.php consider adding a header at the end.
For example:
if(isset($_POST['name'] &&
isset($_POST["image"] &&
isset($_POST["character"]) {
/* do your stuff here */
header("Location: /thePageYouWantToRefresh.php");
exit;
}
I've been trying to figure out how to reload a page and pull dynamic info from a server without users noticing the page has been reloaded. For instance, if I want to create a 'live' message board system when the board updates every time other people make a comment or post a message.
I noticed that Javascript has a boolean function .reload() that when set to false reloads the page from the cache and when set to true reloads the page from the server, but from what it looks like, the function does something similar to reloading the browser. Is there another way do what I'm trying to do?
Something like this...
function getContent()
{
return new Promise(function(resolve, reject){
var url = "http://yourendpoint.ext"
$.ajax({
url: url,
success: function(data)
{
resolve(data);
},
error: function(err)
{
reject(err);
}
});
}));
}
// Usage
getContent()
.then(function(data)
{
$('#some-element').html(data);
});
Are you sure you really want to do an reload?
What you could do is make an AJAX Request to the server and display the result, without even reloading the Page. I would recommend using jQuery for this, just out of comfort.
AJAX stands for Asynchronous JavaScript and XML. In a simple way the process could be:
User displays page, a timer is started
Every 10s (or 20s or whatever) you do an AJAX Request using JavaScript, asking the server for new data. You can set a callback function that handles the result data.
Server answers with result data, your callback function inserts the new data.
Code Example (taken from jQuery Docs):
$.ajax({
method: "POST",
url: "target.php",
// Data to be sent to the server
data: { name: "John", location: "Boston" },
// success will be called if the request was successfull
success: function( result ) {
// Loop through each Element
$.each(result.newElements, function(index, value) {
// Insert the Element to your page
$('.classOfYourList').append(value);
}
});
});
Just set the proper endpoint of your server as the target and insert whatever you want to do in the success function. The function will get an answer containing whatever you sent to it from the server. More Information in the jQuery Documentation:
You can Achive what you want using AJAX. you can use ajax with either javascript or jquery. You can load the content you want dynamically without reloading the entire page. here is a quick example.
Here is a <div> with id load where your content will be loaded.
<div id="load">Loaded Content:</div>
<button id="load_more">load more</button>
JQuery to request for the data, where getdata.php is the php file which will send data you want to display.
<script type="text/javascript">
$(document).ready(function(){
$("#load_more").click(function (){
$.post("getdata.php", {variable1:yourvariable, variable2:ifneeded},function(data){
//data is the string or obj or array echoed from getdata.php file
$('#load').append(data); //putting the data into the loaded div.
}
});
});
});
</script>`
finally getdata.php file
<?php
//fetch data from Databas eif needed. or echo ut what you want to display in the div.
echo "This is a small example of using JQuery AJAX post request with PHP.";
?>
Hope that helps!
I want to count number of click to particular div(#counter) and then redirect to a different site.
I did a ajax call on click event of the div with the id counter. and then on success function i'm doing a redirect on ajax complete. Here is the code
jQuery('#counter').click(function(){
var data = { clicked:'yes'
};
jQuery.ajax({
url:"stat.php",
type:"POST",
data:data
}).done(function(res){
window.location = "http://www.myurl.com";
});
});
The thing is, this is making some time to redirect such that user have to wait until the ajax complete event trigger.
Since am not care of the response i just need a request that initiates user has clicked that(#counter) div so i'll just increment the value in DB. So is there a way to redirect to a different website as soon as the ajax started? I don't want the user to wait for the response and then redirect. because the response is not needed in this case. This is only for site stat or what is the best way to count a button click and then redirect them to a different site.
Edit, updated
Try
jQuery('#counter').click(function(){
data = { clicked:'yes'
};
var redirect = function() {
setTimeout(function() {
window.top.location.href = "http://stackoverflow.com/questions/"
+ "25554598/"
+ "how-to-perform-a-count-statistics-"
+ "without-wait-for-ajax-response/";
}, 1500); };
$.when(jQuery.ajax({
url:"/echo/json/",
type:"POST",
data:{json:JSON.stringify(data)}
}), redirect())
.done(function(_data) {
alert(_data[0].clicked)
})
});
jsfiddle http://jsfiddle.net/guest271314/51g5huvq/
Just move your redirect code outside of the .done callback. This way, when you click, two things are instantly done : an ajax request is sent, and the redirection is fired. You can wrap the redirection in a short setTimeout to make sure the ajax request has been fired before redirecting the client.
jQuery('#counter').click(function(){
var data = { clicked:'yes'
};
jQuery.ajax({
url:"stat.php",
type:"POST",
data:data
}).done(function(res){
});
setTimeout(function(){window.location = "http://www.myurl.com";}, 500);
});
using ASP .Net MVC 4.0 , vs10 , MSSQL 2008
I have a stored procedure, which is executed in one of my page. it generally takes 30 to 50 second to execute. I want to show a alert dialogue where an gif image will be loaded during this process time. I am executing stored procedure with sqlcommand. The process started on clicking Process button. after finishing the process, the page returns another view.
I have poor knowledge of javascript, so please show me a simple way.
EDIT:
Is it possible to show an image on buttonclick an do other codebehind process?
Like:
<script type="text/javascript">
function showImage() {
document.getElementById('Processing').style.visibility = visible;
}
</script>
<div id="progessbar">
<img alt="Processing" src="../../Images/Processing2.gif" id="Processing" style="visibility:hidden"/>
</div>
It will be difficult to accomplish what you're trying to do in a traditional MVC fashion since the request takes a long time. This is better accomplished using AJAX which processes your request asynchronously. I recommend also using jQueryUI dialog or any modal to show a progress indicator, or even any custom JS.
I like jQuery BlockUI personally to create the modal for me but that's just a preference.
/** Using a wrapper to show/hide the progress indicator.
Swap the blockUI with any library or custom JavaScript for displaying the progress indicator.
*/
var showProgress = function() {
$.blockUI({ message: '<img src="progressImage.gif" />' });
};
var hideProgress = function() {
$.unblockUI();
;}
/** Trigger to submit the form */
$('#submit').click(function() {
/** Show an indicator before making an AJAX request*/
showProgress();
$.ajax({
url: '/someEndpoint',
data: $.toJSON({/* some JSON param */}),
type: 'POST',
dataType: 'json',
timeout: 50000 /** Override timeout in ms accordingly */
}).done(function(data){
/** Remove the indicator once the request has succeeded and process returned data if any. */
hideProgress();
});
return false;
});
Use ajax for your process. It ll make the parallel processing for "showing gif" and completing your desired code.
You can use JQuery-AJAX with page methods this way: [1]: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
The success callback contains a parameter with the returning data.
or you can try simply this
var actionURL = "(Your disired action e.g /index.jsp)"
$.ajax({
cache:false,
url: actionURL,
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=UTF-8' );
$("#progessbar").show();
//Here you can write any code to execute before the action like gif loading etc
},
success: function( data ) {
alert("Success Conditions");
//"data" is what u gets from your target. You can see by alert(data); here
//Here you can write any code which you want to execute on finding the required action successfully
},
complete: function(){
alert("Complete Conditions");
$("#progessbar").hide();
//Here you can write any code which you want to execute on completion of the required action you given in actionURL
},
error: function(){
alert("Error Conditions");
}
});
NOTE: alerts are just for explanation, you can write your own code also
For this code you have to include jquery plugins. which can be downloaded from their official site [l]: http://jquery.com/