How to send data through ajax function in JavaScript - javascript

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.

Related

why does my browser reloads when using ajax?

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

Undefined _POST variable when using XMLHttpRequest()

I am trying to use Ajax to insert data into database with POST method. But php can not recognize the post variables.
ajax:
function createUser() {
var _id=document.getElementById('new_id').value;
var _name=document.getElementById('new_name').value;
var params = "id="+_id+"&name="+_name;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
console.log(xmlhttp);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if(xmlhttp.responseText=="")
alert("New User is created!");
else
document.body.innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","resource/create_profile.php",true);
xmlhttp.send(params);
}
php:
<?php
$id = $_POST["id"];
$name = $_POST["name"];
$conn = oci_connect(....);
$query = "....";
$result = oci_parse($conn, $query);
oci_execute($result);
oci_close($conn);
?>
if i uncomment the request header content type then nothing happens, no error is shown. if i comment it then php shows error. i am giving a screenshot.
http://imgur.com/CdKO84V
what am i supposed to do? if i use get method then it is working good but i can not use it since i need to upload file.
At last I have found the solution! I had to add the setRequestHeader() method below the open method. So in the end the code looks like:
xmlhttp.open("POST","resource/create_profile.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

new to ajax, Object not found,

Hey guys I'm trying to work with AJAX for my first time using Javascript, PHP, and HTML. I have created the following code, and saved it in the htdocs folder in xampp. xampp is up and running but every time I navigate to localhost/foodstore.html nothing works I just get the error "Object not found!" I've Checked my code over a few times with a tutorial Im following, and found and corrected quite a few errors. I was wondering if the Object not found is because of my code or something else I am doing wrong. This is also my first time really using PHP and xampp. Also is there any other method that you would recommend to learn AJAX?
HTML
<html>
<head>
<script type= "text/javascript" src="foodStore.js"></script>
</head>
<body onload="process()">
<h3>Quaff Bucket</h3>
Enter the food you are looking for:
<input type="text" id="userInput"/>
<div id="underInput"/>
</body>
</html>
PHP
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('bacon','beans','chicken');
if(in_array($food,$foodArray)){
echo 'we do have'.$food.'!';
}
elseif($food==''){
echo 'Please Enter a food you idiot!';
}
else{
echo 'we do not have'.$food.'punk!';
}
echo'</response>';
?>
JS
var xmlHttp= createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp= new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("Cant create the object");
}
else{
return xmlHttp;
}
}
function process(){
//states 4 and 0 mean that the object is free for communication
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
//get the info from the web page
food = encodeURICompnent(document.getElementById("userInput").value);
// (Request type,where it is sending,should it be handled asynchronously)
xmlHttp.open("GET","foodstore.php?food="+food,true);
xmlHttp.onreadystatechange =handleServerResponse;
xmlHttp.send(null);
}
else{
//wait 1 second before trying again
setTimeout('process()',1000);
}
}
function handleServerResponse(){
//4= done communicating
if(xmlHttp.readyState==4){
//200= Object is ok
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
//response is the only child in the xml page data= the response that would be genterated from the PHP
message = xmlDocumentElement.firstChild.data;
//makes underInput= to message
document.getElementById("underInput").innerHTML='<span style ="color:blue">'+message +'</span>';
setTimeout('process()',1000);
}else{
alert('something went wrong');
}
}
}

Google Maps arcsine formula with SQL error

The following is my php code with SQL.
$con=mysqli_connect("localhost","root","","ananas");
if (mysqli_connect_errno()) {
echo json_encode(mysqli_connect_errno());
}
$sql = "SELECT venues.*, (6371*acos(cos(radians(".$curr_lat."))*cos(radians(venues.lat))*cos(radians(venues.longi)-radians(".$curr_longi."))+sin(radians(".$curr_lat."))*sin(radians(venues.lat)))) AS radius
FROM venues
HAVING radius < ".$radius ;
$result = mysqli_query($con,$sql);
if (!$result) {
die("Error running $sql: " . mysql_error());
}
I ve verified all the database, table names and column names I wanna extract are working fine. Even same code was working fine before I reinstalled xampp and reset my phpmyadmin with DB.
But now even with older setting, i.e. after restoring the same database, tables, username & password as before I get an error. It shows error when I try calling it from JS file using xmlhttprequest object.
The following is my JS function for calling the PHP file through xmlhttp
function loadXMLDoc(city)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
myData= eval("(" + xmlhttp.responseText + ")");
console.log(myData);
$('#header_bottom_wrapper .nav span').html(city);
mapMarkers(myData);
map.fitBounds(circle.getBounds());
loadPlaces();
getVenues();
}
else{
alert(status+", "+exception);
}
}
xmlhttp.open("GET","./content/sessionVariableChange.php?city="+city+"&curr_lat="+curr_lat+"&curr_longi="+curr_longi+"&radius="+radius+"&capacity="+capacity,true);
xmlhttp.send();
}
sessionVariableChange.php is the name of php file where I access my database.
When I try to run the file, I get the following error in my console.
**Uncaught SyntaxError: Unexpected token ) **
Any help would be helpful. Thanks in advance.

Javascript AJAX responseText problem in IE

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 ;)

Categories

Resources