Loading a new page with Javascript/Ajax - php

I have an Ajax script that allows me to check a form without refreshing the page. But i want it to check if fields haven't been complete, but if al fields are complete i want to send the user to a new page.
I'm not sure how i can do this. Here is the Ajax script:
function pass()
{
// Real Browsers (chrome)
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//Store data
var email = document.getElementById('email').value;
var firstname = document.getElementById('firstname').value;
var surname = document.getElementById('surname').value;
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
var postcode = document.getElementById('postcode').value;
//Open POST location
xhr.open("POST","addUserSeminar.php");
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
//Make object to store all data
var obj = {email: email, firstname: firstname, surname: surname, address1: address1, address2: address2, postcode: postcode};
//Encode the data with JSON and send it to the server
xhr.send("data=" + JSON.stringify(obj));
//Check return state and change "myDiv"
xhr.onreadystatechange=function()
{
if (xhr.readyState==4)
{
document.getElementById("settingsDiv").innerHTML = xhr.responseText;
}
}
//Return false so form doesn't submit
return false;
}
It sends the data out to a php file where i check if the boxes are filled, if not i each a message like "Name not found". But if all data is posted then i add a record to my database and then return true.
How could i pick up that return in my Ajax script so i can test if its true, if so forward to a new page.
Thanks for the time.

Return back something from the server that says it is complete and read it with the xhr.responseText in an if statement.
if( xhr.responseText.indexOf("forward to next page") > -1 ){
//forward
} else {
//show error message
}
It would be a lot better if you used a JSON object to return errors and success messages, since you could just check the object to waht to do.

In your onreadystatechanged, readyState == 4 if block...
if(xhr.responseText.indexOf("SUCCESS") >= 0) {
window.location.href = NEW_URI;
} else {
document.getElementById("settingsDiv").innerHTML = xhr.responseText;
}
Have your PHP script return a unique string to denote SUCCESS vs FAILURE with fields that are blank.

return the string "TRUE" from server side on success
PHP CODE
if($valid_inputs) { // all input fields are valid
echo "TRUE";
} else {
echo "FALSE";
}
client side JS code
if (xhr.readyState==4)
{
if (xhr.responseText.indexOf("TRUE") > -1) {
window.location = "redirecturl.php"; //redirect url
}
}

Related

How to make a submit button send the input values only if the input values matches with the mysql data?

I'm trying to make a simple registration page that makes the user enter the username and email.
The problem is how can I check if the input values(email)already exists in the mysql when I press the submit button without going to the next page instantly ? if the input value doesn't exist in the mysql database I want to display a message like "email not registered". I'm trying to use ajax,jquery, and php but I cant find a decent solution.
//this is the script to check if the emails that the users entered matches.
//I'm trying to post the values to the'checkPage.php' to check if the email exists
//The problem is how can I on move to the next page after the result have been returned?
Sorry for my bad explanation.
<script>
$('input#submitbutton').on('click',function(){
var mail=$('input#mail').val();
var mail2=$('input#mail2').val();
if($.trim(mail)===$.trim(mail2)){
$.post('checkPage.php',{mail:mail},function(data){
$('#name-data').text(data); // displays the result if the email exists or not
});
}else{
}
});enter code here
</script>
//CheckPage.php
//I want the registration page to go to the next page only if the email
//haven't been found in the mysql database.
<?php
if(isset($_POST['mail'])&&isset($_POST['mail2'])){
$mail = $_POST['mail'];
$mail2 = $_POST['mail2'];
try{
$con = mysql_connect("localhost","root",""); echo "connected";
$db = mysql_select_db("db",$con);
$query = mysql_query("select email,id from user where email ='". mysql_real_escape_string(trim($mail))."'",$con);
echo (mysql_num_rows($query)!==0) ? mysql_result($query,0,'email'):'none';
} catch (Exception $ex) {
}
}
?>
*/
you can use this;
$('input#submitbutton').on('click',function(event){
event.preventDefault();
var mail=$('input#mail').val();
var mail2=$('input#mail2').val();
if($.trim(mail)===$.trim(mail2)){
$.post('checkPage.php',{mail:mail},function(data){
$('#name-data').text(data); // displays the result if the email exists or not
if (data !== "none") {
$('#your_form_id').submit();
}
});
}else{
}
});
First of all on submit button make an ajax call as follows
<script>
function myformsubmit()
{
var mail=$('#mail').val();
$.post( "check.php", { mail: mail})
.done(function( data ) {
if(msg == 'error')
{
$('#diverr').html('Match found');
return false;
}
else
{
//redirect to a valid page
}
});
}
In the check.php you will have to get your data by post make an sql select query loop thru the mail ids returned by the query and if there is a match found return 'error' or return blank
try to put your javascript code in $(document).ready();
$(document).ready(function() {
//your code here
$('input#submitbutton').on('click',function(){
var mail=$('input#mail').val();
var mail2=$('input#mail2').val();
if($.trim(mail)===$.trim(mail2)){
$.post('checkPage.php',{mail:mail},function(data){
$('#name-data').text(data); // displays the result if the email exists or not
});
}else{
}
});e
});

How do I stop my javascript functioning if the input is empty and if the input is not an existing twitter account?

The input on my html form has a problem. Curently I am taking the input which is a twitter name into an Ajax function that calls tweets via php from the twitter api.
The problem is that if the input is empty or the input is not a valid twitter account it executes the php call to the twitter api and the return is an error message.
How can I stop the Ajax functioning if the twitter account does not exist or the input is empty? Would something have to happen on the php side?
Here is the html for the input:
<div id="topdiv">Input Twitter ID:
<input type="text" id="userid" onkeydown="if(event.keyCode===13) {document.getElementById('tweet-button').click();}">
<input type="submit" id="tweet-button" onclick="getStatusesX();" value="Get recent tweets">
<p id="tweetbox"></p>
</div>
the script taking the input and connecting to the php:
var intervalstop;
function getStatusesX() {
//trying to stop an empty input from executing but not working
if(input == ""){
alert("PLease enter a Twitter ID");
return false;
}
clearInterval(intervalstop);
var userID = document.getElementById("userid").value;
getStatuses(userID);
intervalstop = setInterval(function() {getStatuses(userID);}, 20000);
}
//Create a cross-browser XMLHttp Request object
function getXMLHttp() {
var xmlhttp;
if (window.ActiveXObject) {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
XMLHttp = new XMLHttpRequest();
} else {
alert("Your browser does not support XMLHTTP!");
}
return XMLHttp;
}
//function that searches for the tweets via php
function getStatuses(userID){
XMLHttp1 = getXMLHttp();
//var userID = document.getElementById("userid").value;
//ajax call to a php file that will extract the tweets
XMLHttp1.open( 'GET', 'TwitterGlimpsePHP.php?userid='+userID, true);
// Process the data when the ajax object changes its state
XMLHttp1.onreadystatechange = function() {
if( XMLHttp1.readyState == 4 ) {
if( XMLHttp1.status ==200 ) { //no problem has been detected
document.getElementById("tweetbox").innerHTML=XMLHttp1.responseText;
}
}
}
XMLHttp1.send(null);
}
input isn't defined anywhere. Move this line:
var userID = document.getElementById("userid").value;
Then check if the userID is empty:
function getStatusesX() {
var userID = document.getElementById("userid").value;
if(userID === ''){
alert("Please enter a Twitter ID");
return false;
}
clearInterval(intervalstop);
getStatuses(userID);
intervalstop = setInterval(function() {getStatuses(userID);}, 20000);
}
Your doing a check for input but nowhere have you defined this. Check on the userID instead
function getStatusesX() {
clearInterval(intervalstop);
var userID = document.getElementById("userid").value;
//trying to stop an empty input from executing but not working
if(userID == ""){
alert("PLease enter a Twitter ID");
return false;
}
getStatuses(userID);
intervalstop = setInterval(function() {getStatuses(userID);}, 20000);
}
As the previous responses stated, for the empty input case, you're checking a variable that is not defined.
As for checking if the input is a valid twitter user, it has to done be server side. For example, your "TwitterGlimpsePHP.php" script might do this check and if the user is not valid, return a special http status. You can use a 4XX http status but I'm not sure which would be the most relevant (400 for Bad Request perhaps).
Last modification would be to change the getStatutes function to check the server response as :
//function that searches for the tweets via php
function getStatuses(userID){
XMLHttp1 = getXMLHttp();
//var userID = document.getElementById("userid").value;
//ajax call to a php file that will extract the tweets
XMLHttp1.open( 'GET', 'TwitterGlimpsePHP.php?userid='+userID, true);
// Process the data when the ajax object changes its state
XMLHttp1.onreadystatechange = function() {
if( XMLHttp1.readyState == 4 ) {
if( XMLHttp1.status ==200 ) { //no problem has been detected
document.getElementById("tweetbox").innerHTML=XMLHttp1.responseText;
} else if (XMLHttp1.status ==400 ) {
// The user was not valid. Stop refresh.
clearInterval(intervalstop);
}
}
}
XMLHttp1.send(null);
}
Edit for the server side :
The server side script you provide doesn't seem to check the twitter statut (I'm not a php expert, more java/.net dev so I might be wrong). For invalid user, twitter will answer differently.
For example, look at https://api.twitter.com/1/statuses/user_timeline/fdfsfsfsfsdf.xml and you will see :
<errors>
<error code="34">Sorry, that page does not exist</error>
</errors>
Your php script will have to check for this type of response from twitter then return the http status. You can take a look at this question to see how to set the http status : Set Response Status Code. I hope those explanations will help you.

PHP AJAX Confirm on Form Submit

I have a small form which contains a first name, last name and a date. On clicking to submit the form I want it to check the database for a duplicate entry (with Ajax), and if there is already 1+ entries, present a confirm window confirming another submission. The confirm shouldn't show if there aren't any entries.
For some reason it seems to be presenting the confirm without the result from the Ajax PHP page. If I introduce an alert after the xmlHttp.send(null) line, it gets the text from the PHP (as wanted), making me think I misunderstand the order the code is executed. Here is the code:
Javascript:
function check_duplicates() {
var first = document.getElementById('first_name').value;
var last = document.getElementById('last_name').value;
var date = document.getElementById('event_date').value;
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser does not support AJAX!");
return;
}
var result = "ERROR - Ajax did not load properly";
var url="check_duplicate.php";
url=url+"?first="+first;
url=url+"&last="+last;
url=url+"&date="+date;
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
result = xmlHttp.responseText;
alert("RESULT="+result);
if(result != "clean") {
var validate = confirm(result);
return validate;
}
}
}
xmlHttp.open("GET",url,true);
var test = xmlHttp.send(null);
}
function GetXmlHttpObject() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
PHP:
// DATABASE CONNECTION INFORMATION REMOVED
$first = $_GET['first'];
$last = $_GET['last'];
$date = date('Y-m-d',strtotime($_GET['date']));
$sql = "SELECT COUNT(*) AS count FROM Table WHERE First='$first' AND ".
"Last='$last' AND Date='$date'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if($row['count'] > 0) {
if($row['count'] == 1) {
echo "There is already an entry for ".$first." ".$last." on ".
date('M jS',strtotime($date)).".\n".
"Are you sure you want to submit this entry?";
}
else { // plural version of the same message
echo "There are already ".$row['count']." entries for ".$first." ".
$last." on ".date('M jS',strtotime($date)).".\n".
"Are you sure you want to submit this entry?";
}
} else {
echo "clean";
}
Here is an answer using synchronous AJAX. This way, you don't have to overload the default form handling to get it to work. However, all javascript will be blocked while the confirmation request is running, which means your web page may appear to come to a screeching halt for however long the confirmation request lasts.
This function will return true if the record should be added, and false otherwise.
function check_duplicates() {
var first = document.getElementById('first_name').value;
var last = document.getElementById('last_name').value;
var date = document.getElementById('event_date').value;
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser does not support AJAX!");
return false;
}
var result = "ERROR - Ajax did not load properly";
var url="check_duplicate.php";
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);
xmlHttp.open("GET",url,false);
xmlHttp.send(null);
var validated = true;
var result = xmlHttp.responseText;
if (result != 'clean')
validated = confirm("RESULT="+result);
return validated;
}
This line of code return undefined.
var test = xmlHttp.send(null);
What you have to understand is that the send() call returns immediately and Javascript keeps running. Meanwhile, your AJAX request is running in the background. Also, your onreadystatechange handler is called once the request is done, whether it takes 10ms or 100s, and its return value is not received by the rest of your code.
I think what you wanted to submit the form AFTER the confirmation was finished. You only know when the request is finished from inside your onreadystatechange handler. The problem here is that, in order to wait for the AJAX request to finish you have to override the default behavior of the form.
You'll need to call preventDefault() on the form-submit event, and then submit the data manually after confirmation.
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
var confirmed = false;
var result = xmlHttp.responseText;
if (result == "clean")
confirmed = true;
else
confirmed = confirm("RESULT="+result);
if (confirmed) {
var url = "addData.php";
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);
window.location = url;
}
}
}
Also, when you're building your URL you should use encodeURIComponent.
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);

jQuery Post and Get Form data

When a form is submitted, I can get its field values with $_POST. However, I am trying to use a basic jQuery (without any plugin) to check if any field was blank, I want to post the form content only if theres no any blank field.
I am trying following code, and I got the success with jQuery, but the only problem is that I am unable to post the form after checking with jQuery. It does not get to the $_POST after the jQuery.
Also, how can I get the server response back in the jQuery (to check if there was any server error or not).
Here's what I'm trying:
HTML:
<form action="" id="basicform" method="post">
<p><label>Name</label><input type="text" name="name" /></p>
<p><label>Email</label><input type="text" name="email" /></p>
<input type="submit" name="submit" value="Submit"/>
</form>
jQuery:
jQuery('form#basicform').submit(function() {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
return false;
});
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return true;
}
To be very specific to the question:
How can I get the server response back in the jQuery (to check if
there was any server error or not). Here's what I'm trying:
Sound like you're talking about Server-Side validation via jQuery-Ajax.
Well, then you need:
Send JavaScript values of the variables to PHP
Check if there any error occurred
Send result back to JavaScript
So you're saying,
However, I am trying to use a basic jQuery (without any plugin) to
check if any field was blank, I want to post the form content only if
there's no any blank field.
JavaScript/jQuery code:
Take a look at this example:
<script>
$(function()) {
$("#submit").click(function() {
$.post('your_php_script.php', {
//JS Var //These are is going to be pushed into $_POST
"name" : $("#your_name_field").val(),
"email" : $("#your_email_f").val()
}, function(respond) {
try {
//If this falls, then respond isn't JSON
var result = JSON.parse(respond);
if ( result.success ) { alert('No errors. OK') }
} catch(e) {
//So we got simple plain text (or even HTML) from server
//This will be your error "message"
$("#some_div").html(respond);
}
});
});
}
</script>
Well, not it's time to look at php one:
<?php
/**
* Since you're talking about error handling
* we would keep error messages in some array
*/
$errors = array();
function add_error($msg){
//#another readers
//s, please don't tell me that "global" keyword makes code hard to maintain
global $errors;
array_push($errors, $msg);
}
/**
* Show errors if we have any
*
*/
function show_errs(){
global $errors;
if ( !empty($errors) ){
foreach($errors as $error){
print "<p><li>{$error}</li></p>";
}
//indicate that we do have some errors:
return false;
}
//indicate somehow that we don't have errors
return true;
}
function validate_name($name){
if ( empty($name) ){
add_error('Name is empty');
}
//And so on... you can also check the length, regex and so on
return true;
}
//Now we are going to send back to JavaScript via JSON
if ( show_errs() ){
//means no error occured
$respond = array();
$respond['success'] = true;
//Now it's going to evaluate as valid JSON object in javaScript
die( json_encode($respond) );
} //otherwise some errors will be displayed (as html)
You could return something like {"error": "1"} or {"error": "0"} from the server instead (meaning, put something more readable into a JSON response). This makes the check easier since you have something in data.
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return json_encode(array("error" => 0));
} else {
return json_encode(array("error" => 1));
}
JavaScript:
jQuery('input#frmSubmit').submit(function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
var myData = data;
if(myDate.error == 1) {//or "1"
//do something here
} else {
//do something else here when error = 0
}
});
}
$("form#basicform").submit();
return false;
});
There are two ways of doing that
Way 1:
As per your implementation, you are using input[type="submit"] Its default behavior is to submit the form. So if you want to do your validation prior to form submission, you must preventDefault() its behaviour
jQuery('form#basicform').submit(function(e) {
//code
e.preventDefault();
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$(this).submit();
return false;
});
Way 2:
Or simply replace your submit button with simple button, and submit your form manually.
With $("yourFormSelector").submit();
Change your submit button to simple button
i.e
Change
<input type="submit" name="submit" value="Submit"/>
To
<input id="frmSubmit" type="button" name="submit" value="Submit"/>
And your jQuery code will be
jQuery('input#frmSubmit').on('click',function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$("form#basicform").submit();
return false;
});
To get the response from the server, you have to echo your response.
Suppose, if all the variables are set, then echo 1; else echo 0.
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
echo 1;
} else {
echo 0;
}
And in your success callback function of $.post() handle it like
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast",{err:data}, function(e) {
if(e.data.err==1){
alert("no error");
} else {
alert("error are there");
});
});

Posting not working via JS (Jquery) but is with form

I have a rather confusing problem.
I have a php file (http://example.com/delete.php)
<?php
session_start();
$user_id = $_SESSION['user_id'];
$logged_in_user = $_SESSION['username'];
require_once('../classes/config.php');
require_once('../classes/post.php');
$post = new Post(NULL,$_POST['short']);
#print_r($post);
try {
if ($post->user_id == $user_id) {
$pdo = new PDOConfig();
$sql = "DELETE FROM posts WHERE id=:id";
$q = $pdo->prepare($sql);
$q->execute(array(':id'=>$post->id));
$pdo = NULL;
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
and I'm trying to get this jquery to post data to it, and thus delete the data.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This post? (" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("post Has Been Deleted!");
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
and when I do that, it returns "Post Has Been Deleted!" but does not delete the post.
Confused by that, I made a form to test the php.
<form action="http://example.com/delete.php" method="POST">
<input type="hidden" value="8" name="short"/>
<input type="submit" name="submit" value="submit"/>
</form>
which works beautifully. Very odd.
I have code almost identical for deleting of a comment, and that works great in the javascript.
Any ideas? Beats me.
Thanks in advance,
Will
EDIT:
this works... but doesn't follow the href at the end, which is the desired effect. Odd.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This Post? (http://lala.in/" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete/post.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("Post Has Been Deleted!");
******************************************
event.preventDefault();
return false;
******************************************
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
If your PHP script delete the post, it doesn't return anything.
My bad, it's not answering the real question, but still is a mistake ;)
Actually, it seems that PHP session and AJAX doesn't quite work well together sometimes.
It means that if ($post->user_id == $user_id) will never validate, hence the non-deleting problem.
2 ways to see this :
Log $user_id and see if it's not null
Try to send the $_SESSION['user_id'] with your ajax post and check with it. But not in production, for security reason.
1-
Your PHP should return something in every case (at least, when you're looking for a bug like your actual case).
<?php
[...]
try {
if ($post->user_id == $user_id) {
[...]
echo 'true';
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
2-
jQuery is nice to use for AJAX for many reasons. For example, it handles many browsers and make checks for you but moreover, you can handle success and error in the same .ajax() / .post() / .get() function \o/
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short'); // If that's where your data is... Fair enough.
if (confirm("Delete This Post? (http://lala.in/" + num + ")")) {
$.post("delete/post.php", {short: num}, // Relative is nice :D
function(data){
if (data == 'false') {
alert('Deleting Failed!');
}else{
alert("Post Has Been Deleted!");
// Your redirection here ?
}
});
}
});
3-
If you need to send data from a form to a script and then do a redirection, I won't recommand AJAX which is usually use not to leave the page !
Therefore, you should do what's in your comment, a form to a PHP script that will apparently delete something and then do a redirection.
In your code I don't see num defined anywhere...and invalid isn't set when you think it is, so you're not passing that 8 value back and you're getting the wrong message, either you need this:
$.post("http://example.com/delete.php", {short: $("input[name=short]").val()},
Or easier, just .serialize() the <form>, which works for any future input type elements as well:
$.post("http://example.com/delete.php", $("form").serialize(),
I'm not sure where your code is being called, if for example it was the <form> .submit() handler, it'd look like this:
$("form").submit(function() {
$.post("http://example.com/delete.php", $(this).serialize(), function(data){
if (data == 'false') {
alert('Deleting Failed!');
} else {
alert("Post Has Been Deleted!");
}
});
Note that you need to check inside the callback, since invalid won't be set to true until the server comes back with data the way you currently have it, because it's an asynchronous call.

Categories