Mario Ene
Mario Ene

Reputation: 853

Send php variable to javascript Ajax in HTML page

I have a HTML page with javascript function:

<script type="text/javascript">
/* <![CDATA[ */
  function voteCounter(messageID)
  {
    $.get("./_vote/counter_ajax.php?messageID="+messageID, function(data){
       alert(data);
    });
  } 
/* ]]> */  
</script>

My PHP file 'counter_ajax.php':

<?php

require "../lib/config.php";

$STB = $config['dbTableNames']['votes'];

$DBServer = $config['dbConnection']['host'];
$DBUser = $config['dbConnection']['user'];
$DBPass = $config['dbConnection']['pass'];
$DBName = $config['dbConnection']['name'];

$messageID = $_GET['messageID'];

$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);

$resultUp = $db->query("SELECT SUM(voteUp) AS voteUp FROM $STB WHERE messageID = '$messageID'")->fetch_object()->voteUp;
$resultDown = $db->query("SELECT SUM(voteDown) AS voteDown FROM $STB WHERE messageID = '$messageID'")->fetch_object()->voteDown;

echo json_encode("Positive: " . $resultUp . " .... Negative: " . $resultDown);

?>

If I run PHP file in browser is working, the result is filled with text and variables:

Positive: 3 .. Negative: 2

But the response in HTML in alert box is this, without variables:

Positive: .. Negative:

What is the right approach?

Upvotes: 1

Views: 709

Answers (2)

Himanshu Saini
Himanshu Saini

Reputation: 812

JQuery Ajax functions are designed to identify the response type(html, json, xml etc.) according to the mine type/content type sent by server in header of response.

In your case you have not set any content type so JQuery function was unable to figure out the json response.

On PHP side you can do :

$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

OR at jQuery side you can use jQuery.getJSON() that always assumes that server response is in json.

Also there is option in jQuery.get() to set the datatype in the fourth parameter like:

 jQuery.get( url [, data ] [, success ] [, dataType ] )

Upvotes: 1

LIMEXS
LIMEXS

Reputation: 181

Given your php output is json, data variable will be json object and alert will not convert data object to string. Try this:

<script type="text/javascript">
/* <![CDATA[ */
  function voteCounter(messageID)
  {
    $.get("./_vote/counter_ajax.php?messageID="+messageID, function(data){
       alert(data.Positive);
    });
  } 
/* ]]> */  
</script>

Here is relevant documentation: https://api.jquery.com/jquery.get/#example-5

Upvotes: 1

Related Questions