Get variable from PHP file using JQuery/AJAX
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.
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/. :)