how to send asynchronous request to php page using jquery ajax - javascript

i am new to web development creating a kind of social networking website for college project. I want to include update the messages count in the message menu every time there is a new msg in the database for the user(like facebook message menu on homepage)
But it's frustrating learning ajax, however after searching on web and reading some topics from some books I came to the solution that i can make an $ajax call in my js file in the homepage and send data ('name'=>'user') stored in javascript cookie that i have created on loading of home page after the user login, to a php file which will search across the recent_msg table in database to fetch the recent message for the logged in user if any after fetching the php file will create the html file with code snippet and further another jquery code will append that snippet from file to the message list menu.
the PHP part is not the problem but how can i send the username to the php file using jquery ajax api, here is the code what i think i can apply but i am doubtful in that if this is the correct way
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
}
} );
},10);
});
what is the purpose of success function in the code?

data needs to be in the form of an object / key-value-pair (EDIT: or if a string, as a valid querystring). data: { name: usr }. However, since it's in a cookie, your PHP page will have direct access to that cookie. It's safer to let your session cookie tel the PHP page who the user is instead of relying on an AJAX call to tell the PHP page who it is.
http://php.net/manual/en/features.cookies.php
So I'd drop data from your AJAX call altogether, and in your PHP page, use $_COOKIE["name:"]
Then whatever HTML gets passed back from the PHP page will arrive in the data call. If it's HTML, then simply add it to your HTML to some message div, such as.
<div id="recent-messages"></div>
<script type="text/javascript">
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
$('#recent-messages').html(data);
}
} );
},10);
});
</script>

The success function executes whenever your ajax call completes successfully. This means that the page actually exists and no server-side errors occurred on the page. The variable data will contain whatever information is returned from the page on the sever /phpScripts/recent_msg.php. Generally this is either json or xml, but it entirely depends on your implementation of recent_msg.php.

If the user has to log in that means you have to have created a session. In that case you can store the logged in user's information such as their name in $_SESSION on the server and there is no need to store it as a cookie. Since $_SESSION is already on the server, there is no need to send that data via ajax in any case.

Related

Set ajax call only when the new record inserted to database

I wants to get updated comment from chat list to the page without refreshing the page, Thats I have used ajax call for the list but I have to call this function for every 5 seconds to check whether new chat is inserted or not to the database,
$(document).ready(function(){
setInterval(function(){
$.ajax({
type:'POST',
url: baseUrl+"chat",
cache: false,
data: dataString,
crossDomain: true,
success: function(data){
var getData = JSON.parse(data);
if(getData.status == "success")
{
for(i=0;i<getData.chat.length)
{
$("chatList").text("");
$("chatList").append("<span class='black'>"+getData["chat"][i].name+" : <span class='blue'>"+getData["chat"][i].comment+"</span>");
}
}
else
{
alert(getData.message);
}
}
});
},5000);
});
So I wants to know if there is any easy way to do this or from PHP MySQL it is possible to send page a new comment inserted notification ?
Best practice is to use HTML5 WEB WORKERS.
HTML5 Web Workers
The problem with JavaScript on the browser is that it runs on a single thread. In other words, two scripts or processes cannot run simultaneously. If you are processing JavaScript after page load, the end user cannot interact dynamically with the page. The JavaScript will not handle UI events while processing something else. If you process something large before page load, the end user has to wait all-together which is a horrible user experience.
You can use a websocket, socket.io for example. That will allow you to send notifications from the server to the client.
So, when you recieve data from your chat (cient) in your API (server), after updating the database, you will have to send a 'notification' to your client.
When your client get the notification, you can make your AJAX call :
socket.on('notification', function(){
doYourAJAXStuff();
});
You can use socket.io api to get real-time information to the client..

How do I reload a page without the user noticing?

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!

How to get data param on the destination page from Ajax response call

I am Opening dynamically a page using Ajax, to prevent browser refresh. It opens and it runs scripts on the destination page. but before executing the script, I want them to retrieve the parameters like request.querystring but in Javascript.
This is my code that opens the page.
function cargarPagina(para1) {
$.ajax({
url: "/tarea.aspx",
context: document.body,
data: { "p1": para1 },
type: 'POST',
success: function (responseText) {
$("#maincontent").html(responseText);
$("#maincontent").find("script").each(function (i) {
if ($(this).text() != "") {
$("#maincontent").find("#hola").val(para1);
//alert(para1); //eval($(this).text());
}
});
},
async: true
});
}
After that, the tarea.aspx opens and executes scripts blah blah.
But before executing scripts, I want to get the "para1" value that was sent within the ajax POST call.
Any help would be much appreciated.
You are doing a POST not to the page, but to a server. The server then looks at your POST and says "oh, it looks like this is the page that you are requesting", and serves up some html content. The javascript on that served up page does not have any knowledge of the original POST, or how it (the page) came to be created.
If you want to get the POST parameters into the destination page, you must handle the POST request on the server, and then write the parameters in to the output page, via ASP.net or PHP or whatever scripting language you are using.
Alternatively, you could use GET instead of POST, and then the parameters would be available in the URL

AJAX to retrieve and store object in a variable

I have two files. One is index.php where the user clicks and invokes an AJAX request. The second one is process.php whic sends back data back to index.php.
function AjaxResponse() {
var myData = 'connect=1';
jQuery.ajax({
type: "POST",
url: "process_facebook.php",
dataType: "text",
data: myData,
success: function(response){
$result = response;
window.location.replace("http://myurl.com");
}
the $result doesn't here. I can do like this $('#something').html(response); but can't store the value returned in a variable.
Kind of hard to tell what you would like here. But I'm going to guess that you want to store the result of the ajax call into a variable in php. So I'll remind you the order in which things proceed for a server/client web interaction.
Server processing ==> client side processing ==> repeat.
The only real way to store that value in a variable after receiving the data from your ajax request would be to submit a form and have your data serialized into JSON or xml and then parse it.
Alternatively, your process_facebook.php file could insert your data into a database and you could return a key to your callback, and either create a cookie on the users browser of that key, or have the browser pass that key as a get variable to your index.php (sanitize it so that a malicious user can't just go entering whatever they want), and then do what you want with that information.
To clarify, the session is not stored on the browser, it is stored on the server, you cannot set any session variables on the browser unless you did it in an ajax call to the server.

jQuery: handling mixed html/js ajax response

Having trouble accessing javascript code in a mixed html/js ajax response. jQuery ajax doc states:
If html is specified, any embedded JavaScript inside the retrieved
data is executed before the HTML is returned as a string
Which I can confirm by adding a simple snippet to the html reply:
<script type="text/javascript"> alert($(this)); </script>
How then to retain access to the js code vs. one-and-done execution?? Trying to implement a modal login (to prevent data loss on session timeout in form submission screens). Of course I need to be able to access the ajax'd js code to then validate email/password fields and ajax authenticate user credentials on the remote server.
Here's the modal login coffeescript snippet:
# submit form
$.ajax
success: (data) -> ...
error: (data) ->
popAuth(data.responseText) if(data.status == 401)
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
title: title
})
Perhaps I can add a success callback to popAuth() ajax options to store the returned js code? How about jQuery "live" handler? Unfortunate that this scenario is not as straight forward as one would hope ;-) I have seen $.getScript as an option, but would prefer to not separate html from js since server-side already assembles html + js and the original ajax call pulls it all down in one go. (i.e. avoid creating a dedicated server-side controller to send back js file content bundle)
I am of course open to alternative solutions to workaround this issue. For example, I could store login fields and js login validation code on every screen (JVM CRUD application living behind WordPress front end so every screen is basically auth required) in a hidden div, and then pop the modal login window "locally", which I assume would get around the annoying one-and-done js execution of remote ajax content.
Anyway, Ideas appreciated! client-side is both wonderfully simple and...horribly complex ;-)
Ok, fending off the veritable deluge of responses, I'll take a stab myself.
As I understand it now, since mixed html/js content is one-and-done executed, we have one chance to capture ajax response js code and bind it to current scope.
First, in the original ajax call (i.e. form submit that returns a potential 401 not authorized status) set the context of the modal login's ajax setup to $(this), the currently executing scope that contains jquery validation and other shared js code needed for modal login ajax submit to work.
In my case, using fancybox, adding context param it now looks like:
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
context: $(#)
title: title
})
Then, since the parent window contains the majority of needed javascript, the only requirement is to create a js file that binds modal login form button click event to validation and $.ajax submission.
# login.coffee
jQuery ->
$('#loginSubmit').click (e) ->
e.preventDefault()
isValid = $('#loginForm').validate().form()
if isValid
$('#spinner').show()
$.ajax
data: $('#loginForm').serialize()
success: (data) ->
$('#status').fadeOut()
location.href = '/foo'
error: (data) ->
$('#status > div').html( data.responseText )
$('#status').fadeIn()
complete: () ->
$('#spinner').hide()
Done, all good, works ;-)

Categories

Resources