I have a problem, the solution might be very simple but I just can't find it for a couple of hours already. Basically I have an Ajax post to a controller. I want the data sent with Ajax to be taken from a with class ".theme-h1" from my page, so I have this
function get_video_reviews_data(){
something = $(".theme-h1").text();
alert(something);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>main/video_reviews_data",
dataType: 'json',
data: { title: something },
})
.done(function(data) {
alert(data.title);
get_video_reviews_videos(data);
}); }
In this situation, my controller does not see $_POST['title'] for some reason. If I change the second line to this:
something = "some text";
then I can see $_POST['title'] in my controller. I also tried changing this:
data: { title: something },
to this:
data: { title: $(".theme-h1").text() },
and it still doesn't work. Seems like I can only have a value between quotes for the variable I'm sending.
Please help me out :) Thank you!
Try encasing your value in parenthesis:
function get_video_reviews_data(){
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>main/video_reviews_data",
data: {
title:($(".theme-h1").text())
}
}).done(function(data) {
alert(data.title);
get_video_reviews_videos(data);
});
}
Not sure why, but I found by encasing it in parenthesis it magically will allow for calling jQuery methods when it wouldn't before.
Also, notice I got rid of datatype:'json'
. Don't leave that up to intelligent guessing (which is really what jQuery does, it is far from bulletproof), explicitly declare it in the header for the file:
header('Content-type: application/json');
Which is bulletproof. I also noticed you had a trailing comma after the data
object, so I removed that as well.
Please check on console that $(".theme-h1").text() returns something as a string.
UPDATE: Please remove the additional comma after $data in the answer below and try again...
also, do you use firebug to debug your code in the browser? If so, what does your "Post" information show?
Try this:
something = $(".theme-h1").text();
$data = "&title=" + encodeURIComponent(something);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>main/video_reviews_data",
dataType: 'json',
data: $data,
})
.done(function(data) {
alert(data.title);
get_video_reviews_videos(data);
}); }