1

I want to pass variable from javascript to php using POST and I am doing something like the following. I view1.php

 <script>
function testing(col) {
    $("#bookId").val(col);
    $.ajax({
            type: 'POST',
            url: <?php echo Yii::app()->createUrl('siteaccess/create') ?>,
            data: {ad_id:<?php echo "hello" ?>},
            success: function(col){console.log(col)},
    });
}
</script>

In same file I have following code calling testing()

function(){
testing($(this).parent().parent().children(\':nth-child(2)\').text());
 }

In create.php I have

<?php 
$v = $_POST['ad_id'];
echo $v;
?>

For create.php I am getting this error "Undefined index: ad_id". Can anyone guide where I am making mistake?

1
  • at .ajax you haven't escaped your url: '<php>' and you should define dataType Commented Oct 22, 2013 at 12:30

2 Answers 2

1

You have missed the semicolumn in the php code and also define the dataType in the ajax request:

$.ajax({
        type: 'POST',
        url: "<?php echo Yii::app()->createUrl('siteaccess/create'); ?>",
        data: {"ad_id":"<?php echo 'hello'; ?>"},
        dataType: 'text',
        success: function(col){console.log(col)},
});

use the above code.

Sign up to request clarification or add additional context in comments.

7 Comments

@Svetlio right now i have done. same for the data value also.
No I had already tried semicolon, colon, inverted commas almost everything but it is giving same error "Undefined index: ad_id"
yes I copied your code to my file but it is giving same error.
@user2673943 you cann't get the data directly on the view page you need to get the data on controller's action then send it to view page. may be this is the issue. see this : stackoverflow.com/questions/12301639/…
ok I tried that also I changed $_POST to Yii::app()->request->getPost('ad_id'); Now no error is shown but when I echo Yii::app()->request->getPost('ad_id'); nothing is displayed.
|
0

Neither your URL or ad_id contain quotes so it won't work. Try this:

<script>
function testing(col) {
    $("#bookId").val(col);
    $.ajax({
            type: 'POST',
            url: "<?php echo Yii::app()->createUrl('siteaccess/create') ?>",
            data: {ad_id:"<?php echo "hello" ?>"},
            success: function(col){console.log(col)},
    });
}
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.