3

I'm trying to implement a custom suggestion engine using jquery.

I take the user input, call my codeigniter v2 php code in order to get matches from a pre-built synonyms table.

My javascript looks like this:

var user_str = $("#some-id").val();

$.ajax({
    type: "POST",
    url: "http://localhost/my-app/app/suggestions/",
    data: {"doc": user_str},
    processData: false
})
.done(function (data)
{
    // Show suggestions...
});

My PHP code (controller) looks like this:

function suggestions()
{
    $user_input = trim($_POST['doc']);
    die("[$user_input]");
}

But the data is NOT posted to my PHP :( All I get as echo is an empty [] (with no 500 error or anything)

I've spent 2 days looking for an answer, what I've read in SO / on google didn't help. I was able to make this work using GET, but then again, this wouldn't work with unicode strings, so I figured I should use POST instead (only this won't work either :()

Anyone can tell me how to fix this? Also, this has to work with unicode strings, it's an important requirement in this project.

I'm using PHP 5.3.8

TheDude
  • 3,045
  • 4
  • 46
  • 95

2 Answers2

2

Try using the $.post method, then debug. Do it like this:

JS

var user_str = $("#some-id").val();
var url = "http://localhost/my-app/app/suggestions";
var postdata = {doc:user_str};
$.post(url, postdata, function(result){
    console.log(result);
});

PHP

function suggestions(){
    $user_input = $this->input->post('doc');
    return "MESSAGE FROM CONTROLLER. USER INPUT: ".$user_input;
}

This should output the message to your console. Let me know if it works.

CodeGodie
  • 12,116
  • 6
  • 37
  • 66
  • Thanks, I followed your approach, and did some digging. I have it working now, even with unicode POSTed strings, but I had to turn off this `csrf_protection`, which is really not ideal as far as I'm aware. Any idea how to make it work *without* disabling the csrf_protection? – TheDude Feb 19 '15 at 21:16
  • nice!.. glad i could help. – CodeGodie Feb 19 '15 at 21:16
  • in that case, you need to find a way to filter and clean your $user_input before you send it back to the front end. Look into utf8_encode/utf8_decode – CodeGodie Feb 19 '15 at 21:27
  • I did, please take a look at the code that I just posted. Thanks for your help, I really appreciate your time man :) – TheDude Feb 19 '15 at 21:34
0

For those interested, this works for me, even with csrf_protection being set to true

var cct = $.cookie('csrf_the_cookie_whatever_name');
$.ajax({
    url: the_url,
    type: 'POST',
    async: false,
    dataType: 'json',
    data: {'doc': user_str, 'csrf_test_your_name': cct}
})
.done(function(result) {
    console.log(result);
});
TheDude
  • 3,045
  • 4
  • 46
  • 95