Juspeeh Juspeeh - 1 month ago 4
Ajax Question

Using ajax to run a php file and output php on page

I'm trying to run a php file with ajax and have text output from the php file into my container. I've looked into multiple examples but still don't get anything out of my ListTranslations.php file.

Short explanation of what is supposed to happen:

On index.php file I run a list of all languages found in database and fill onclick function with a specific language. On click the ajax function should run my ListTranslations.php file and output the list of all the translations found for the specific language.

Here is the index.php where the ajax function is called:

foreach($languages as $language){
echo '<a href="index.php?id='. $language . '"target="_self" onclick="sendLanguage(\'' .$language. '\')">' . $language . '</a>' . ': ' . count($language) . "<br>";
}


ajax function: ( I have a content div set )

function sendLanguage(tongue) {
jQuery.ajax({
url: "ListTranslations.php",
method: 'GET',
data: {language: tongue},
contentType: 'application/json; charset=utf-8',
dataType: 'json'
}).done(function(r){
$('#content').html(response);
}).fail(function(e){
console.log(e);
});
}


ListTranslations.php file:

if($_GET["tongue"]) {
$aPoem = $poems->find(array('language'=>($_GET["tongue"])));
foreach($aPoem as $poem) {
echo '<a href="testi.php?id=' . $poem["_id"] . '" target="_self">' . $poem["title"] .'</a><br>';
}
}


I have no clue what I'm doing wrong and why it is not working so any help is much appreciated!

Answer

First of all, declare if your div is of a class or id content:

$(".content");
$("#content");

Also, your function argument isn't used in the whole structure and you use only 'tongue' string; to pass a variable, get rid of '' like:

data:{language: tongue}

Also, any particular reason to use deprecated jQuery methods? If not, you should use this structure:

function findDifferentNameThanAjax(tongue) {
  $.ajax({
    url: "ListTranslations.php",
    method: 'GET',
    data: {language: tongue},
    contentType: 'application/json; charset=utf-8', 
    dataType: 'json'
  }).done(function(r){
    $('#content').html(response);
  }).fail(function(e){
    console.log(e);
  });
}

Alse, make sure if your ajax url is correct.