ajax PHP MySQL query - javascript

I need help with an ajax call, but I'm a newbie with ajax and I'm not sure as to how to do it.
I have the following PHP code (phonecall.php):
<?php
$con = mysqli_connect('localhost','root','root','mydb');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"mydb");
$sql="SELECT * FROM incoming_calls";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$callArray[] = array('phonenumber' => $row['phone_number'], 'id' => $row['phone_login_id']);
print "<div id=\"call\">";
print_r($callArray);
print "</div>"
}
mysqli_close($con);
?>
I want to make a page update in real time automatically anytime something new is posted to the table.
Here is my non-working page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Phone calls</title>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction() {
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
var ajaxDisplay = document.getElementById('call');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
setInterval(function() { //Broken
ajaxRequest.open(); //Not sure what to put here.
}, 1000);
}
//-->
</script>
</body>
</html>

Your ajaxRequest.open() method takes 3 parameters, as per the XMLHttpRequest specification:
The method of the request (POST, GET, etc)
The file you're sending your request to
Whether or not the request will be asyncronous.
So:
ajaxRequest().open('GET','yourfile.php',true);
Would build an asynchronous GET request to yourfile.php.
You're also missing the ajaxRequest().send(), which would actually send your request to the server.
There's plenty to know about this so I suggest googling it, since you seem to be lacking on the basics.

Related

xmlhttprequest not being posted to php file

I am trying to make a post request through javascript to a locally hosted php file but it seems the php file is either not receiving the data or not displaying.
I tried all sorts of ways to print with vardump print_r $_post $_request raw_http_data but nothing seems to work.
what is wrong with the code?
is the url a problem?
This is the javascript file:
const rightswipe = (n) =>{
var foo = "me";
var bar = "ft";
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function()
{
if(this.readyState === 4)
{
if(this.status==200 || this.status==201)
{
//let newData = JSON.parse(this.responseText);
//console.log(newData);
}
else{
alert("invalid link");
}
}
});
xhr.open("POST", "like.php" , true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send("to_user="+foo+"&from_user="+bar);
};
like.php is a file in the same folder:
if (array_key_exists('foo', $_POST) && array_key_exists('bar', $_POST)) {
$foo = $_POST['foo'];
$bar = ($_POST['bar']);
// do stuff with params
echo 'Yes, it works!';
} else {
echo 'Invalid parameters!';
}
also the $_post and $_request are empty;
and var_dump($_server["REQUEST_METHOD"]) returns "GET"
and am locally hosting this site with xampp ie apache and mysql
I have set up a test and your code works fine. There is just one problem that I can see and that is you post "to_user" and "from_user" parameters but in your PHP you check for "foo" and "bar" keys. Therefore in my test I get "Invalid parameters!" returned as expected.
Note: Currently your PHP is returning text so if you were to uncomment the JSON.parse line you would likely get a JavaScript error. Make sure to json_encode your response in PHP.
I am not sure what your test that showed the request method was "GET" but suspect it was not a valid test as you clearly send a POST request.
UPDATE following discussion below:
I installed the same XAMPP version mentioned on Windows 10 and setup the basic files and still cannot replicate the problem.
C:\xampp\htdocs\rightswipe.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="rightswipe.js"></script>
</body>
</html>
C:\xampp\htdocs\rightswipe.js
const rightswipe = (n) =>{
var foo = "me";
var bar = "ft";
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function()
{
if(this.readyState === 4)
{
if(this.status==200 || this.status==201)
{
let newData = JSON.parse(this.responseText);
console.log(newData);
}
else{
alert("invalid link");
}
}
});
xhr.open("POST", "like.php" , true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send("to_user="+foo+"&from_user="+bar);
};
C:\xampp\htdocs\like.php
<?php
if (array_key_exists('to_user', $_POST) && array_key_exists('from_user', $_POST)) {
$foo = $_POST['to_user'];
$bar = ($_POST['from_user']);
// do stuff with params
echo json_encode('Yes, it works!');
} else {
echo json_encode('Invalid parameters!');
}
Went to http://localhost/rightswipe.html in Chrome and opened developer tools (F12)
In the console tab I entered rightswipe(1); and saw the console log message 'Yes, it works!'
Went to network tab to check request and response:
Everything working as expected.

How to send data through ajax function in 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.

Ajax with javascript not working on wamp server

I am new to ajax and was following a youtube tutorial to create a simple food search app
where users enter food name in input field it shows the name below else it
says that food not available
but somehow its not working on wamp server ..it shows the error alert instead
here is my code
index.html
<!Doctype html>
<html lang = "en">
<head>
<title>Ajax app</title>
<meta charset = "UTF-8">
<style>
</style>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The Chuff Bucket</h3>
Enter the food you would like to order:
<input type="text" id="userInput"/>
<div id="underInput"></div>
</body>
</html>
foodstore.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("can't create that object boss");
}else{
return xmlHttp;
}
}
function process()
{
if(xmlHttp.readyState==0||xmlHttp.readyState==4){
food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET","foodstore.php?food=" + food, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout("process()",1000);
}
}
function handleServerResponse()
{
//readystate 4 whenever response is ready and object done communicating
if(xmlHttp.readyState==4){
//state 200 means communiaction went ok
if(xmlHttp.readyState==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = "<span style='color:blue'>" + message + "</span>"
setTimeout("process()",1000);
}else{
alert("something went wrong");
}
}
}
foodstore.php
<?php
header("Content-type: text/xml");
echo "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>";
echo "<response>";
$food = $_GET["food"];
$foodArray = array("tuna","bacon","beef","loaf","ham");
if(in_array($food,$foodArray))
{
echo "We do have" .$food. "!";
}
elseif($food ="")
{
echo "Enter a food please.";
}
else
{
echo"sorry but we don't even sell" . $food. "!";
}
echo "</response>";
?>
any help will be highly appreciated ,thanks
Please do NOT use xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");. Your best bet is to combine jQuery, but "ActiveXObject("Microsoft.XMLHTTP")" is obsolete (even for Microsoft environments), and unsupported on many browsers.
Here's a simple example (no jQuery):
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log('myArr', myArr);
}
};
xmlhttp.open("GET", url, true);
This syntax is supported on ALL contemporary browsers ... and has been supported by Microsoft since IE7 (since 2006).
ALSO:
You definitely want to learn about Chrome Developer Tools (part of the Chrome browser), if you're not already familiar with it:
https://developers.google.com/web/tools/chrome-devtools

Not getting a response on MDN AJAX example

I previously attempted to interact with PHP using AJAX (1st time using Javascript to any significant degree) and had no success, so I tried to start with the basics using a Mozilla Developer Network example as a test:
Example - https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
That isn't working either even though I copy-pasted it straight from the site with only one change (setting the url to my test page, running on XAMPP). When I click the button to run the MDN script, the resulting output is the alert "There was a problem with the request".
I'm using Firebug to check the result, and it shows a "200 OK" code for Status. If I understand the script correctly, shouldn't that not lead to an error message?
Here is the code from the example (along with the code from the Foundation framework I was using, in case that's somehow the issue):
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Foundation | Welcome</title>
<link rel="stylesheet" href="css/foundation.css" />
<script src="js/vendor/modernizr.js"></script>
</head>
<body>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script type="text/javascript">
(function() {
var httpRequest;
document.getElementById("ajaxButton").onclick = function() { makeRequest('http://localhost:8000/pages/test.html'); };
function makeRequest(url) {
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', url);
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
</body>
And here is the code for the test HTML page that I made:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
Test
</body>
</html>
Where am I going wrong?
EDIT - Adding the original PHP script being referenced. I originally tried to use an altered version of the MDN script on this but likewise couldn't get it to work:
<?php
require ('includes/config.inc.php');
require (MYSQL);
$u = NULL;
$P = NULL;
$u = mysqli_real_escape_string ($dbc, $_GET['username']);
$p = mysqli_real_escape_string ($dbc, $_GET['password']);
$q = "SELECT user_id FROM users WHERE (username='$u' AND password=SHA1('$p')) AND active IS NULL";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (#mysqli_num_rows($r) == 1) { // A match was made.
$a = 'True';
print json_encode($a);
} else { // No match was made.
$a = 'False';
print json_encode($a);
}
?>
2ND EDIT - Thanks for the suggestion about the console log, that did it. All I needed to do was enable CORS and now it works fine.

XMLHttpRequest error SCRIPT10

Hi all I have to connect to an external server to retrieve data.
They told me to use their script and I have to modify something because it was wrong. Now I ahve a problem when I try to lunch my request.
Return me an error into my internet explorer console
SCRIPT10: The data required for the completion of this operation are
not yet available.
This is my javascript page, the problem I think is because the query doesn't finish in time to print my result. How can I print the result when they are ready and don't return me error?
I have try to comment all my request and leave only the method "open" but the error return me every time. Why??
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
var req = null ;
function sendRequest(){
var urlStr="www.test.it";
var xmlString="";
xmlString+="<?xml version='1.0' encoding='UTF-8'?><some xml>";
createHTTPRequestObject();
var resp = getResponseText(urlStr+"?"+xmlString,null);
var xmlDoc;
xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = false;
xmlDoc.loadXML(resp);
alert(xmlDoc.xml);
}
function createHTTPRequestObject(){
req=null ;
var pXmlreq = false ;
if (window.XMLHttpRequest) {
pXmlreq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try{
pXmlreq = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e1) {
try{
pXmlreq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e2) {
}
}
}
req = pXmlreq ;
}
function getResponseText(action,query,method,async,contenttype){
if(method==null){
method="POST";
}
if(async==null){
async="true";
}
if(contenttype==null){
contenttype = "application/x-www-form-urlencoded";
}
req.open(method,action, async);
req.setRequestHeader("Content-Type", contenttype);
if(query){
req.send(query);
}else{
req.send();
}
return req.responseText ;
}
</script>
</head>
<body>
<input type="button" name="Request" value="Request" onclick="sendRequest();"/>
<div id="content" />
</body>
</html>
You are trying to read the responseText before it is ready. Looks like you are treating a asynchronous call as synchronous. That would be the issue.

Categories

Resources