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.
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.
Website coding surely is awesome and I recently rialized that JavaScript and Ajax are really essential elements in order to build a outstanting website. I've done the research on internet, but the results weren't that useful. Every code included Jquery, which I don't comprehend. Also JSON is slightly unclear regarding the objects, etc.
W3schools published a few examples on how to generate an Ajax code that reacts with a PHP file. This data is retrieved through 'resonseText'. However this element only retrieves one unselected PHP string.
Is there a method to select specific variables or values from the PHP file and accordingly send it back to the Javascript (Ajax) file, so I can subsequently utilize them for further Javascript coding.
Thank you in advance. (It would greatly help, since Ajax is such a complex form of JavaScript.)
My Ajax code, to send data to the PHP file
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 (this.readyState == 4 && this.status == 200) {
var XMLResponse = this.responseText ;
document.getElementById("nameInputNote").innerHTML = "Status: " + XMLResponse ;
}
} ;
xmlhttp.open("GET","ajaxIndex.php?rq1="+valueNameInput,true) ;
xmlhttp.send() ;
The PHP code:
<?php
$rq1 = $_GET['rq1'] ;
if (empty($rq1) ) {
} else {
$sql1 = "SELECT userName FROM users WHERE userName = '{$rq1}' " ;
if ($result1 = mysqli_query($connection, $sql1) ) {
$resultsSql1 = mysqli_num_rows($result1) ;
if ($resultsSql1 == 0) {
echo "vacant" ; //select this value with JS
$permission = "true" ; //and select this value separately with JS
} else {
echo "occupied" ; // or in this senario: select this value
$permission = "false" ; // and this value
// In this case the $permission variable is needed to determine whether a form should be submitted or not.
}
}
}
Try with
let src = <?php echo json_encode($yourVar); ?>;
And then use that variable. Other ways you can do that is to use axios, cookie or VueJS and pass data into component. Hope that helps.
I changed the GET methods into POST in php and ajax files but the logical error here is that every time I add a student into the database it doesn't work. I can't really figure out the problem because I'm new to AJAX.
Here's my code:
php file for adding
<?php
//I changed to POST
$q1=$_POST["q1"];
$q2=$_POST["q2"];
$q3=$_POST["q3"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("stud", $con);
$sql="INSERT INTO stud_info(IDno, LName, FName) VALUES ('$q1', '$q2', '$q3')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
getting the stud id
<?php
$q=$_POST["q"]; //I changed to POST
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("stud", $con);
$sql="SELECT * FROM stud_info WHERE IDno like '".$q."%'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>IDno</th>
<th>LName</th>
<th>FName</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['IDno'] . "</td>";
echo "<td>" . $row['LName'] . "</td>";
echo "<td>" . $row['FName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
JavaScript for ajax It doesn't work very well
// JavaScript Document
var xmlHttp;
function showStud(id)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="getStud.php";
url=url+"?q="+id;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
function addStud(id, ln, fn)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="addStud.php";
url=url+"?q1="+id+"&q2="+ln+"&q3="+fn;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
function editStud(id, ln, fn)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="editStud.php";
url=url+"?q1="+id+"&q2="+ln+"&q3="+fn;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
function deleteStud(id)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="deleteStud.php";
url=url+"?q="+id;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
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;
}
There are few things I would like to point out. First you are executing the function stateChanged here:
xmlHttp.onreadystatechange=stateChanged;
and assigning the RESULT of that function (which in this case is undefined) to xmlHttp.onreadystatechange.
Now, when the readystate changes, XMLHttpRequest attempts to call onreadystatechange which is now undefined, so nothing will happen.
Try this:
function stateChanged(){
return function(){
if(xmlHttp.readyState==4){
if (xmlHttp.status==200){
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
}
}
Now, you are still assigning the result of the function to http.onreadystatechange, but this time it is a callable function instead of undefined.
And second, to POST data like an HTML form, add an HTTP header with setRequestHeader(), and specify the data you want to send in the send() method, like this:
// Example of deleteStud(id) function
var url="deleteStud.php";
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange=stateChanged();
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("q="+id);
Edited:
For example, your showStud function would be like this,
function GetXmlHttpObject(){
// your code
}
function stateChanged(){
return function(){
if(xmlHttp.readyState==4){
if (xmlHttp.status==200){
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
}
}
function showStud(id)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null){
alert ("Browser does not support HTTP Request");
return;
}
var url="getStud.php";
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange=stateChanged();
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("q="+id);
}
So change your other functions accordingly.
Re-edited:
There are few additional key things you need to know.
1) The correct order of calls is:
new XMLHttpRequest
xmlHttp.open()
xmlHttp.onreadystatechange = ...
xmlHttp.send()
In some browsers, calling .open clears any event handlers on it. This allows for clean re-use of the same xmlHttp object, which is supposedly more memory-efficient (but that really doesn't matter if you code properly to let the GC do its job). So, simply put the .open call before the onreadystatechange assignment and you should be good to go.
2) onreadystatechange isn't just fired once. It's fired multiple times, you need to be able to handle that. These are the codes you need to handle:
0 UNSENT - open()has not been called yet
1 OPENED - send()has not been called yet
2 HEADERS_RECEIVED - send() has been called, and headers and status are available
3 LOADING Downloading - responseText holds partial data
4 RESPONSE is ready - The operation is complete
Hence your error check should be inside the xmlHttp.readyState==4 check, like this:
if(xmlHttp.readyState==4){
if (xmlHttp.status==200){
// your code
}
}
POST method via JS XMLHttpRequest compared to GET is a bit different.
Just a quick untested example:
GET
url=url+"?q1="+id+"&q2="+ln+"&q3="+fn;
xmlHttp.open("GET",url,true);
xmlHttp.send();
POST
url=url; // stays the same
xmlHttp.open("POST",url,true);
xmlHttp.send(q1="+id+"&q2="+ln+"&q3="+fn); // params go into .send()
You can find working examples at w3schools.com
Based on your source
addStud function is missing xmlHttp.setRequestHeader
and xmlHttp.send string is missing & connecting parameters
like so:
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("q1="+id+"&q2="+ln+"&q3="+fn);
Undefined index: q in the $q=$_POST["q"]; in the php file
Maybe because you are using q1 in your php file while on the javascript file you are using q only or vice versa. Make it the same and it should work fine.
And don't forget to add this before xmlHttp.send :
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
You changed your requests to post - but it seems that you didn't change the placement of your paramters. You still attach them to your url:
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
You send "null" in the request body.
You will need to send the paramters in the body to make it work as expected by you. Refer to this: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp for further information.
Edit: Small (non-tested) Example:
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("q=test?data=asd?moredata=das");
Update: Since you attached the dropbox folder / content I tried it.
You are still missing the essential function seRequestHeader as listed above. After adding this i am able to read the POST data.
Example for your code:
xmlHttp.open("POST","getStud.php",true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("q="+id);
IMPORTANT: The seRequestHeader function needs to be called AFTER the open function and BEFORE the send function.
Endpoint dumps the POST variable and displays content as proof that it works
Here I am retrieving values of database using AJAX and PHP. I stored the path of images like photos/image1.jpg in database. While retrieving that data from database and sending them back that data is not getting printing back as it has backslashes or fronth slashes in them. So what is the process to send that data back to main pages which contain special characters while using AJAX?
My JavaScript code:
function getdata(eve)
{
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("grayscreen").innerHTML=xmlhttp.responseText;
} }
xmlhttp.open("GET","picdetails.php?q="+eve,true);
xmlhttp.send();
My PHP code
<?php
include 'config.php';
$query2="select * from Sampletable where sublabel= '".$_GET['q']."'";
$query=mysql_query($query2);
if(mysql_num_rows($query)>0)
{
$count=0;
while($res= mysql_fetch_array($query))
{
if($count==0)
{
$ans= "<img src=". $res['image']."\>";
echo $ans;
}
else {
echo "<img src=".$res['image']." style='display:none'/>";
}
$count=$count+1;
}
}
?>
Here $res['image'] is the path of image which is like images/image1.jpg which will be retrived from database.
Output in the screen is
"<img src="\\">"<img src="style='display:none'/">
But output is supposed to be
<img src="images/images1.jpg"/> <img src="images/images2.jpg" style='display:none'/>
The problem is the data which is retrieved from are images/images1.jpg and images/images2.jpg which is not getting echoed back as it has front slash in it.
How to print that data?
Change:
$ans= "<img src=". $res['image']."\>";
To:
$ans= '<img src="'. $res['image'] .'"/>';
This should work.
Hope it helps!
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 ;)