0

Everything is going well with my ajax code when passing variables, lets say "hello world" but when passing a variable containing such as "hello world http//www.facebook.com" leads to many problems actually.

Actually its the variable "new_textarea" that I am having problem with. To clarify things out say,

var new_textarea = "hello world"; //successfully saves it to database

but when

var new_textarea = "http://www.facebook.com" // will lead to problems

This is my ajax code:

$.ajax({
url: '/learns/quickpostcomment/'+user_discussion_id+'/'+user_id+'/'+new_textarea+'/'+parent_id,
success: function(data){
}});

And this is my cakephp:

public function quickpostcomment()
{
    $post = $this->params['pass'];
    $this->ClassroomComment->create();
    $this->ClassroomComment->set('classroom_id', $post[0]);
    $this->ClassroomComment->set('user_id', $post[1]);
    $this->ClassroomComment->set('comment', $post[2]);
    $this->ClassroomComment->set('parent_id', $post[3]);
    $this->ClassroomComment->save();
    die;
}

So far all that I inspected is that whats triggering the problem is the "/" or slashes on the variables when variables contain a url.

Is there any way I can pass a variable to my ajax containing slashes or url? I need help badly :(

electricfeel1979
  • 179
  • 2
  • 4
  • 17

2 Answers2

2

Try using encodeURIComponent() around your variable new_textarea. See this answer for more information on using encodeURI() and encodeURIComponent.

In your quickpostcomment() action you may need to use the urldecode() function on $post[2]. I can't remember if cake does this automatically for you, but I doubt it does.

Community
  • 1
  • 1
Josh
  • 1,794
  • 3
  • 17
  • 31
2

I think you should send a POST request with Ajax instead of a GET. If you build the posted data correctly, you could event get them in your action as you get data from standard Cake forms.

jQuery.ajax({   
    url     : "<?php echo Router::url(array('controller' => 'learns', 'action' => 'quickpostcomment'), true); ?>,
    type    : "POST",
    cache   : false,
    data    : "data[ClassroomComment][user_discussion_id]=" + user_discussion_id + "&data[ClassroomComment][user_id]=" + user_id + "&data[ClassroomComment][new_textarea]=" + new_textarea + "&data[ClassroomComment][parent_id]=" + parent_id,
    success : function(data){

    }
};

The posted data would then be available in you controller in:

$this->request->data['ClassroomComment']
nIcO
  • 5,001
  • 24
  • 36
  • thank you so much!!! this is what I came up with $.ajax({ type: "POST", url: '/learns/quickpostcomment/', data: "data[ClassroomComment][user_discussion_id]=" + user_discussion_id + "&data[ClassroomComment][user_id]=" + user_id + "&data[ClassroomComment][new_textarea]=" + new_textarea + "&data[ClassroomComment][parent_id]=" + parent_id, success: function(data){ alert("Okay!"); } – electricfeel1979 Nov 15 '12 at 17:53