AJAX issue : button doesn't responsed anymore - javascript

Last night I had issue with registration where php was saving null data to my database when ajax was used but with a help of stack overflow the issue was resolved. I was sending data in url and rather than using $_GET i used $_POST, problem solved so this morning I thought lets do the same with login page but this time when I add ajax to it the login button it does nothing, it just clicks and does nothing
what I was trying to do was when user login with correct info it goes to home page index.php but when the user try to log in with wrong info then it echo invalid. so I was trying to echo it in index.php rather than taking user to new page.
the following is the code i was working on.this one is saved as index.php where user puts there details.
<?php
if (!isset($_SESSION['uid'])) {
echo "<form action='login_parse.php' method='post' style='display: inline-block'>
Username: <input type='text' name='username' id='username' />
Password: <input type='password' name='password' id='password' />
<input type = 'button' value='login' id='submit' onclick='hello2()'/>";
echo "</form>";
echo "<form action='signup.php' method='post' style='display: inline-block'>";
echo "&nbsp";
echo "<input type='submit' name='submit' value='Signup'>";
echo "</form>";
echo "<div id='ack1'></div>";
} else {
echo "<form style='display: inline-block'>";
echo "<p>You are logged in as ".$_SESSION['username']."";
echo "</form>";
echo "<form action='logout_parse.php' method='post' style='display: inline-block'>";
echo "&nbsp";
echo "<input type='submit' value='logout'>";
echo "</form>";
}
?>
this one is saved as ajax.js
function loadXMLDoc()
{
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");
}
return xmlhttp;
}
var HTTP = loadXMLDoc();
function hello2(){
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "login_parse.php?username="+username+"&password="+password;
HTTP.onreadystatechange=function()
{
if (HTTP.readyState==4 && HTTP.status==200)
{
document.getElementById("ack1").innerHTML=HTTP.responseText;
}
}
HTTP.open("POST", url ,true);
HTTP.send();
}
and at last this one is saved as login_parse.php
<?php
session_start();
include_once("connect.php");
if (isset($_POST['username'])) {
$username = mysql_real_escape_string( $_GET["username"]);
$password = mysql_real_escape_string( md5 ($_GET["password"]));
$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) == 1) {
$row = mysql_fetch_assoc($res);
$_SESSION['uid'] = $row['id'];
$_SESSION['username'] = $row['username'];
header("Location: index.php");
exit();
} else{
echo "INVALID login information.";
exit();
}
}
?>
am I doing something wrong, do I have to use ajax just to echo invalid in index.php

Here are the fixes for the ajax code not displaying the invalid login message.
First i removed the function call for the hello2 function and placed in a javascript event at within a script tag at the bottom of the page. This made it easier for me to conduct tests. You will have to add the id submit-button to your button html.
The previous echo in your index php file will look like this now.
echo "<form action='login_parse.php' method='post' style='display: inline-block'>
Username: <input type='text' name='username' id='username' />
Password: <input type='password' name='password' id='password' />
<input id='submit-button' type = 'button' value='login' id='submit' />";
Here is the javascript that will before the closing body tag of your index.php file:
<script src="ajax.js"></script>
<script>
//return XMLHTTP request and store it
var HTTP = loadXMLDoc();
//on click event for #submit-button
var submitEvent = document.getElementById("submit-button").onclick = function(){
hello2(HTTP);
};
</script>
This is were I found the main problem. I made the variable xmlhttp have global scope by placing it at the top your ajax.js code.
I found this problem initially by changed the following line of code:
document.getElementById("ack1").innerHTML= HTTP.responseText;
to:
document.getElementById("ack1").innerHTML= "it worked";
By doing this I discovered that your function call at this point was working but your HTTP.onreadystatechange=function(){} was unable to access the responseText.
Here is the new ajax.js file code below:
//moved variable outside of functions to give it the global scope
var xmlhttp;
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function hello2(HTTP){
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "login_parse.php?username="+username+"&password="+password;
HTTP.onreadystatechange=function()
{
if (HTTP.readyState===4 && HTTP.status === 200){
document.getElementById("ack1").innerHTML= HTTP.responseText;
}
};//<--was missing a semicolon ;
HTTP.open("POST", url ,true);
HTTP.send();
}
Fix for PHP code so that you don't have to refresh index.php to show the You are "logged in as ..." message.
Place this php code before any other php code in you index.php file so that you can access your session variables.
//start the session so that you can echo session variables on this page
session_start();

Related

Pass a current page's php variable through to XMLHttpRequest2 (i.e. $user_id)

I am trying to figure out if a current page's php $var can be passed through to the XMLHttpRequest2. The file that is being called is located outside of the views(where the current php page is located) folder in the /assets/js directory. I am using CodeIgniter as well. Trying to pass the $user_id along to use in a SQL query in side the XMLHttpRequest2 requested file.
publication_call.php (current file)
<form>
<input type="hidden" id="someid" value="<?= $idz ?>"/>
<?php
echo form_label('Validation: (Enter Publication keywords, Matches will appear in Dropdown > )');
echo form_label('Matching<br>Publications:');
?>
<select name="matched_pub" id="matched_pub"></select>
</form>
<script>
jQuery(function($){
//still want to bind the change event
$('#matched_pub').bind('change', function(){
$('#title').val($('#matched_pub option:selected').text());
});
$('#validation').keyup(function() {
showKeywords( $('#validation').val() );
document.getElementById('matched_pub').style.display='block';
});
});
</script>
<script>
function showKeywords(str)
{
if (document.getElementById("matched_pub")) {
if (str.length==0)
{
document.getElementById("matched_pub").innerHTML="";
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
xmlhttp2.send();
}
}
</script>
searchwords.php (requested/external file)
<?php
$user = 'root';
$pass = 'root';
$db = 'hey_there';
$host = 'localhost';
$conn = mysql_connect($host, $user, $pass);
$db_selected = mysql_select_db($db, $conn);
//trying to display special chars
mysql_query("set names 'utf8'");
if(!$db_selected) {
echo 'broke';
}
//echo 'db connected';
$q = $_GET["b"];
//explode and parse $q into all the fragments separated by spaces and do full text search +word1 +word2 +word3, this will ignore HTML tags as it ignores word order, will also solve the middle initial problem [db setup is not compatible with full text search, but can do likes per word, less efficient, but how it must be done]
$queryWords = explode(' ', $q);
//for services query, explode the query into words and search for each separately
$query = "SELECT DISTINCT(pub_title)
FROM teacher_publications
JOIN users ON teacher_publications.user_id = users.id
WHERE keywords IS NOT NULL
AND pub_title IS NOT NULL
AND teacher_publications.user_id = 103 <-- $var will go here
";
$queryServicesLoop = '';
$queryServicesEnd = ' ORDER BY pub_title ASC';
//loop through all words in string
foreach($queryWords as $queryWord) {
$queryServicesLoop .= " AND (keywords LIKE '%{$queryWord}%')";
}
$queryServices = $queryServices.$queryServicesLoop;
$queryServices = $queryServices.$queryServicesEnd;
$resultServices = mysql_query($queryServices);
$services ='';
if(mysql_num_rows($resultServices) > 0){
while($rowServices = mysql_fetch_assoc($resultServices)) {
$services .= '<option value="' . $rowServices['pub_title'] . '">' . $rowServices['pub_title'] . '</option>';
}
}
if( mysql_num_rows($resultServices) == 0 )
{
echo '<option value="">Your search failed to find any matching results.</option>';
}
else
{
echo '' . $services . '';
}
/* ==============================
Edited Code
============================== */
publication_call.php (current file)
<input type="hidden" id="someid" value="<?= $user_id ?>"/>
<script>
function showKeywords(str)
{
if (document.getElementById("matched_pub")) {
if (str.length==0)
{
document.getElementById("someid");
document.getElementById("matched_pub").innerHTML="";
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid'), true);
// xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
xmlhttp2.send();
}
}
</script>
searchwords.php (requested/external file)
$usr = $_GET["user_id"];
$query = "SELECT DISTINCT(pub_title)
FROM teacher_publications
JOIN users ON teacher_publications.user_id = users.id
WHERE keywords IS NOT NULL
AND pub_title IS NOT NULL
AND teacher_publications.user_id = ".$usr."
";
You can put $user_id inside of a hidden input field, and using Javascript, read the value of it to use in your Ajax request
You can do it like this:
<input type="hidden" id="someid" value="<?= $user_id ?>
And then after you've done that, you can get the value by doing this:
document.getElementById('someid'); using plain Javascript or $('#someid').value(); if you use jquery
This will get you the user ID value which you can then use in the request.
Like so:
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid').value, true);
Replace your current xmlhttp2.open with the one above
Now you can access the value of user ID in $_GET['user_id'] in the requested file.

AJAX page reload

I am creating a forum in which the posted user has option to delete his own posts. So, I am using ajax to send get request to delete a particular post and I am echoing null in place of the deleted post. The problem here is the post is getting deleted but the page is reloading after deletion which shouldn't happen as I am using ajax request. Can anyone help?
PHP CODE TO DISPLAY THE POSTS(ONLY A PART)
$sql = "SELECT * FROM classposts where branch='$branch' and joindate='$year' and class='$class' order by".$orderby." desc";
$result = $connection->query($sql);
if(isset($_SESSION['username'])){
$username=$_SESSION['username'];
}
while($row = $result->fetch_assoc()) {
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "-----------------------------------</br>";
echo "-----------------------------------</br>";
echo "Posted By: ".$row['user']."&nbsp&nbsp&nbsp&nbsp";
if($username==$row['user']){
echo "<a href='classwall.php' onclick='deletepost(".$row['id'].")' >DELETE POST</a>&nbsp&nbsp&nbsp";
}
Ignore if any parenthesis are not matching as this is only a part of the code.
javascript function which is called after delete link is clicked
function deletepost(postid){
var r=confirm("Are you sure you want to delete the post?");
if(r==true){
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("postspan"+postid).innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","deletepost.php?pid="+postid,true);
xmlhttp.send();
}else{}
}
deletepost.php page
$pid=$_GET['pid'];
$query="delete from dubiousposts where id='$pid'";
$sql=mysqli_query($connection,$query);
$query="delete from genuineposts where id='$pid'";
$sql=mysqli_query($connection,$query);
$query="delete from posts where id='$pid'";
$sql=mysqli_query($connection,$query);
if($result=mysqli_fetch_array($sql)){
echo "";
}
You have given the ahref link to calsswall.php page that's why you goes to other page.
change
echo "<a href='classwall.php' onclick='deletepost(".$row['id'].")' >DELETE POST</a>&nbsp&nbsp&nbsp";
to
echo "<a href='javascript:void(0);' onclick='deletepost(".$row['id'].")' >DELETE POST</a>&nbsp&nbsp&nbsp";

Redirection in an ajax called page

I have read quite a bit and I still am missing something.
I have a page that has a button on it. When you click the button it will call an AJAX function that will then wait and refresh every 5 seconds in waiting for a MySQL database change. Once the change in the database is made, I would like to take the user to a new page all together.
I have tested the refreshing for the database changes and they work great with echos. I have tried to use windows.location and the php header redirect. Neither are working.
I am not using jquery for the ajax call. Any help would be greatly appreciated.
Thank you
code:
index.php
<?php
session_start();
$_SESSION = array(
'player' => 0
);
?>
<!DOCTYPE HTML>
<html>
<head>
<script src="ajax.js"></script>
<title></title>
</head>
<body>
<div id="join"><button type="button" onclick="startGame()">Throwdown!</button></div>
</body>
</html>
rpsjoin.php
<?php
include("db.php");
session_start();
$lastId_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT MAX(id) AS id from game'));
$lastId = $lastId_q['id'];
$gameStatus_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT game.game_status FROM game WHERE game.id =' . $lastId));
$gameStatus = $gameStatus_q['game_status'];
if ($gameStatus == 2) {
mysqli_query($con, "INSERT INTO game (game_status, player1_joined) VALUES(1,1)");
$_SESSION['player'] = '1';
$playerNumber = $_SESSION['player'];
$lastId_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT MAX(id) AS id from game'));
$lastId = $lastId_q['id'];
$_SESSION['lastId'] = $lastId;
} elseif ($gameStatus == 1 && $_SESSION['player'] != 1) {
mysqli_query($con, "UPDATE game SET player2_joined = 1 WHERE id = " . $lastId);
$_SESSION['player'] = '2';
$playerNumber = $_SESSION['player'];
$_SESSION['lastId'] = $lastId;
}
$player1_join_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT player1_joined FROM game WHERE game.id =' . $lastId));
$player2_join_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT player2_joined FROM game WHERE game.id =' . $lastId));
$player1_join = $player1_join_q['player1_joined'];
$player2_join = $player2_join_q['player2_joined'];
echo $lastId . "<BR>";
echo $gameStatus . "<BR>";
echo $player1_join . "<BR>";
echo $player2_join . "<BR>";
if ($player1_join == 1 && $player1_join == $player2_join) {
echo '<form action="rpsover.php" method="post">
<button type="submit" name="player" value="1">Rock</button>
<button type="submit" name="player" value="2">Paper</button>
<button type="submit" name="player" value="3">Scissors</button>
</form>';
} else {
echo "Locating player. Please be patient";
}
echo session_id();
?>
function startGame() {
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("join").innerHTML=xmlhttp.responseText;
setTimeout('startGame()',1000);
}
}
xmlhttp.open("GET","rpsjoin.php",true);
xmlhttp.send();
}
At the end of rpsjoin.php, instead of showing a form, i want to be redirected to another page.
Yes I know my code is bad and there are test echos in it.
Thank you

dynamic select list AJAX and insertion in database table through posting form

I am wondering to find a solution for my dynamic select list of cities, now I am successfully populated the cities but now unable to post the selected city to database.
here is php file:
<html>
<head>
<script type="text/javascript" src="show_cities.js"> </script>
</head>
<body>
<?php
session_start;
//library
include("conn.php");
?>
<form enctype='multipart/form-data' action='posting_process.php' method='post'>");
<!-- **************************** Country select list ********************** -->
Country:
<select name="country" onChange="showCities(this.value)">
<?php $sql = 'SELECT country_no, country_name FROM country '.'ORDER BY country_no';
$rs = mysql_query($sql);
echo "<option value='0'>"."Select a Country"."</option>\n ";
while($row = mysql_fetch_array($rs))
{
echo "<option value=\"".$row['country_no']."\">".$row['country_name']."</option>\n ";
}
?>
</select>
City: <div id="txtCity" class="city_no">
<input type=submit name=action value=Post>
</body>
</html>
here is javascript: show_cities.js
// JavaScript Document
/* <script type="text/javascript"> */
function showCities(str)
{
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("txtCity").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_cities.php?q="+str,true);
xmlhttp.send();
}
/* </script> */
here is php file: get_cities.php
<?php
session_start;
//library
include("conn.php");
$q=$_GET["q"];
$sql="SELECT * FROM city WHERE country_no = ".$q;
$result = mysql_query($sql);
echo "<select name='city'>";
while($row = mysql_fetch_array($result))
{
echo "<option value=\"".$row['city_no']."\">".$row['city_name'] . "</option>\n";
}
echo "</select>";
?>
I don't know how to mention the following which return / display the city
regards:
Why don't you use the jQuery Ajax to send the data to the backend php code and receive the response.
Your php code seems fine, I would suggest to use the following mechanism to work with ajax.
Please add id as "countrylist" to your country list in the front end html page.
And use the following code instead of your javascript for ajax calls.
$(function (){
$('#countrylist').change(function() {
var sel_val=$("#countrylist").val();
$.ajax({
url: 'get_cities.php?q='+sel_val,
success: function(data) {
$('#txtCity').html(data);
}
});
});
});
Also make sure you have added the jquery libraries before adding this javascript code.
Hope this helps.
Thanks

window.XMLHttpRequest combine with script .change

I have a problem with combinning two scripts.
Fisrt script is working perfectly and taking stuf from mysql:
<script type="text/javascript">
function showUser(str)
{
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','includes/test-search.php?q='+str,true);
xmlhttp.send();
}
</script>
The second one is working perfectly and it's simple script for inserting data after change:
<script type="text/javascript">
$("document").ready(function(){
$("#selection").change(function () {
$("#someDivName").html( $("#selection option:selected").val() );
});
});
</script>
now the hole point is to combine them.
It's look like, when I load the site it don't have id selection and second script stops but after taking data from php and mysql file test-search.php the missing id selection is on site but the first script is not checking if id selection apear and don't work.
The php code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("table", $con);
$sql="SELECT * FROM prod_models WHERE prod_main_group_id = '".$q."'";
$result = mysql_query($sql);
echo '
<select id="selection" name="prod_main_group_id" onchange="change_val()">
<option value="">Wybierz produkt</option>
';
while($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id'].'">';
echo $row['product_name'] . "</option>";
}
echo "</select>
";
mysql_close($con);
?>
Code to display changed script:
<input type="text" id="someDivName" value="" />
if any one can help with solving the problem will be realy nice.
Thx i'm waiting for it now and trying to solve this for my self but now I don't have other ideas for it.

Categories

Resources