A.Hollingsworth A.Hollingsworth - 4 months ago 7
Ajax Question

How to display variables in AJAX?

I have a form where users enter 6 numbers, which are collect and stored as variables when the form is submitted. I'm then using AJAX to display a loading screen. I was wondering how to display the numbers entered on the loading screen using AJAX beforeSend function?

$(function() {

$(".submit").click(function() {

var num1 = $("#num1").val();
var num2 = $("#num2").val();
var num3 = $("#num3").val();
var num4 = $("#num4").val();
var num5 = $("#num5").val();
var num6 = $("#num6").val();
var dataString = 'num1=' + num1 + '&num2=' + num2 + '&num3=' + num3 + '&num4=' + num4 + '&num5=' + num5 + '&num6=' + num6;
if (num1 == '' || num2 == '') {
$('.error').fadeOut(200).show();
} else {

$.ajax({
type : "POST",
url : "index.php",
data : dataString,

data : jQuery('#numbers_form').serializeArray(),
beforeSend : function() {
$('#loader').css('display', 'block');
$('#loader').css('margin', 'auto');

},
success : function(res) {
$('#success').css('display', 'block');
}
});
}
});
});

Answer

Change

else {

    $.ajax({

to

else {
    $('body').append(num1+' '+num2+' '+num3+' '+num4+' '+num5+' '+num6);
    $.ajax({

That should do it. If it is absolutely mandatory to use beforeSend then make it

$.ajax({
    type : "POST",
    url : "index.php",
    data : dataString,
    beforeSend : function() {
    $('#loader').css('display', 'block');
    $('#loader').css('margin', 'auto');
    $('body').append(num1+' '+num2+' '+num3+' '+num4+' '+num5+' '+num6);
    },
    success : function(res) {
            $('#success').css('display', 'block');
    }
});

You can change the 'body' selector to any other element and append function to text() or html() as well.

Note: You have assigned data twice. That would be unnecessary if the inputs are only 6 numbers.