简体   繁体   中英

JQuery Ajax returning bool(false)

I've been looking at other questions related to my problem however none seem to correspond to my exact circumstances. I'm attempting to create a javascript variable which I will POST with Ajax to a PHP variable further down in my code. After hopefully setting the variable correctly I attempt to POST and var_dump the result however it is not the "0" I had hoped for but rather a frustrating bool(false). I've read that this may be a problem with the url (as I POST from the same file) or perhaps some other issue to do with the transfer of data to the Ajax request though I have as yet been unable to work out the issue. Testing for the data in the console also shows nothing so I've been forced to ask here. Thank you for any help or guidance.

Javascript

jQuery(document).ready(function(){var offset = parseInt("0");
        $.ajax({url: 'index.php', type: 'POST', data: offset, success:function(data){return data;}});
    });

PHP

<?php var_dump(isset($_POST['offset']));

add an index called offfest

$.ajax({
    url: 'index.php', 
    type: 'POST', 
    data: {offset:offset}, 
    success:function(data){
        return data;
    }
});

you can try with :

jQuery(document).ready(function(){
    $.ajax({url: 'index.php', type: 'POST', data: {offset: parseInt("0")}, success:function(data){return data;}});
});

I'm not totally familiar with PHP but in your javascript code, data should be dictionary for Ajax post. something like {'offset': 0}

Js:

var offset = parseInt("0");
$.ajax({url: 'index.php', type: 'POST', data:{offset: offset},success:function(data){alert(data.offset);}});

php:

<?php echo json_encode(array('offset'=>isset($_POST['offset'])));

Your problem is that you're using var_dump in your php.
That literally returns the string: "bool(true)" .

Use var_export , instead.

Instead of :

<?php var_dump(isset($_POST['offset'])); ?>

Use :

<?php var_export(isset($_POST['offset'])); ?>

var_export will output the string representation of the value, instead of the type / value combo var_dump returns.


If you just want to return the posted value, do this:

<?php var_export($_POST['offset']); ?>

Or:

<?php echo json_encode($_POST['offset']); ?>

Just keep in mind that you need to pass the data to the post , correctly:

data: { offset: offset }

Instead of:

data: offset

您应该给offset变量起一个名字,以便将data参数更改为JSON格式:

$.ajax({url: 'index.php', type: 'POST', data:{ 'offset': offset},success:function(data){return data;}});

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