Cesar Bielich Cesar Bielich - 6 months ago 15
Javascript Question

php session_start() changing value of a numeric variable from ajax/jquery call

I am having a weird issue where for some reason something related to

session_start()
in php is changing the value of a numeric value in a variable from any number (in this case 131, but does it with any number) to 1 from a form select.

HTML

<select id="findcity">
<option value="130">this</option>
<option value="131">that</option>
<option value="132">another</option>
</select>
<button class="btn btn-primary" id="btn_0">button</button>


In this case I am selecting option #2 with value 131

My jquery

$('#box_0').on('click','#btn_0',function() {
var findcity = $('#findcity').val();
alert(findcity);
$.ajax({
type: "POST",
url: "includes/addfindcity.php?",
data: "findcity="+ findcity,
success: function(data) {

}
});
});


If I place an
alert(findcity)
after
var findcity = $('#findcity').val();
the value it retrieves from my select is correct which is the number
131


If I place the
alert(data)
in the success from the ajax callback the value returned in
1
. Example...

$('#box_0').on('click','#btn_0',function() {
var findcity = $('#findcity').val();
$.ajax({
type: "POST",
url: "includes/addfindcity.php?",
data: "findcity="+ findcity,
success: function(data) {
alert(data);
}
});
});


So of course I go to my php file
addfindcity.php
and see what's going on there.

Here is my php file

addfindcity.php

<?
session_start();
$_SESSION['findcity'] = $findcity;
?>


If I
echo
back the value it comes back
1


<?
session_start();
echo $_SESSION['findcity'] = $findcity;
?>


but... if I echo back the value before
session_start()
then the value is correct and still remains at
131
like this

<?
echo $findcity;
session_start();
$_SESSION['findcity'] = $findcity;
?>


I am not sure why something with saving the numeric value to a session is changing it to
1
. I have several other scripts that do the same thing with none numeric values that work fine. It seems that this one that is numeric only does this. Any ideas?

Answer

Use it like this

JS

    $('#box_0').on('click','#btn_0',function() {
    var findcity = $('#findcity').val();
    $.ajax({
        type: "POST",
        url: "includes/addfindcity.php",
        data: "findcity="+ findcity,
        success: function(data) {
            alert(data);
        }
    });
});

PHP

 <?php
session_start();
$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$_SESSION['findcity'] = $_POST["findcity"];
?>