0

I'm trying to store data from ajax (jquery) response to variable because I need to use it later in code.

Jquery code:

  $(document).ready(function () {
  $("#submitReg").click(function () {
    var email = $("#email").val();
    var password = $("#password").val();
    var confpassword = $("#confpassword").val();
    if (email == '' || password == '' || confpassword == '') {
        swal({
            type: "error",
            timer: 10000,
            showConfirmButton: true,
            confirmButtonText: "OK",
            confirmButtonColor: "#f4511e",
            title: "Prosím vyplňte všetky polia!"
        });
    } else {
        $.get("./php/register.php", {
            email: email,
            password: password,
            confpassword: confpassword,
            dataType: 'json',
            //data: '1',

            success: function ($data) {
                var controlNumber = $data;
                alert(controlNumber);
                if (controlNumber != 1) {
                    swal({
                        type: "success",
                        timer: 10000,
                        showConfirmButton: true,
                        confirmButtonText: "OK",
                        confirmButtonColor: "#f4511e",
                        title: "Registrácia prebehla úspešne."
                    });
                  //  $('#registerme')[0].reset();
                } else {
                    swal({
                        type: "error",
                        timer: 10000,
                        showConfirmButton: true,
                        confirmButtonText: "OK",
                        confirmButtonColor: "#f4511e",
                        title: "Mail už bol zaregistrovaný."
                    });

                }
            }
        })
    }
});
}); 

PHP code:

<?php

require_once 'connect.php';

$email = ($_GET['email']);
$password = ($_GET['password']);
$passwordR = ($_GET['confpassword']);

if ($password == $passwordR) {

$password = hash('sha256', $password);
$emailCheck = mysqli_query(connect(), "SELECT * FROM users WHERE email='" . 
$email . "'");

if (mysqli_num_rows($emailCheck) > 0) {
    echo json_encode(1);
    die();
 } else {
    $sql = "INSERT INTO users (email, password) VALUES ('$email','$password')";
}
}

if (connect()->query($sql) === TRUE) {
//implementuj reset kody ptm
} else {
echo "Error: " . $sql . "<br>" . connect()->error;
}

die();

?>

I'm receiving response - 1 so I think that works but I need to store it somehow
Thanks everyone for any answers

Martin K.
  • 93
  • 2
  • 11

3 Answers3

0

I'm trying to store data from ajax (jquery) response to variable because I need to use it later in code.

The accepted Answer has 'var controlNumber = $data;' declaration inside Ajax Success Callback, which wouldn't accessible from Outside of Ajax Function. That statement is very clear that You Can't get'controlNumber' variable outside of Ajax Callback Success Function, because it's a local variable, declared inside a function.. So the best would be declare a Global JavaScript Variable and reassign value again inside Ajax Success callback.

By they way if I follow the line "I'm trying to store data from ajax (jquery) response to variable" then the accepted answer is fine.

But if I follow the statement "I need to use it later in code" creates 2 assumptions here..

1 - if your code is still on inside ajax function - Then Fine

2 - if your code using ajax response on outside ajax function, then you won't be able to get 'controlNumber' value. if you try you will get 'undefined'

So what is the best way to deal Ajax Response, Create a function which responsible to return ajax object with success or error response. I am sure it didn't sound clear.. ;) No worry here is more or read more :)

First of all understand what is ajax and how it works...?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Content Reference: W3CSCHOOL

Kindly notice the word 'asynchronously', it means if you call ajax and trying to use ajax response data at next line then you can't. Because, DOM will not wait for Ajax Response & script won't stop to wait to complete process of ajax it will continue & you will get 'undefined' until you don't make ajax request with 'async: false' option. *But as of jQuery 1.8, the use of async: false is deprecated! Wohooo!! Sounds Great!!! @-@ *

Many people also suggest to use global var and set variable value later inside ajax success callback to use. But the problem is asap you try to use variable after next ajax call then it will produce same error as describe above.

So the best method would be to Store or Use or Get Ajax Response by using a function which returns ajax object and you can later use that ajax object with 'YourAjaxObject.success(callback)' anywhere any time in your application without any worry. You can also use/put your functions which requires ajax response inside ajax success callback.

A very simple example I am sharing with you to understand this better..


// global var declare here
var collect = null;
$(document).ready(function() {
    var btn = $('#mySubmitButton');
    btn.on('click', function(e) {
        e.preventDefault();
        $.post('url.php', {
            id: 1
        }, function(ajx_res) {
            // store ajax response in global var
            collect = ajx_res;
            // 'I will execute last with collect = ajx_res data
            alert(collect);
        });
        // 'I will execute first with collect = null data
        alert(collect);
        // When btn click again, I will execute first with previous ajx_res data
        alert(collect);
    });
});
$(document).ready(function() {
    var btn = $('#mySubmitButton');
    btn.on('click', function(e) {
        e.preventDefault();
        $.post('url.php', {
            id: 1
        }, function(ajx_res) {
            // now I am local var
            var collect = null;
            // store ajax response in local var
            collect = ajx_res;
            // 'I will execute last with collect = ajx_res data
            alert(collect);
        });
        // I will execute first with collect = undefined
        alert(collect);
        // When btn click again I will execute first with same collect = undefined
        alert(collect);
    });
});
/**
 * Ajax Request & Return Response
 * @param url _url         action url
 * @param object options send payloads
 */
function AjaxCall(_url, _options) {
    return $.ajax(_url, {
        method: 'POST',
        data: _options,
        error: function(xhr, ajaxOptions, thrownError) {
            alert("Request Error:" + thrownError + " with Status" + xhr.status);
        }
    });
}
// I am again as global var
var collect = null;
$(document).ready(function() {
    var btn = $('#mySubmitButton');
    // first button, click
    btn.on('click', function(e) {
        e.preventDefault();
        // return ajax object, and can be use within entire application via callback
        collect = AjaxCall(_url, _options);
        // use success callback to retrieve data
        collect.success(function(ajx_res) {
            // I will execute first with ajx_res
            alert(ajx_res);
        });
    });
    var btns = $('#mySubmitButtons');
    // on another button, another click
    btns.on('click', function(e) {
        e.preventDefault();
        // using previous ajax obj to get data
        collect.success(function(ajx_res) {
            // I will execute first with previous ajx_res
            alert(ajx_res);
        });
    });
});

// I am again as global var
var collect = null;
$(document).ready(function() {
    var btn = $('#mySubmitButton');
    // first button, click
    btn.on('click', function(e) {
        e.preventDefault();
        // return ajax object, and can be use within entire application via callback
        collect = AjaxCall(_url, _options);
    });
    var btns = $('#mySubmitButtons');
    // on another button, another click
    btns.on('click', function(e) {
        e.preventDefault();
        // using previous ajax obj to get data
        collect.success(function(ajx_res) {
            // I will execute first with previous ajx_res
            alert(ajx_res);
        });
    });
});

So in short:

1 - You can't use local variable (which declared inside function or loop) out side of their declaration area.

2 - Ajax don't return the response, you can get the response by using callbacks.

3 - Store Ajax response in global variable to use outside of ajax callback function.

4 - If any code, function depends on ajax response, put them inside ajax success callback.

5 - If any specific functions needs ajax response value, then call those functions inside success callback & pass ajax response as parameters or you can use 'Injection Techniques' (function to function with same parameter) e.g.

function Hello (ajx_res) {
    alert (ajx_res);
    // send in another function
    Foo (ajx_res);
}

function Foo (ajx_res) {
    alert (ajx_res);
    // send in another function
    Bar (ajx_res);
}

function Bar (ajx_res) {
    alert (ajx_res);
}

So my answer would be for this Question use Ajax Object & Get response by Callbacks.

/**
 * Ajax Request & Return Response
 * @param url _url         action url
 * @param object options send payloads
 */
function AjaxCall(_url, _options) {
    return $.ajax(_url, {
        method: 'POST',
        data: _options,
        error: function(xhr, ajaxOptions, thrownError) {
            alert("Request Error:" + thrownError + " with Status" + xhr.status);
        }
    });
}
$(document).ready(function() {
    $("#submitReg").click(function() {
        var email = $("#email").val();
        var password = $("#password").val();
        var confpassword = $("#confpassword").val();
        if (!email || !password || !confpassword) {
            swal({
                type: "error",
                timer: 10000,
                showConfirmButton: true,
                confirmButtonText: "OK",
                confirmButtonColor: "#f4511e",
                title: "Prosím vyplňte všetky polia!"
            });
        } else {
            var ajaxObj = AjaxCall("./php/register.php", {
                email: email,
                password: password,
                confpassword: confpassword,
            });
            // your ajax callback function for success
            ajaxObj.success(function(response) {
                var controlNumber = response;
                if (controlNumber == '1') {
                    swal({
                        type: "success",
                        timer: 10000,
                        showConfirmButton: true,
                        confirmButtonText: "OK",
                        confirmButtonColor: "#f4511e",
                        title: "Registrácia prebehla úspešne."
                    });
                } else if (controlNumber == '0') {
                    swal({
                        type: "error",
                        timer: 10000,
                        showConfirmButton: true,
                        confirmButtonText: "OK",
                        confirmButtonColor: "#f4511e",
                        title: "Mail už bol zaregistrovaný."
                    });
                } else {
                    alert(controlNumber);
                }
            });
        }
    });
});

Hope this will clear doubts for beginners user who are not comfortable with ajax at first sight, first love :D ^_^ Tadaaa.. :)

Nono
  • 6,986
  • 4
  • 39
  • 39
-2

In your php, if are trying to return 1 if the row is found then just echo 1; instead of echo json_encode(1);. Whenever you make a call to the php page, the outputted value is the retrieved data in the Ajax response. No reason to json encode the value because it isn't a json formatted value. It will return as a literal value of output.

If you're trying to store the response value on the same page session, then you need to initialize the variable as a global variable and not a local variable to the Ajax request.

var test;

$.ajax({
  url:'',
  data:{index: value, index: value}, //if you have a form, $('[form selector]').serialize();
  method:'', // get or post
  success: function(data){
    // the data here is the data returned from the Ajax request
    test=data.whatever;
  }
});

Because test is initialized outside of the Ajax call, it will now be stored in mem until the page is refreshed or changed, and can be used in other parts of the javascript.

  • What should I put in data ? Data that I want to receive or data I want to send or what ? – Martin K. Jun 16 '17 at 20:04
  • Declare var controlNumber outside the ajax callback and you will have access to the data later on in the script. Side note: should you be sending passwords in a GET request and querying the database using mysqli and not even escaping your variables? It seems like a really bad idea. – SebastianGreen Jun 16 '17 at 20:11
  • Yeah I know, I will take care about security part after I'll finish with this – Martin K. Jun 16 '17 at 20:21
  • No because I think you got me wrong, my only problem is that for some reason data that which is received from PHP if it finds same registered email in database (it is - 1) isn't stored into my variable controlNumber and I cant figure that out – Martin K. Jun 16 '17 at 20:32
  • Oh, I'm sorry I misunderstood the issue. I'll was half correct, I missed the php part it seems. Is that correct? – Stephen Adkins Jun 16 '17 at 20:39
-2

Your code looked ok did some improvement try it:

JS:

$(document).ready(function () {
  $("#submitReg").click(function () {
    var email = $("#email").val();
    var password = $("#password").val();
    var confpassword = $("#confpassword").val();
    if (email == '' || password == '' || confpassword == '') {
        swal({
            type: "error",
            timer: 10000,
            showConfirmButton: true,
            confirmButtonText: "OK",
            confirmButtonColor: "#f4511e",
            title: "Prosím vyplňte všetky polia!"
        });
    } else {
        $.ajax("./php/register.php", {
            method:'POST',
            data: {
            email: email,
            password: password,
            confpassword: confpassword,
             },

            success: function ($data) {
                var controlNumber = $data;
               // alert(controlNumber);
                if (controlNumber == 1) {
                    swal({
                        type: "success",
                        timer: 10000,
                        showConfirmButton: true,
                        confirmButtonText: "OK",
                        confirmButtonColor: "#f4511e",
                        title: "Registrácia prebehla úspešne."
                    });
                  //  $('#registerme')[0].reset();
                } 
                 else if(controlNumber == 0)
                 {
                    swal({
                        type: "error",
                        timer: 10000,
                        showConfirmButton: true,
                        confirmButtonText: "OK",
                        confirmButtonColor: "#f4511e",
                        title: "Mail už bol zaregistrovaný."
                    });

                }
                else
               {
                alert(controlNumber );
               }

            }
        })
    }
});
}); 

PHP:

<?php

require_once 'connect.php';

$email = ($_POST['email']);
$password = ($_POST['password']);
$passwordR = ($_POST['confpassword']);

if ($password == $passwordR) {

$password = hash('sha256', $password);
$emailCheck = mysqli_query(connect(), "SELECT * FROM users WHERE email='" . 
$email . "'");

if (mysqli_num_rows($emailCheck) > 0) {
    echo 0;
    die();
 } else {
    $sql = "INSERT INTO users (email, password) VALUES ('$email','$password')";
}
}

if (connect()->query($sql) === TRUE) {
 echo 1;
 die();
} else {
echo "Error: " . $sql . "<br>" . connect()->error;
die();
}
Riaz Laskar
  • 1,317
  • 9
  • 17