Slay29 Slay29 - 21 days ago 5
Ajax Question

PHP echoing into JavaScript value "0" even when value is not "0" after POSTing with AJAX

I have button that is using AJAX post method to post value into PHP.

When I echo that value back in JavaScript it's always echoing 0, even when I am 100% sure that value in PHP is not 0.

Here is JavaScript:

function slanje(br){
$.ajax({
type: 'POST',
dataType: 'html',
data: {
'broj' : br,
}
});
}

function otvaranje(id, broj){
slanje(broj);
var testNumber = <?php echo $br; ?> + "";


And PHP (I do file write to check if PHP received correct value):

if(isset($_POST['broj'])){
$br = $_POST['broj'];
$file = fopen($br . "broj.txt", "w");
fclose($file);
}


Here is what value I get back in Javascript:

enter image description here

And here is value in PHP:

enter image description here

Edit 2: I want to post variable in PHP, than get value of element of PHP array with index I passed with ajax. And that without reloading page. I didn't include array part because while I was testing around I couldn't even make it echo back variable I'm passing using AJAX.

Answer

If you want to do it using AJAX, then let your PHP script return the POSTed value and grab it in the success handler of the AJAX request. For the success handler to be able to change the value of testNumber, the variable has to be declared outside of function otvaranje.

Here are the necessary modifications (also take note of the comments I added):

PHP

if(isset($_POST['broj'])){
    $br = $_POST['broj'];
    $file = fopen($br . "broj.txt", "w");
    fclose($file);

    // Just output the value and exit
    // If there is business logic doing something with
    // $br, then move this after that code.
    // But remember to only do this if the script was 
    // called with POST, otherwise the initial request 
    // wouldn't work anymore.
    print $br;
    exit;
}

JavaScript

var testNumber = "<?php echo $br; ?>";

function slanje(br){
    $.ajax({
        type: 'POST',
        dataType: 'html',
        data: {
            'broj' : br,
        },
        success: function(data) {
            // called when the request succeeded
            testNumber = data;
        }
    });   
}

function otvaranje(id, broj){
    slanje(broj);
    // move outside: var testNumber = <?php echo $br; ?> + "";
    // rest of function content
}
Comments