I am trying to display a PHP echo in a textarea using AJAX that auto refreshes every second. So far everything I do this doesn't want to work and I get nothing in the textarea.
Here is my code:
<?php
$stmt = mysqli_prepare($db_conx,"SELECT message FROM chat WHERE asker = ?");
$stmt->bind_param('s', $asker);
$stmt->execute();
$stmt->bind_result($message);
/* fetch values */
while ($stmt->fetch()) {
$currvalue[] = array('message'=>$message);
}
echo $message;
echo '333333333';
?>
HTML code:
<textarea id="chattercontent" style="width:90%; height:150px; resize:none;" readonly></textarea>
AJAX/jQuery code:
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php",
dataType: "text", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(load, 1000)
}
});
}
load();
});
</script>
What happens with the code above, I get the echo '333333333'; in my textarea like so 333333333 which is good and fine. But I don't get the echo $message; in my textarea.
I have checked to see if the MySQL table and column to see if its not empty and I can confirm that it is not empty and it has some values in it.
I also, viewed the file.php page directly from the browser and it does echo $user_message; properly. But it doesn't get echoed in AJAX call and in my textarea.
Could someone please advise on this issue?
Your $message variable is not being assigned anywere
replace your echo $message; with
print_r($currvalue);
and you will see your output.
In other words, you $message variable contains nothing! (assign it something with $message = 'someting';)
Related
This is my code below for page.php file.
<?php session_start(); ?>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/jquery.colorbox.js"></script>
<script type="text/javascript" src="js/new-landing.js"></script>
<script type="text/javascript">
var ans1 = "home";
function aa(){
$.post("ajax.php", { "ans": "test" }, function(data){
alert("Posted");
}, "html");
};
</script>
<a href="#" id="q1" onClick="javascript:aa();" >click</a>
and this is where i want to see if my data is posted.
<?php
session_start();
$te = $_POST['ans'];
$_SESSION['demo'] = $te;
echo "<pre>".print_r($_SESSION,'/n')."</pre>";
?>
when i click the anchor tag. the alert box is shown. but when i refresh the ajax.php page. it shows an error..Notice: Undefined index: ans in ajax.php on line 3
and the print of session is also empty.
Array(
[demo] =>
)
but when i refresh the ajax.php page. it shows an error
It sounds like you want to set the session variable when a value is posted, and get the session variable otherwise:
<?php
session_start();
if (isset($_POST['ans'])) {
$te = $_POST['ans'];
$_SESSION['demo'] = $te;
}
echo "<pre>".print_r($_SESSION,'/n')."</pre>";
?>
$.post and $.get are just shorthand versions of the more structured $.ajax(), so I prefer using the latter. The additional structure keeps me straight.
Since you are using jQuery anyway, I would re-structure your code like this:
$('#q1').click(function() {
var test = "Hello there";
$.ajax(function() {
type: "POST",
url: 'ajax.php',
data: 'ans=' +test+ '&anothervarname=' + anothervarvalue,
success: function(recd_data) {
alert('Rec'd from PHP: ' + recd_data );
}
});
});
Note that the data: line is for example purposes and does not match with your code -- just showing you how to pass variables over to the PHP side.
Of course, the above includes removing the inline javascript -- never a good idea -- from your anchor tag HTML, thus:
<a href="#" id="q1" >click</a>
Also, on the PHP side, you can verify that things are working by adding a test at the top. Matching with the data: line in the example AJAX code, it would look like this:
ajax.php
<?php
$a = $_POST['ans'];
$b = $_POST['anothervarname'];
$response = '<h1>Received at PHP side:</h1>';
$response .= 'Variable [ans] has value: ' . $a . '<br>';
$response .= 'Variable [anothervarname] has value: ' . $b . '<br>';
echo $response;
Important: Note the use of echo, not return, to send values back to the AJAX script.
Also note that you must deal with the stuff returned from PHP in the AJAX success: function ONLY. If you need access to that data outside of the success: function, then you can stick the data into a hidden <input type="hidden" id="myHiddenInput"> element, like this:
success: function(recd_data) {
$('#myHiddenInput').html(recd_data);
}
Here are some additional examples of simple AJAX constructions:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});
I Have a problem here. I try to show up the information box using DIV after successfully save the data to mysql.
Here my short code.
// Mysql insertion process
if($result){?>
<script type="text/javascript">
$(function() {
$.ajax({
$('#info').fadeIn(1000).delay(5000).fadeOut(1000)
$('#infomsg').html('Success.')
});
}
</script>
<?php }
How can DIV appear? I tried but nothing comes up. Any help? Thank you
a basic jQuery ajax request:
$(function() {
$.ajax({
url: "the url you want to send your request to",
success: function() {
//something you want to do upon success
}
});
}
lets say you have a session of ID and you want to retrieve it in your database.
here is: info.php
<input type="hidden" name="id"><input>
<input type="submit" onclick="showResult(id)" value="Click to Show Result"></input>
function showResult(id){
$j.ajax(
method:"POST",
url:"example.php",
data: {userid:id},
sucess: function(success){
$('#infomsg').html(Success)
});
}
<div id= "infomsg"></div>
example.php
$id = $_POST['userid']; ///////from the data:{userid :id}
//////////config of your db
$sql = mysql_query("select * from users where id = $id");
foreach ($sql as $sq){
echo $sq['id']."<br>";
}
the "infomsg" will get the result from the function success and put it in the div.
<!doctype html>
<html>
<head>
<title>jQuery Tagit Demo Page (HTML)</title>
<script src="demo/js/jquery.1.7.2.min.js"></script>
<script src="demo/js/jquery-ui.1.8.20.min.js"></script>
<script src="js/tagit.js"></script>
<link rel="stylesheet" type="text/css" href="css/tagit-stylish-yellow.css">
<script>
$(document).ready(function () {
var list = new Array();
var availableTags = [];
$('#demo2').tagit({tagSource:availableTags});
$('#demo2GetTags').click(function () {
showTags($('#demo2').tagit('tags'))
});
/*
$('li[data-value]').each(function(){
alert($(this).data("value"));
});*/
$('#demo2').click(function(){
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: alert("OK")
});
});
function showTags(tags) {
console.log(tags);
var string = "";
for (var i in tags){
string += tags[i].value+" ";
}
var list = string.split(" ");
//The last element of the array contains " "
list.pop();
}
});
</script>
</head>
<body>
<div id="wrap">
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
?>
<div class="box">
<div class="note">
You can manually specify tags in your markup by adding <em>list items</em> to the unordered list!
</div>
<ul id="demo2" data-name="demo2">
<li data-value="here">here</li>
<li data-value="are">are</li>
<li data-value="some...">some</li>
<!-- notice that this tag is setting a different value :) -->
<li data-value="initial">initial</li>
<li data-value="tags">tags</li>
</ul>
<div class="buttons">
<button id="demo2GetTags" value="Get Tags">Get Tags</button>
<button id="demo2ResetTags" value="Reset Tags">Reset Tags</button>
<button id="view-tags">View Tags on the console </button>
</div>
</div>
</div>
<script>
</script>
</body>
</html>
This code will just transfer the list of items in the dostuff.php but when I try to print_r it on PHP nothing won't come out. why is that?
I am doing an ajax request on this line
$('#demo2').click(function(){
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: alert("OK")
});
});
and the code in PHP
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
?>
This is just a shot in the dark, given the limited information, but it would appear that you're expecting something to happen with the data sent back from the server.. but you literally do nothing with it. On success, you have it display an alert... and nothing else.
Try changing your success entry to the following:
success: function(data) {
$("#wrap").html(data);
}
This will fill the div with the data from the POST request. The reason it shows up as nothing as it is..., you aren't loading the currently executing page with the data needed for the print_r to actually echo anything.
Edit: How to insert values into database;
Database interaction now-a-days is done with either custom wrappers, or the php Data Object, also referred to as PDO, as opposed to the deprecated mysql_* functions.
First, you prepare your database object, similar to how a connection is done in the aforementioned deprecated functions:
$dbh = new PDO("mysql:host=hostname;dbname=database", $username, $password);
Then, you can begin interaction, preparing a query statement..
$stmt = $dbh->prepare("UPDATE table_name SET column1 = :column1 WHERE id = :id");
Binding a parameter in said statement..
$stmt->bindParam(':column1', $column1);
$stmt->bindParam(':id', $id);
$id = $_POST['id'];
And finally executing the query:
try {
$stmt->execute();
}
catch (Exception $e) {
echo $e;
}
PDO auto-escapes any strings bound in the prior statements, making it save from SQL-injection attacks, and it speeds up the process of multiple executions. Take the following example:
foreach ($_POST as $id) {
$stmt->execute();
}
Since the id parameter is already bound to $id, all you have to do is change $id and execute the query.
Where where you expecting the PHP result of print_r to "come out"?
Try changing your AJAX call to this (only the value of success is different):
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: function(data, textStatus, jqXHR){
alert(data);
}
});
With this, the output of your PHP template, which you would normally see if you posted to it the old fashioned way (ie. with a form and a full page reload), will display in an alert.
Hope that helps.
Try to add encodeURI for the jQuery part,
$.ajax({
url: "demo3.php",
type: "POST",
data: { items: encodeURIComponent (list.join("::")) },
success: function(response) {
console.log(response);
}
});
And urldecode for the PHP part:
$lis = $_POST['items'];
$liarray = explode("::", urldecode($lis));
print_r($liarray);
3 things:
Set your AJAX's success to show the echos/prints given in your PHP script
success: function(result)
{
$("#somecontainer").html(result);
}
That way ANYTHING that gets printed in a PHP script otherwise, will be put in i.e.
<div id="somecontainer">
Result of PHPcode here
</div>
Second, instead of
var string = "";
for (var i in tags)
{
string += tags[i].value+" ";
}
var list = string.split(" ");
//The last element of the array contains " "
list.pop();
use push(). This adds the value at the next unoccupied index in the array:
var string = "";
for (var i in tags)
{
list.push(tags[i].value);
}
That way you don't have to pop the last element off.
Third point: put your PHP code in a separate file (and your JavaScript/jQuery as well). Have like:
/root/index.html
/root/script/dostuff.php
/root/script/myscript.js
then let your AJAX call to url: "/script/dostuff.php"
So... thanks to one of stackoverflow users I tried to implement this fancy feature into my existing Codeigniter application...
In my View I have this:
<script type="text/javascript">
$(function() {
$(".submit_op").click(function() {
var dataString = $("#op_form").serialize();
var url = "<?php echo site_url('submit/insert_data'); ?>";
$.ajax({
type: "POST",
url: url+"/"+dataString,
data: dataString,
cache: false,
success: function(html){
//$("div#op").prepend(html); //PROBLEM HERE???
$("div#op").prepend("<div>TEST</div>");
$("div#op div:first").fadeIn("slow");
//$("#debug").append("<font color=green><b>OK!</b></font> : " + dataString + "<br/>");
},
error: function(html){
//$("#debug").append("<font color=red><b>ER!</b></font> : " + dataString + "<br/>");
}
});
return false;
});
});
</script>
<div id="debug"></div>
<?php
//here goes some data from db... newly added div should go in top of other divs
foreach ($some_data_sent_from_controller as $var) {
echo "<div id=\"op\">";
echo "<table width=\"100%\" border=\"0\">";
//showing data
echo "</table>";
echo "</div>";
}
echo "<form action=\"#\" id=\"op_form\">";
//some clickable stuff...
echo br().form_submit('submit', 'OK', 'class="submit_op"');
echo "</form>";
In my Controller I have a function which handles data sent from View:
function insert_data($input) {
$this->load->model('blah_model');
//processing serialized data and sending it to corresponding tables via Model
$this->blah_model->add_to_table($some_data);
$this->blah_model->add_to_another_table($some_other_data);
}
And the Model is not a biggy :)
function add_to_table($data){
//processing data...
$insert = $this->db->insert('my_table', array('array_which_contains_actual_data'));
if ($insert == TRUE) {
return TRUE;
} else {
return FALSE;
}
}
//etc.
As far as I can tell, my problem is not in my M-V-C pattern, since every time I submit a form the data is correctly inserted in all possible tables in my relational db... But the newly added row just won't show up unless I refresh a page.
I think that I'm doing something wrong inside of my jQuery.ajax lines... If I run my script with this line $("div#op").prepend("<div>TEST</div>"); and when I submit a form, I get desired result - text TEST shows up on top of my page every time I submit... But if I change that line to $("div#op").prepend(html); nothing show up until refreshing...
What am I doing wrong here??
Thanks a lot for any help!
wow, this was probably pretty lame from me... But in the end I figured out that I have to echo out my result in controller, not return it... So when I change the function in my controller into
function insert_data($input) {
$str = "<div>KILLROY WAS HERE!</div>";
echo $str; // <----- !!!!!!
}
I can see a message on my page...
Now to other things... Thanks for self-brainstorming :)