Matei
Matei

Reputation: 372

Sending data from javascript to Controller Yii

I'm trying to send an array to an action from a controller in Yii but I'm getting 404 all the time. This is how I'm sending the data from javascript:

$.ajax({
    url: baseUrl + '/user/validateUser',
    data: $('#usr').val(),
    type: 'post',
    dataType: 'json',
    success: function(res)
    {
        console.log(res);
    }
});

In my UserController i have the following action:

public function actionValidateUser() {
    if ($_POST > 0){
        $username = $_POST['username'];
        var_dump($username);
    }
}

I'm getting this response:

Request URL:http://localhost/myapp/user/validateUser
Request Method:POST
Status Code:404 Not Found

What am I doing wrong? In Zend I did this and it worked just fine. Here ... I don't know.

Upvotes: 1

Views: 893

Answers (2)

chris---
chris---

Reputation: 1546

Seems like your apache rewrite rules are not correct/present. Create/edit the file named .htaccess under your htdocs folder. Put the following in it:

Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php

Save it and restart apache. Make sure you have mod_rewrite enabled in your apaches httpd.conf.

Upvotes: 1

Callebe
Callebe

Reputation: 1097

your ajax call receive a string as data, and there is not information about which field this string represent. You should indicate which field this data represents.

Try the code below:

$.ajax({
    url: baseUrl + '/user/validateUser',
    data: { username: $('#usr').val() },
    type: 'post',
    dataType: 'json',
    success: function(res)
    {
        console.log(res);
    }
});

your original request is generating some call to //localhost/myapp/user/validateUser?<username>. but the code above will generating a call to //localhost/myapp/user/validateUser?username=<username>

Upvotes: 0

Related Questions