简体   繁体   中英

How to pass javascript variable value to php variable using ajax to store in session in codeighter

I am working in codeighther and want to pass my javascript variable value to php so that I can store it in session and then store to database.

Following is what I have tried so far.

<div id="wrapper">
    <button id="detect-button">Detect Device</button>
</div>

<script>
    $('#detect-button').ready(function() {

        var detector = new MobileDetect(window.navigator.userAgent)
        var test = document.write("Mobile: " + detector.mobile());

        //document.write( "Phone: " + detector.phone());
        //document.write( "Tablet: " + detector.tablet());
        // document.write( "OS: " + detector.os());
        // document.write( "userAgent: " + detector.userAgent());


    });

    $.ajax({
                type: 'Post',
                url: '<?php echo  $base_url ?>Home/index',
                data: ({
                    value: +detector.mobile()
                }),
                cache: false,
                success: function(data) {
                    $('#results').html(data);
                }
</script>

<p id="results"> </p>

you can pass you test varibale data like,

 $.ajax({
                type: 'POST',
                url: '<?php echo  $base_url ?>Home/index',
                data: {field1 : test},
                cache: false,
                success: function(data) {
                    $('#results').html(data);
  }

And you can fetch data in PHP like $_POST['field1']

For more details, please visit http://thisinterestsme.com/simple-ajax-request-example-jquery-php/

I would recommend you to make use of the $.post or $.get syntax of jQuery for simple cases.

Define detector as a global variable. Its current scope is restricting its use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM