I'm trying to pass my topic variable from this javascript function to my php file faqs.php. I know you can do this with a form, however this function is called when clicking text on the html page. I've tried AJAX but it didn't work for me and I feel like there must be a simpler way.
getFaqs function:
function getFaqs(topicId, topic) {
$("#topic-container").html("");
//insert javascript to send 'topic' to php file here
$.getJSON("faqs.php", function(data) {
if(data == "") {
$("<div>", {class: "list-group-item", text: "Please add FAQs."}).appendTo($("#topic-container"));
}
$.each(data, function(faqId, faq){
$("<div>", {id: "faq" + faqId, class: "list-group-item", text: faq}).appendTo($("#topic-container"));
});
});
return false;
}
faqs.php:
<?php
header('Content-Type: application/json; charset=utf-8');
//insert some php to get 'topic' here
if(isset($_POST['topic'])){
$topic=$_POST['topic'];
$clean_topic = preg_replace('/\s+/', '', $topic);
}else{
echo json_encode("Please enter a topic!");
}
$musicalinstruments = array("Question1"=>"What is the best musical instrument in the world?", "Answer1"=>"The English concertina", "Question2"=>"How many double bass players does it take to change a light bulb?", "Answer2"=>"None, the piano player can do that with his left hand");
$programminglanguages = array("Question"=>"Why do programmers confuse halloween and christmas?", "Answer"=>"Because Oct 31 = Dec 25");
$varietiesofpizza = array("Question"=>"Should I eat more pizza?", "Answer"=>"Yes. Always.");
echo json_encode ($topic);
?>
topicsin JavaScript code?