Get variable from PHP file using JQuery/AJAX
Asked Answered
G

1

12

This is my first post here and I hope that someone will be able to help me. For the past week I have been working on a project of mine. Apparently, I have stuck with the last part.
So basically, I have an AJAX chat and when I submit a line I send (using a Post method) the whole line to be analyzed (to a file named analysis.php).
The chat line is being analyzed and find the variable I needed by doing queries on a MySql Database.
All I need now, is to have this variable taken with JQuery-AJAX and put it on a div in my html file(so it can be displayed on the right-left-whatever of the chat).

Here are my files :
analysis.php

<?php
$advert = $row[adverts];
?>

ajax-chat.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX Chat</title>

<link rel="stylesheet" type="text/css" href="js/jScrollPane/jScrollPane.css" />
<link rel="stylesheet" type="text/css" href="css/page.css" />
<link rel="stylesheet" type="text/css" href="css/chat.css" />

</head>

<body>

<div id="chatContainer">

    <div id="chatTopBar" class="rounded"></div>
    <div id="chatLineHolder"></div>

    <div id="chatUsers" class="rounded"></div>
    <div id="chatBottomBar" class="rounded">
        <div class="tip"></div>

        <form id="loginForm" method="post" action="">
            <input id="name" name="name" class="rounded" maxlength="16" />
            <input id="email" name="email" class="rounded" />
            <input type="submit" class="blueButton" value="Login" />
        </form>

        <form id="submitForm" method="post" action="">
            <input id="chatText" name="chatText" class="rounded" maxlength="255" />
            <input type="submit" class="blueButton" value="Submit" />
        </form>

    </div>

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="js/jScrollPane/jquery.mousewheel.js"></script>
<script src="js/jScrollPane/jScrollPane.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>

So, I am basically trying to get the $advert from the analysis.php file(after the whole analyze is done) , and by using JQuery/AJAX pass it eventually to the ajax-chat.html file. Any help is really appreciated. I have googled everything but haven't found something to help me. Thanks in advance.

Gutta answered 26/4, 2012 at 21:6 Comment(3)
You cannot put anything in your HTML file: by the time AJAX is running, your HTML file does not exist, it has been sent to the browser, which will have created its own internal data structure. What you can do is run some Javscript in that browser which will update the structure. I don't speak JQuery, so I can't advise you specifically.Pindus
Thank you for your answer...Just to make it more clear: Let's say that this chat is something like mood detector. If the line is analyzed and found out that the user's mood is good, then the $advert will have the value "good" and it should somehow retrieved and put into a div in the html and displayed to the user. If that makes it more clear.Gutta
Yes, I understand what you are trying to do: that is the kind of problem that Ajax was invented to solve. I was just trying to warn you of a conceptual mistake that I thought you might be making (but I may be wrong), that you were somehow doing something to that HTML file. You cannot: all you can do is modify the DOM in the browser which was created from that HTML.Pindus
M
35

If I understand right, you need to use JSON. Here is a sample.

In your PHP write:

<?php
// filename: myAjaxFile.php
// some PHP
    $advert = array(
        'ajax' => 'Hello world!',
        'advert' => $row['adverts'],
     );
    echo json_encode($advert);
?>

Then, if you are using jQuery, just write:

    $.ajax({
        url : 'myAjaxFile.php',
        type : 'POST',
        data : data,
        dataType : 'json',
        success : function (result) {
           alert(result['ajax']); // "Hello world!" alerted
           console.log(result['advert']) // The value of your php $row['adverts'] will be displayed
        },
        error : function () {
           alert("error");
        }
    })

And that's all. This is JSON - it's used to send variables, arrays, objects etc between server and user. More info here: http://www.json.org/. :)

Marsupial answered 26/4, 2012 at 21:13 Comment(6)
Note: PHP 5.2+ required for json_encode($var) OR PHP 4.3+ with PECL 1.2+ extension. @erik1001 its also a good idea to link the documentation for the OP php.net/manual/en/function.json-encode.phpPoi
If, instead of the alert(result['ajax']), we use $('#the_div_I_want').html(result); , will this variable be displayed in this specific html div of mine?Gutta
Of course it will. You can even send HTML from serverside and display it where you want.Marsupial
I have simplified your Jquery part into this, $.ajax({ url : 'php/analysis.php', success : function (result) { alert("You are getting a reply!"); }, error : function () { alert("error"); } }) in order to see what's the response. The fact is that I am getting a response, but it is a whole bunch of things that I don't need. Even though i did json_encode($the_variable_I_needed) to the php file. How can I specifically retrieve only the variable I need? Thanks again.! :Gutta
Another issue is that I don't want to pass variables using the AJAX, just receive those variables from the already analyzed text (inside the php file), in which there will be the variable I need to retrieve.Gutta
What is the $the_variable_you_need and what is displayed in browser's console after successful request and $.ajax({success : function(result) { console.log(result); }}) ? And if you don't want to send data with AJAX request, just skip "data" property and display the variable you've received.Marsupial

© 2022 - 2024 — McMap. All rights reserved.