Jonathan Nielsen
Jonathan Nielsen

Reputation: 1502

Fetch data from db using ajax jquery

I've got some issues fetching a value from db by using ajax in my jquery script.

index.php:

<?php include 'db/db_connection.php';?>
<?php include 'db/db_getvalues.php';?>

<div class="arrow">
  <img src="img/arrow_left.png" />
</div>

<div class="text-box"></div>

script.js

$(document).ready(function () {
  $(".arrow").click(function () {
    $.ajax({
      type: "GET",
      url: "../db/db_getvalues.php", // This is the correct path, but do jquery recognize "../db/" etc?
      dataType: "text",
      success: function (response) { // Here is where i'm lost, what do i need to write to update my innerHTML with the returned value from the db_getvalues.php-file?
        $(".text-box").html(response);
      }
    });
  });
});

db_getvalues.php // This file works, i've selected data directly from html-file

<?php
  function getdbvalues() {
    $query = 'SELECT * FROM mydb WHERE Id = 1';
    $fetch = mysql_query($query) or die ('Could not find tablerow');
    $row = mysql_fetch_assoc($fetch);

    $textString = $row['Text'];

    return $textString;
  }
?>

Upvotes: 1

Views: 5180

Answers (2)

Sami
Sami

Reputation: 8419

You have to make sure 1. your click function working 2. your ajax request is success ful 3. php is producing some html to be received by ajax success function 4. your php code is giving you (echoing) required html

Check my lines having comments(1,2,3,4) added in your code

$(document).ready(function () {
  $(".arrow").click(function () {
  alert("I am called"); //1
    $.ajax({
      type: "GET",
      url: "../db/db_getvalues.php", 
      dataType: "text",
      success: function (response) { 
      alert(response+" __ url is fine");//2
        $(".text-box").html(response);
      }
    });
  });
});



<?php
  echo "php is called"; //3
  function getdbvalues() {
    $query = 'SELECT * FROM mydb WHERE Id = 1';
    $fetch = mysql_query($query) or die ('Could not find tablerow');
    $row = mysql_fetch_assoc($fetch);

    $textString = $row['Text'];

    return $textString;
  }
echo getdbvalues(); //4
?>

Upvotes: 0

MH2K9
MH2K9

Reputation: 12039

Yes, AJAX recognize such URL. Your ajax seems ok but a little suggestion to change in db_getvalues.php. You should echoing the value instead of return. I suggest you to call the getdbvalues() function & to echo it like below.

In db_getvalues.php

function getdbvalues() {
    $query = 'SELECT * FROM mydb WHERE Id = 1';
    $fetch = mysql_query($query) or die ('Could not find tablerow');
    $row = mysql_fetch_assoc($fetch);
    $textString = $row['Text'];
    return $textString;
}

echo getdbvalues(); //Added

Upvotes: 2

Related Questions