i created an ajax function that when clicked by a user it adds a messages to his favorites tab. i want it to work similar to a twitter like button so when a user clicks the favorite button it does not reload the page. i created everything correctly and even the ajax function calls the php file and inserts everything into the database, its just that it still reloads the page after the clicking.
my ajax code:
<script>
function GetXmlHttpObject() {
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e)
{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
}
r eturn xmlHttp;
}
function ajaxfav(){
var xmlHttp=GetXmlHttpObject();
var url="favorite.php?message="+document.msgidform.fav_message.value;
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
alert("Message is favorited");
}
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
</script>
my php code:
$user_id = $_SESSION['active_user_id'];
extract($_POST);
extract($_GET);
if(isset($_GET['message']))
{
$id=$_GET['message'];
$q=$db->prepare("SELECT msgid,date,text
FROM messages
WHERE to_id=? and msgid=?");
$q->bindValue(1,$user_id);
$q->bindValue(2,$id);
$q->execute();
$row2=$q->fetch();
$d=$row2['date'];
$fav_questionq=$db->prepare("SELECT *
FROM messages
LEFT JOIN users
ON messages.to_id=users.id
WHERE users.id=? AND messages.msgid=?
");
$fav_questionq->bindValue(1,$user_id);
$fav_questionq->bindValue(2,$id);
$fav_questionq->execute();
$frow=$fav_questionq->fetch();
$fquestion= $frow['text'];
$result = $db->prepare("SELECT * FROM fav_messages
WHERE username=? AND message=?");
$result-bindValue(1,$user_id);
$result-bindValue(2,$id);
$result->execute();
if($result->rowCount()== 1 )
{
$deletequery=$db->prepare("DELETE FROM fav_messages WHERE message=?");
$deletequery->bindValue(1,$id);
$deletequery->execute();
echo("<script>location.href = 'index.php?a=recieved';</script>");
}
else
{
$insertquery = $db->prepare("INSERT INTO fav_messages (username,message,fav_question,fav_date) values(?,?,?,?)");
$insertquery->bindValue(1,$user_id);
$insertquery->bindValue(2,$id);
$insertquery->bindValue(3,$fquestion);
$insertquery->bindValue(4,$d);
$insertquery-execute();
}
echo("<script>location.href = 'index.php?a=recieved';</script>");
}
my html code:
<form name="msgidform" method="post">
<input type="hidden" name="fav_message" id="" <?php echo "value= '$msg_id'"; ?>></p>
</form>
<a class="msg-icon" href="" onclick="ajaxfav();"><img
src="images/linedfav.png" id='img'></img></a>
why does my browser still reloads even though i am using ajax?
It's is because you're using <a> tag, even in you don't provide a href attribute it will redirect you, in your case to homepage that's why you have the reload effect. A way to solve it would be to create a fake anchor tag by using <span>tag that would have the styles of <a> tag and attaching your ajax function to the <span> tag
Related
i am trying to create an ajax favorite button in php similar to instagram and twitter.
my code seems to be fine and i am doing everything correctly and tried to get it working this way:
php code:
$user_id = $_SESSION['active_user_id'];
extract($_POST);
extract($_GET);
if(isset($_GET['message']))
{
$id=$_GET['message'];
$q=$db->prepare("SELECT msgid,date,text
FROM messages
WHERE to_id=? and msgid=?");
$q->bindValue(1,$user_id);
$q->bindValue(2,$id);
$q->execute();
$row2=$q->fetch();
$d=$row2['date'];
$fav_questionq=$db->prepare("SELECT *
FROM messages
LEFT JOIN users
ON messages.to_id=users.id
WHERE users.id=? AND messages.msgid=?
");
$fav_questionq->bindValue(1,$user_id);
$fav_questionq->bindValue(2,$id);
$fav_questionq->execute();
$frow=$fav_questionq->fetch();
$fquestion= $frow['text'];
$result = $db->prepare("SELECT * FROM fav_messages
WHERE username=? AND message=?");
$result-bindValue(1,$user_id);
$result-bindValue(2,$id);
$result->execute();
if($result->rowCount()== 1 )
{
$deletequery=$db->prepare("DELETE FROM fav_messages WHERE message=?");
$deletequery->bindValue(1,$id);
$deletequery->execute();
echo("<script>location.href = 'index.php?a=recieved';</script>");
}
else
{
$insertquery = $db->prepare("INSERT INTO fav_messages (username,message,fav_question,fav_date) values(?,?,?,?)");
$insertquery->bindValue(1,$user_id);
$insertquery->bindValue(2,$id);
$insertquery->bindValue(3,$fquestion);
$insertquery->bindValue(4,$d);
$insertquery-execute();
}
echo("<script>location.href = 'index.php?a=recieved';</script>");
}
javascript code:
<script>
function GetXmlHttpObject() {
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e)
{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
}
return xmlHttp;
}
function ajaxfav(){
var xmlHttp=GetXmlHttpObject();
var url="favorite.php?message="+document.msgidform.fav_message.value;
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
alert("Message is favorited");
}
}
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
</script>
HTML form and link code:
<form name="msgidform" method="post">
<input type="hidden" name="fav_message" id="" <?php echo "value= '$msg_id'"; ?>></p>
</form>
<a class="msg-icon" href="" onclick="ajaxfav();"><img
src="images/linedfav.png" id='img'></img></a>
but i kept getting an error in the console that reads:
"Uncaught TypeError: Cannot read property 'value' of undefined
at ajaxfav" but i've fixed it and now it immediately goes to the alert message, but nothing is inserted into the database, meaning that the data was not sent to the php file.
can someone advise me on what i can do?
network tab of the ajax call
please i would appreciate any help or suggestion. the php file is called but does not insert anything into the database.
You can use
document.msgidform.elements['fav_message'].value
in your ajaxfav() function to get name field value.
I'm trying to add an auto-complete function to a text field.
This used to work, but then I switched to an MVC structure and now I can't get it back to work.
PHP/HTML:
echo '<br><br>Add member:<br>'
. '<form method="post"><input type="text" name="username" oninput="findUsers(this.value)" list="livesearch">'
. '<datalist id="livesearch"></datalist>'
. '<input type="submit" value="Add">'
. '</form>';
JavaScript:
<script>
function findUsers(str) {
if (str == "") {
document.getElementById("livesearch").innerHTML = "no suggestions";
xmlhttp.send();
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","/user/search/?q="+str,true);
xmlhttp.send();
}
}
</script>
/user/search opens a function called search in the class User in the UserController.php file
class UserController extends Controller
{
public function search()
{
$response = "hello";
echo $response;
}
}
So this should put the "hello" message in the livesearch datalist.
But for some reason just nothing is happening.
If I replace the xmlhttp.open by window.open, the page does load normally and shows the hello message. But that is obviously not what I want.
Figured out the exact problem:
My xmlhttp.responseText is also returning the header of my website, which is already loaded in the MVC structure.
How would I work around this?
Is it an option to just edit the string and get the last part in javascript?
Or are there better solutions?
Used JavaScript to grab the last part of the string (so without the header)
It does what it's supposed to do now, but feels like a pretty "dirty" solution.
Also had to add the <option value=""> tag, which was in my code, but not in my testcode.
Background
I've read through several posts and tutorials here on AJAX, and I've gotten it to work great - on one page, but I'm still new to utilizing AJAX so I hit a rough spot that I can't understand how to fix.
I have my main page, ajaxtest.php which contains a drop-down with this code:
<a>
<?php
include('./db.php');
$PM = mysqli_query($con, "SELECT DISTINCT PMName FROM report WHERE PMname <> '' ORDER BY PMName ASC");
?>
<select name="PMName" onchange="showUser(this.value)">
<?php
while ($row = mysqli_fetch_row($PM)) {
$selected = array_key_exists('PMName', $_POST) && $_POST['PMName'] == $row[0] ? ' selected' : '';
printf(" <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0]);
}
?></select></a>
which pulls this function:
<script>
function showUser(str) {
if (str !==".PM") {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
Sending the selection from the database off to my second page, getuser.php.
The user then sees the rest of the initial page populated with the results of getuser.php, which contains the bulk of my code and the HTML tables populated with the SQL info.
This is working fine.
Issue
My issue stems from the fact that once (and pardon my lack of technical jargon,) getuser.php is populated into the <div> that is inside of ajaxtest.php, I can't utilize any other JavaScript or AJAX functions or the entire page just refreshes as if I were to reload ajaxtest.php again from scratch and it puts me back to the initial blank screen with the dropdown menu.
On getuser.php, within the <form> that surrounds the entire table, there is a submit button:
<form action="" method="POST" onsubmit="test()">
and
<input class="button" name="update"<?= $LineID ?>" type="submit" id="update" value="UPDATE">
and this is supposed to link to my JavaScript test() function that simply reads:
function test() {
alert("yo");
}
but when I click the button, the entire page refreshes instead of executing this function. Why is this?
If I manually go to localhost/getuser.php?q=John%20Doe instead of "having this page load inside of my ajaxtest.php <div>" and click the button, it works just fine and I get the JavaScript alert to pop up. What am I doing wrong here?
Try editing the function test() to return false
function test() {alert("yo"); return false}
and change the line
<form action="" method="POST" onsubmit="test()">
into
<form action="" method="POST" onsubmit="return test()">
Now it shouldn't refresh the page. Function used in onsubmit needs to return true or false.
I'm stuck in a problem here that I tried all google answers and nothing did this work out. Specially because I prefer to do a pure JavaScript solution if possible... I have a menu, with a cart. This menu shows something like: Your cart (0)
where 0 is the number of items inside the cart. The items number are query from a SQL table 'cart', where I save all users products added to cart. So they don't lose the items on cart when the session closes. But I want to update this menu span everytime they add something inside the cart, without the need to refresh the page. The items are being added this way:
In the table where products are displayed I have:
<td id="add'.htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8').'"> <label><b><img src="/img/cart.gif" /></b></label> </td>
so I call javascript:addtocart passing 'id' of the product as parameter. This function does:
function addtocart(id)
{
document.getElementById('add'+id).innerHTML='<b>On your cart!</b>';
load('/index.php?addtocart&id='+id);
}
Ok, function load does:
function load(url) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
eval( xmlhttp.responseText );
}
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
OK, so we have my index.php receiving the GET with id of the product to add to cart, and I do on index.php:
if (isset($_GET['addtocart']) && isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
mysql_query("INSERT INTO cart VALUES('$id', '$userid')");
}
This is working very well, and if I refresh the page, in the menu I get "Your cart (1)"... But how to do this refresh automatically when the client clicks on the table? Possible with pure javascript function?
//EDIT for index.php content:
<?php
include("./includes/header.php");
include("./includes/db.php");
?>
<html>
<head>
<link rel="stylesheet" href="./css/style.css">
<title>MyShop</title>
<script type="text/javascript">
function load(url) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('cart').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
function addtocart(id)
{
document.getElementById('add'+id).innerHTML='<b>On your cart!</b>';
load('/index.php?addtocart&id='+id);
}
</script>
</head>
<body id="home">
<?php include 'menu.php'; ?>
<div id="container">
<?php
if (isset($_GET['news']))
{
include 'news.php';
}
else if (isset($_GET['orders']))
{
include 'orders.php';
}
else if (isset($_GET['addtocart']) && isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
mysql_query("INSERT INTO cart VALUES('$id', '$userid')");
}
?>
</div>
</body>
</html>
From your index.php page, return the number of products inserted for the current user and then use the success handler of the ajax call to update the span.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// here get the number of products inserted and display in span
document.getElementById('span_id').innerHTML = xmlhttp.responseText;
}
}
EDIT
Do not make the ajax call to the same page. Have the id sent to some other page, let's say abc.php. Then keep only the php related code inside your update_cart_ajax.php page.
So your addtocart() becomes:
function addtocart(id)
{
document.getElementById('add'+id).innerHTML='<b>On your cart!</b>';
load('/update_cart_ajax.php?addtocart&id='+id);
}
update_cart_ajax.php
<?php
include("./includes/db.php");
if (isset($_GET['addtocart']) && isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
mysql_query("INSERT INTO cart VALUES('$id', '$userid')");
}
else
{
echo 0;
exit;
}
// get the number of products added to the cart for the current user
$total_products_in_cart = <value returned from db>;
echo $total_products_in_cart;
exit;
I'm trying to create a sort of chatbox system with PHP/MySql and AJAX but I'm having difficulties running my script in IE. I tested it in Google Chrome and it worked just fine. But when I test it in IE, the AJAX function that should get all messages from the database each 3 seconds, doesn't work properly. It does call the PHP script each 3 seconds and put the responseText into a div (displaying all messages found each 3 seconds). But the messages shown, are the same always ( untill I close the page and re-run the script ). Also when a new message is added to the database, it does not show up. It seems as if the responseText isn't 'updating'. These are my scripts:
(AJAX)
function getMessages(messengerid, repeat)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("messages").innerHTML=xmlhttp.responseText;
document.getElementById("messages").scrollTop = document.getElementById("messages").scrollHeight;
}
}
xmlhttp.open("GET","modules/get_messages.php?key=abcIUETH85i236t246jerst3487Jh&id="+messengerid,true);
xmlhttp.send();
if(repeat) {
setTimeout("getMessages("+messengerid+", 1);", 3000);
}
}
(PHP/MySql)
<?php
$key = "abcIUETH85i236t246jerst3487Jh";
if( ($_GET['key'] == $key OR defined('IS_INTERNAL')) AND (int)$_GET['id'] > 0) {
include_once("../config.php");
include_once("../class/system.class.php");
$sys = new system($template_name);
if(!$sys->connect($db)) {
exit();
}
$messages = $sys->getEntries("messages", " WHERE messenger_id = '".(int)$_GET['id']."' ORDER BY id ASC ");
$messenger = $sys->getEntries("messengers", " WHERE id = '".(int)$_GET['id']."' LIMIT 1");
$user1 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id1']."' ");
$user2 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id2']."' ");
$displaynames[$user1[0]['id']] = $user1[0]['displayname'];
$displaynames[$user2[0]['id']] = $user2[0]['displayname'];
foreach($messages AS $key => $message) {
if(is_numeric($key)) {
?>
<div class="message">
<b><?=$displaynames[$message['account_id']];?> (<?=date("h:m:s", $message['timestamp']);?>) says:</b> <br />
<?=nl2br($message['message_content']);?>
</div>
<?php
}
}
}
?>
Any help would be much appreciated!
Thanks in advance.
Best Regards,
Skyfe.
Your response is being cached. One way to fix this is to append a unique parameter in your request URL, such as the current timestamp.
Its a common problem with IE it caches the result.Add some dummy random parameter to your ajax call e.g current timestamp
i dont know about php but in jsp you can add the following code to your jsp page
response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
i know the post is old , i just replied for future viewers :D ;)