Getting a null value to database when AJAX is used - javascript

I got this registration code which was working fine but I decided to add AJAX to make it more dynamic but when I run it, my PHP code was saving null value to database.
This is what I know so far: whenever a user writes information in signup page it goes to AJAX and the ajax pass it along to php and then php saves the info into database and it echo a message and then it goes to ajax and then it displays the message. All of this works the only problem is that my php code is saving null value no matter what i write in signup page.
and i think this is the code thats not working properly but i just dont know the other way
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "signip_parse.php?username="+username+"&password="+password;
the following is rest of my code. this is the page were user puts information and its saved as signup.php
<head>
<script src = "ajax.js"></script>
<div id="content">
</head>
<body>
<form action="signip_parse.php" method="post" id="registration_form">
<p>Name <input type="text" name="username" id = "username"/></p>
<p>Password <input type="password" name="password" id = "password"/></p>
<p><input type = "button" value="sign up" id="submit" onclick = "hello()"/>
<input type="button" value="Back" onclick="return back()"/></p>
</form>
<div id="ack"><p>1</p></div>
</div>
</body>
and this is the ajax code that I got it from w3school ajax example and i saved it 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 hello(){
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "signip_parse.php?username="+username+"&password="+password;
HTTP.onreadystatechange=function()
{
if (HTTP.readyState==4 && HTTP.status==200)
{
document.getElementById("ack").innerHTML=HTTP.responseText;
}
}
HTTP.open("POST", url ,true);
HTTP.send();
}
and last this is the signip_parse.php where i managed to spell signup wrong
<?php
include_once("connect.php");
$user = mysql_real_escape_string( $_POST["username"]);
$password = mysql_real_escape_string( md5 ($_POST["password"]));
$sql = "INSERT INTO users (username, password) VALUES ('$user','$password')";
if(mysql_query($sql)){
echo "You have been successfully registered";
}
else{
echo "Something went wrong try again";
}
?>
Any help would be great. thanks guys
and yes i know md5 is broken but this is just a demo and intend to used something else.

Since you're sending a request as post, its important to add this on your XMLHttpRequest object:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
And just combine them inside, no need to separate some parts. It would look something like this:
<script type="text/javascript">
function hello() {
var xmlhttp = new XMLHttpRequest();
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("ack").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST", 'signip_parse.php', true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("username="+username+"&password="+password);
}
</script>
Here's what it would look like
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Ref: https://stackoverflow.com/a/12860140/3859027
You should consider also (if you're using PHP 5.5 or greater) to use PHP's native password hashing and replace that md5() instead. If you're below v5.5 then you could use the its compatibility pack

Related

Ajax trying to execute PHP page brings me to a new page

I am trying to get a live chat working using PHP and mysql and AJAX. It is almost completely functioning, except I cant seem to figure out how to submit the chat message without reloading a page. I have a page, sendchat.php, that takes input from the previous page and enters the data into a database. I am trying to use a text input field and when the user clicks the enter key, it would execute the PHP page with the details needed to send to sendchat.php without actually loading or refreshing the page. This is what I have so far:
<form id="send-message-area">
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeydown="onChatEnter(this);"></textarea>
</form>
</div>
</td></tr></table>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
function onChatEnter(str) {
if(event.key === 'Enter') {
$.ajax({
type: "GET",
url: "sendchat.php?msg=" + str ,
success : function() {
// here is the code that will run on client side after running clear.php on server
}
});
}
</script>
All it does is try to load the url, but its not trying to find sendchat.php or send the data. Instead it just tries to load a blank page. Where am I going wrong here? Everything seems spelled correctly and case sensitive. I check if the user pressed enter when they press a key. If they did, I am loading an AJAX function to execute a PHP page. Yet, it is not doing that. Just for FYI, I do not want a button there to be clicked.
EDIT:
I tried the suggestions below and still nothing. I decided to try a different approach now. Still doesn't work.
<script>
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").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 (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","sendchat.php?msg="+str,true);
xmlhttp.send();
}
}
</script>
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeypress="updatechat(this.value);"></input>
Try this:
$("#send-message-area").submit(function(e) {
e.preventDefault();
e.stopPropagation();
});
I am not sure how.. But I fixed it.. I think it had to do with giving the input a name along with the ID. See below:
<script language="javascript" type="text/javascript">
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").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 (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
var planetloc = document.getElementById("loc").value;
chaturl = "sendchat.php?msg="+str+"&loc="+planetloc;
sendie.value="";
xmlhttp.open("GET",chaturl,true);
xmlhttp.send();
}
}
//-->
</script>
This was the code I used for the html:
<p>Your message: </p>
<input type='text' id='sendie' name='sendie' maxlength = '100' onkeypress='updatechat(this.value);'></input>
<input type='hidden' id='loc' name='loc' value='$chatroom'></input>";
I also added chaturl to combine the ajax page I needed along with the parameters passed to it. It seemed by creating a variable for that it solved other issues too.

Ajax Javascript function not being called

First question on StackOverflow so I hope i get this right. I have a AJAX call to a JS function :
function addOptionText(str)
{
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("0").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","AddText.php?q="+str,true);
xmlhttp.send();
}
And Here is my HTML code :
<body>
<FORM NAME ="form6" onclick= "addOptionText(this.value)" >
Text Input:
<INPUT TYPE = "TEXT" VALUE placeholder ="Nume Field" NAME ="Text_Field">
<INPUT TYPE = "Submit" Name = "Edit" VALUE = "Add" >
</FORM>
<p id="0"> </p>
</body>
The php file only contains :
<html>
<body>
<?php
$name = ($_GET['q']);
echo "nume";
?>
</body>
</html>
But the function doesn't appear to be used as the paragraph doesn't change. New to php here and trying to understand how it works so I'm thinking something might've slipped me.
EDIT
I had more than one "submit" id's so that's why it didn't work. I changed the "submit" id from to and now all's working as intended.
Unfortunately, your code is all over the place.
<FORM NAME ="form6" onclick= "addOptionText(this.value)" > is wrong for a multitude of reasons.
First, we don't use onclick on the form itself but on the submit button. Secondly the value you put in the parameter doesn't in any way represent the value of the text box.
Since you want just to display the value of your textbox and not to navigate to a different page, modify your <form> tag, so that it doesn't have an action = "some page" attribute, because that way it will automatically redirect you to the page you specify and thus the AJAX request is rendered useless. Instead, modify your tag so that it looks like this:
<form name = "form6" onsubmit = "return false;">Provided that you specify your input/button type to submit: type= "submit", using the onsubmit event and setting it to return false will prevent the form from sending you over to a new page.
When using Vanilla JavaScript and not jQuery, I believe its more efficient to use IDs, so as to identify your HTML elements easier in JavaScript.
Your PHP code doesn't mean anything at all. Before doing anything else, you need to evaluate if, indeed, the q was sent over to the PHP file with the GET method. To do that, use in your php file:if (isset($_GET["q"])): // Your codeendif;
The line: echo "nume" you wrote will output "nume" regardless of what you have actually sent to your php file with the AJAX request.
In my opinion is pretty useless to still provide support for Internet Explorer 5 and 6. Not many people use it, unless for whatever reason they are mentally bound to it.
Analytically, how your files should be:
HTML:
<body>
<form name = "form6" onsubmit = "return false;">
Text Input:
<input type = "TEXT" placeholder ="Nume Field" id = "textfield" name = "Text_Field"/>
<input id = "submit" type= "submit" Name = "Edit" value= "Add"/>
</form>
<p id = "0"> </p>
<script src = "YOUR JAVASCRIPT FILE" type = "text/javascript"></script>
</body>
JavaScript:
var textfield = document.getElementById("textfield");
var submit = document.getElementById("submit");
submit.onclick = function() {
'use strict';
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("0").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "AddText.php?q=" + textfield.value, true);
xmlhttp.send();
};
PHP:
<?php
if (isset($_GET["q"])):
echo ($_GET["q"]);
endif;
?>

How to load data from an XML file using php to show it in an html page with javascript

I'm doing an assigment for my programming class. I need to show a table with two columns (name and lastname) of a list of friends. This data is stored in a XML file like this:
<?xml version='1.0' standalone='yes'?>
<amigos>
<amigo>
<nombre>Alejandra</nombre>
<apellido>Ponce</apellido>
</amigo>
<amigo>
<nombre>Dalia</nombre>
<apellido>Gordon</apellido>
</amigo>
I retrieve this data with php, like this:
<table width="200" border="1">
<tr align="center">
<td>NOMBRE</td>
<td>APELLIDO</td>
</tr>
<?php
$amigos = simplexml_load_file('listaamigos.xml');
foreach ($amigos->amigo as $amigo) {
echo '<tr>';
echo '<td>',$amigo->nombre,'</td>';
echo '<td>',$amigo->apellido,'</td>';
echo '</tr>';
}
?>
I call this php file with a function written in javascript language. I'm using ajax for this homework. My javascript file is the one I'm showing below:
var xmlHttp;
function createXmlHttpRequestObject() {
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 connect to the host');
else
return xmlHttp;
}
function cargarAmigos(url)
{
if(url=='')
{
return;
}
xmlHttp=createXmlHttpRequestObject();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = procesarEventos;
xmlHttp.send(null);
}
function cargar(url)
{
if(url=='')
{
return;
}
xmlHttp=createXmlHttpRequestObject();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = procesarEventos;
xmlHttp.send(null);
}
function procesarEventos()
{
if(xmlHttp.readyState == 4)
{
document.getElementById("listaAmigos").innerHTML= xmlHttp.responseText;
}
}
I use this javascript file in a html file. I call the function cargar () in the button's onclick event, like this:
<body>
<div id="listaAmigos" >
Lista amigos
</div>
<button onclick="cargarAmigos('procedimiento.php');">Lista Amigos Ajax</button>
</body>
The problem is that the code is not working. I mean that the names are not displaying at all in the table. Actually the table does not appear.
I'm pretty sure that the error is not in the code because it was working last week and I haven't changed the code since then. But today I loaded the html page just for "fun" and it wasn't showing my list of friends.
So I decided to open another project with uses the same algorithm and this one is not working too. I've checked that all the files are in the same folder. I've checked my xammp server and it's apache and mysql services are on. I have no idea what "thing" I could have done to cause this problem.
Any help will be really appreciated.
It looks like you should escape the ' character in this line:
alert('Can't connect to the host');
i.e. rewrite it like
alert("Can't connect to the host");
You can see that there's an error even just by looking at the formatting on Stack Overflow :)
Please refer to this question for the details on why it's working like that: When to use double or single quotes in JavaScript?

unable to get parameters from javascript to php

Unable to get parameters passed from javascript to loginme.php
This is simple form in
index.php
<form method="POST">
<input type="text" id="userid" name="userid"></input>
<input type="password" id="pass" name="pass"></input>
<input type="button" value="Log in" onclick="letUserLogin()"/>
</form>
Javascript function :
myscript.js
function letUserLogin() {
var userid = document.getElementById("userid").value;
var pass = document.getElementById("pass").value;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText); //only shows 'and'
}
}
xmlhttp.open("POST","loginme.php?userid="+userid+"&pass="+pass,true);
xmlhttp.send();
}
Simple echo statement in loginme.php
loginme.php
<?php
// username and password sent from form
$username=$_POST['userid'];
$password=$_POST['pass'];
echo"$username and $password";
?>
You are passing GET parameters:
xmlhttp.open("POST","loginme.php?userid="+userid+"&pass="+pass,true);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
... thus you need to fetch them from $_GET, not $_POST:
$username=$_GET['userid'];
$password=$_GET['pass'];
You possibly want to use the send() method instead to send your data. Right now, your payload is empty:
xmlhttp.send();
You can resolve this with JQuery quite easily if you want:
This method also allows you to put the URL within the action parameter of the form and uses POST which is more secured for transferring password information:
JQUERY:
$(document).on('submit', "form", function(e){ //We add a listener
e.preventDefault();
$.post($(this).attr('action'), $(this).serialize())
.done( function( data ) {
//Do something with response
});
});
Note that you can of course change the listener to only listen to a specific form. In this case all forms submits will be caught rather than a specific one in a page.
HTML:
<form action="/path/to/loginme.php">
<input type="text" name="userid">
<input type="password" name="pass">
</form>
PHP:
$username=$_POST['userid'];
$password=$_POST['pass'];
echo "$username and $password";
You are using POST but explicitly setting the values into the query string, GET style. So basically you are sending a blank POST.
You need to send the values like this:
xmlhttp.open("POST","loginme.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("userid=" + userid + "&pass=" + pass);
try this:
var userid =encodeURIComponent(document.getElementById("userid").value)
var pass =encodeURIComponent(document.getElementById("pass").value)
var parameters="userid="+userid+"&pass="+pass
mypostrequest.open("POST", "loginme.php", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
mypostrequest.send(parameters)
use of encodeURIComponent() to encode any special characters within the parameter values.
Call setRequestHeader() and set its content type to "application/x-www-form-urlencoded". This is needed for any POST request made via Ajax.

Ajax code is not working

So I have this program in which the user enters a city and a country. The program looks in the database to see if the city doesn't already exists, if it does I show a warning message using ajax, if not i add the city to the database.
This is the form:
<form action="addCity.php" method="get" onsubmit="return validateCityInfoForm();">
onsumbit I call the javascript function validateCityInfoForm() that looks like this:
function validateCityInfoForm() {
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)
{
if (xmlhttp.responseText == "true") {
document.getElementById("checkIfCityExistsWarning").style.display = "block";
document.getElementById("checkIfCityExistsWarning").innerHTML = "This city already exists!";
return false;
}
}
}
xmlhttp.open("GET", "checkIfCityExists.php?city=" + cityInput + "&country=" + countryInput, true);
xmlhttp.send();
}
checkIfCityExists.php echoes "true" if the city already exists in the database and "false" otherwise.
The problem is that it always adds the city in the db even though the city already exists.
checkIfCityExists.php returns "true" but it doesn't seem to matter.
I really don't know what the problem is, any help would be greatly appreciated.
Thanks!
here is checkIfCityExists.php:
<?php
include ('database_connection.php');
$city = mysqli_real_escape_string($dbc, $_GET['city']);
$country = mysqli_real_escape_string($dbc, $_GET['country']);
//check if the city and country already exists in the database
$query_verify = "SELECT * FROM city WHERE name = '$city' AND country = '$country'";
$result_verify = mysqli_query($dbc, $query_verify);
if(mysqli_num_rows($result_verify) == 0) { //if the city does not appear in the database
echo "false";
}
else {
echo "true";
}
?>
You are trying to make an asynchronous call to do validation. By the time the call comes back it is too late because the form already is submitted.
Tha Ajax call does not pause the code execution, it makes the call and the rest of the code happens.
What you would need to do it break it up into two steps, make the Ajax call and when the onreadystatechange comes back, submit the form.
The problem is, your onsubmit has no return.
So validateCityInfoForm() returns undefined which does not prevent the Browser from executing the action. validateCityInfoForm() should return false to prevent the Browser from submitting the form. And then in the onreadystatechange call form.submit() if necessary.

Categories