Jump to content

Passing PHP variables back to jQuery

- - - - -

  • Please log in to reply
7 replies to this topic

#1
datalogi

datalogi

    Newbie

  • Members
  • Pip
  • 6 posts
Hi, could someone help me how to pass following variables back to jQuery from PHP-file,
which I was called from jQuery.

$sql = $dbh->prepare("SELECT merkki, vuosimalli FROM autot");
$sql->execute();
$row = $sql->fetch();
$merkki = $row['merkki'];
$vuosimalli = $row['vuosimalli'];

#2
Vaielab

Vaielab

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 547 posts
We'll need to see how you cann this page with jquery

#3
datalogi

datalogi

    Newbie

  • Members
  • Pip
  • 6 posts
Ok, let me explain.

This is jQuery code:
function search () {
$.get("search.php?ID=", function(data){
// return data from PHP file
});
}

And this is PHP-file search.php
<?php
$sql = $dbh->prepare("SELECT merkki, vuosimalli FROM autot");
$sql->execute();
$row = $sql->fetch();
$merkki = $row['merkki'];
$vuosimalli = $row['vuosimalli'];
?>

#4
Vaielab

Vaielab

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 547 posts
In this case, simply do a echo of your variable, and it will be in the variable data

#5
datalogi

datalogi

    Newbie

  • Members
  • Pip
  • 6 posts
But i need to echo to variables: $merkki and $vuosimalli

I think it's possible to echo only one variable....?

#6
Vaielab

Vaielab

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 547 posts

echo($merkki);

echo($vuosimalli);

To split them back in your jquery you could separate them with a comma, or any other char...

If you'd like a more elegant method, you chould do something like this

echo(json_encode(array('merkki' => $merkki, 'vuosimalli' => $vuosimalli)));

and in your jquery you read it with jQuery.parseJSON(data);

#7
datalogi

datalogi

    Newbie

  • Members
  • Pip
  • 6 posts
So now I have:
$character = " | ";

echo($merkki);
echo($character);
echo($vuosimalli);


jQuery output is: "Toyota | 2008"

So how can I parse Toyota to one jQuery variable and 2008 to another jQuery variable?

#8
Orjan

Orjan

    Writes binary right handed and hex left handed

  • Moderators
  • 3,299 posts
  • Location:Karlstad, Sweden
  • Programming Language:C, Java, C++, C#, PHP, JavaScript, Pascal
  • Learning:Java, C#
Do it the JSON way described above and fix the rest in the javascript, i'd say.
__________________________________________
I study Information Systems at Karlstad University when I'm not on CodeCall




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users