HTML5 request response webservice - javascript

I am pretty new to html5 web development
I have created a page with login and password on it and have a submit button.
On submit , I send a rest request to the server which has a url
THE RRQUEST IS SOMETHING LIKE THIS
<USERNAME>
abc
</USERNAME>
<PASSWORD>loooik
</PASSWORD>
which is in js file as var data...
This request is set as
var parameters=JSON.stringify(data);
I use the following code for establishing connection
xmlHttp.open("post",url,true);
XmlHttp.setRequestHeader("Content-type","application/json);
xmlHttp.send(parameters);
xmlHttp.onreadystatechange=function X()
{
if(xmlHttp.readyState==4)
{
alert(xmlHttp.responseText);
}
}
return true;
}
I need to add a loading element and want to display the next screen between request and the response. How can I achieve it?
In tag I have used submit input type where onClick attribute calls return sendPost() method which has the request to be called
How should I proceed for the same... having loading screen and getting the response ... suppose just the name to be displayed on next html screen

First of all see basic jQuery example. This will guide you through how jQuery works and help a lot in the solution I'm going to suggest.
http://learn.jquery.com/about-jquery/how-jquery-works/
jQuery has it's own AJAX method and further shorthand called $.post
Now you can write something like this -
function requestNetwork() {
// Code for loading screen
$.ajax({
url: "yourURL",
data: "yourData"
}).done(function(data) {
alert(xmlHttp.responseText);
// Code for dismissing loading screen
}).fail(function(data) {
// Code when call fails
}).always(function() {
// This code will always run
});
}

Related

How to execute a php file into jquery without post and get method?

I'm trying to program a custom contact content manager in HTML/CSS with PHP/mySQL/Jquery to make it dynamic.
I have my login form which send the $_REQUEST to my connection.php, when the auth is correct, I return json to my Jquery and when it is good, I use window.location.replace to redirect the user to the control panel.
When I'm on the index.php of the control panel, I want to check if the user's session_id is into my sql database and if it exceeded the expiration time.
I have my functions which check this and return the good value but I want to execute it and send the result to my jquery without using GET or POST method.
If I remember, you have
$.ajax({
type: "POST", //or GET method
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function({
}),
error: function({
})
});
But you must specify the element "data" no? can I use it without data and put "file.php" as url without POST or GET method?
I want to get into my success method the result of my php functions :
if the json return false, the user can access the page.
if the json return true, I will logout the user and redirect him to the login.php
I'm doing this system because I don't want anybody can access the control panel by writing the correct url or after 4 days.. I put an expiration time to one hour (for the moment) for anybody who login into the control panel and I check on all page that the expiration time isn't exceeded.
I saw that using 'window.location.replace' doesn't allow to return to the previous page.. has anyone a solution? I don't want to have an event to redirect the user, only redirect him to another url (my file.php) after a condition.
Currently, I use it to execute php without POST, GET method with $.ajax..
$(document).ready(function(){
$(function(){
var ticket = '<? echo $tickets; ?>';
console.log(ticket);
if ( ticket === '' )
$(".new_ticket h2").after('<p>Aucun nouveau ticket.</p>');
else
{
console.log('else');
$(".new_ticket h2").after('<p>Il y a un ticket.</p>');
}
});
});
I have a last question, when I write :
$(document).ready(function(){
$(function(){
}
Is it directly executed by jquery when the DOM is ready? can I write mutliple '$(function(){}' in a file ?
Thanks for the help!
What is the problem with using POST or GET? It works perfectly fine.
Here foobar.php returns a json object with status in it. Change it to whatever your script return.
$.post('foobar.php', function(data) {
if( data.status === false) {
//All good
}else {
//Redirect
window.location.href = "http://newpagehere.com/file.php";
}
});
With window.location.href you will be able to use the back and forward buttons.
And yes, when using $(document).ready(function() { }); it runs when the DOM is ready.
http://api.jquery.com/ready/
One last thing is that I would not rely on Javascript here, I would do all checking with PHP instead when the user changes page. I would also handle the redirection there.

Questions about responseText

Overview:
I'm using the JQuery Form Plugin to send Form Data to a remote file via AJAX. The File then processes the form data and inserts it into the MySQL Database.
Problem:
The Problem is, however, when I want to run code on a successful add, (usually completed using the "success" option, it never runs. Doing further research I found that I needed to send back "responseText" to make the function under "success" run.
Questions:
1) Is this true?
2) How do I go about sending back responseText?
3) (If number on is that it is not true) How do I get the function under success to run?
A few code Snippets:
JQuery (Using the JQuery Form Plugin):
$("#form1").ajaxForm({url: 'submit.php', type: 'post', resetForm: true, success: function () { $('#new-paste').modal({show: false}) }});
I can provide the contents of the remote file (submit.php) if needed.
Thank you in advance!
Change your success to:
function(response) {
$('#new-paste').modal({show: false});
alert(response); // response is the output from the php script it submitted to.
}
Hope this helps.
Alright, so I found the solution.
The Script had to be included on the page itself, not in a remote .js file.
so:
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
Should be included in the head.

Page waits for AJAX before changing location

This question might seem a bit odd, the problem arised when the page went through webtests.
The page uses an AJAX call (async set to true) to gather some data. For some reason it won't swap pages before the AJAX call has returned - consider the following code:
console.log("firing ajax call");
$.ajax({
type: "POST",
url: "requestedService",
data: mode : "requestedMethod",
cache: false,
dataType: "json",
success: function() { console.log("ajax response received") },
error: null,
complete: null,
});
console.log("changing window location");
window.location = "http://www.google.com"
The location only changes after AJAX returns the response. I have tested the call, it is in fact asynchronous, the page isn't blocked. It should just load the new page even if the AJAX call hasn't completed, but doesn't. I can see the page is trying to load, but it only happens once I get the response. Any ideas?
The console output is:
firing ajax call
changing window location
ajax response received
This seems to work fine for me. The location is changed before the code in the async handler executes. Maybe you should post some real code and not a simplified version, so that we can help better.
Here is a demonstration that works as you expect: http://jsfiddle.net/BSg9P/
$(document).ready(function() {
var result;
$("#btn").on('click', function(sender, args) {
setInterval(function() {
result = "some result";
console.log("Just returned a result");
}, 5000);
window.location = "http://www.google.com";
});
});
And here is a screenshot of the result: http://screencast.com/t/VbxMCxxyIbB
I have clicked the button 2 times, and you can see in the JS console that the message about the location change is printed before the result each time. (The error is related to CORS, if it was the same domain, it would navigate).
Bit late but maybe someone else will have the same issue.
This answer by #todd-menier might help: https://stackoverflow.com/questions/941889#answer-970843
So the issue might be server-side. For eg, if you're using PHP sessions by default the user's session will be locked while the server is processing the ajax request, so the next request to the new page won't be able to be processed by the server until the ajax has completed and released the lock. You can release the lock early if your ajax processing code doesn't need it so the next page load can happen simultaneously.

Show user that the form was submitted successful or not

I have a form which sends data to a CRM. If I create a simple HTML form and send the data to the server it will refresh my webpage and show the text:
{"success":false,"error":{"message":"<whatever the error is>"}}
or
{"success":true,"result":"ok"}
After styling the form and integrating animations and validations and stuff everything still works perfectly. Now the data is sent by using http://jquery.malsup.com/form/#getting-started. The server receives it but the user has no idea whether it did or not.
Using this jQuery form plugin or some other plugin you might want me to use(or even code) please help me display text inside a div whether the operation was successful or not, depending on the server's response.
I have only tried to display the response using the examples provided here: http://jquery.malsup.com/form/#ajaxForm but I have failed until now.
Here I've put together a JSfiddle with some form fields and the jQuery form plugin I am using in order to send the data to the server: http://jsfiddle.net/n78p9/1/.
I hope someone will be able to show me what I did wrong or show me another way of doing this.
Thank you!
EDIT #Arun: so it looks like this:
submitHandler: function(form) {
$(form).ajaxSubmit({
target: '.optional',
resetForm: true,
success: function(responseText){
var result = jQuery.parseJSON(responseText);
if(!result.success){
alert(result.error.message)
}
},
error: function(){
alert('Thank you for your message! Our team will contact you in the shortest possible time.')
}
});
}
I am definitely on the right way, but there is a problem: the error alert actually shows when the response is successful. I do not understand why. I have intercepted the POST request through a local proxy and re-sent it through the server and the server sent back this:
{"success":true,"result":"ok"}
But the script considered it an error. That is why I have inserted that text into the error:alert field:D.
What might be the problem?
Try using the callbacks provided by the library
var options = {
target: '#response',
success: showResponse,
clearForm: true,
success: function(responseText){
var result = jQuery.parseJSON(responseText);
if(!result.success){
alert(result.error.message)
}
},
error: function(){
alert('some error')
}
};
$('#contact-form').ajaxForm(options);

How do I use JS to execute a heavy PHP function after the page loads in order to speed things up?

I've got a web page that displays some content. The query itself is pretty slow (4000 ms).
I don't want my users to have to wait for the query to run before the rest of the page loads though.
Is there a way I can stick some code before and after the tag in my HTML template that will "delay" that function from executing until after everything else has rendered?
e.g.:
<javascript code that tells the page not to render what comes next until very last>
<?php my_heavy_php_function(); ?>
</javascript>
As I can understand from your question, you should go for AJAX: you first load the page without the heavy content, and when the page is ready you do an AJAX call to a webservice to fetch and display the data, while showing a "Processing, please wait" message to the user.
symbolic write:
document.onload = ajax call
Using Ajax
Using the jQuery Ajax request method you can post the email data to a script (submit.php). The $(function(){ }); executes when the dom is ready. Also, you might need to use the 'timeout' option if you are going to be executing an long query.
note - I would suggest utilizing the ajax Response Object to make sure the script executed successfully.
$(function() {
$.ajax({
type: 'POST',
url: 'submit.php',
timeout: 10000,
error: function()
{
alert("Request Failed");
},
success: function(response)
{
//response being what your php script echos.
}
});
});
Although, jQuery is by no means required do do an ajax request, I would highly recommend using some kind of framework to help ensure x-browse support.
If you are using a large dataset I would highly recommend using json to encode your repsonses. It makes parsing quite easy. Here's an example with jQuery $.getJSON() API and likewise how you can encode it with PHP
Either optimizing the query or doing an AJAX call. Here is a plain JS way of doing AJAX, I found this script in a Google search and modified to use a callback function so you can parse the data or do other things other than just load the content straight to a HTML element:
the ajax function: The Original function I found unmodified
function ajaxRequest(Url, callback) {
var AJAX;
try {
AJAX = new XMLHttpRequest();
}
catch (e) {
try {
AJAX = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX.");
return false;
}
}
}
AJAX.onreadystatechange = function() {
if (AJAX.readyState == 4) {
if (AJAX.status == 200) {
callback(AJAX.responseText);
}
else {
alert("Error: " + AJAX.statusText + " " + AJAX.status);
}
}
}
AJAX.open("get", Url, true);
AJAX.send(null);
}
Usage of it:
<div> some normal content </div>
<div id="loadlater">loading data...</div>
<div> more content that loads before the data</div>
<script>
ajaxRequest('/echo/html/', function( response) {
document.getElementById('loadlater').innerHTML = response;;
});
</script>
Working example here: JSFiddle

Categories