ajax not sending data to specified page - javascript

I have been following a tutorial and the person who does it provide the code for you to use, so ive tried using the code and going through it line by line but as i hardly know anything about ajax, i cant seem to understand why it is not passing data through to the page that is specified,and since the data isnt being passed through the process of mysqli queries and all other things, they wont begin to happen as the data isnt being passed over.
The data is part of a form and it is to check usernames against the database to check availability, so the code for the data in the form is ...
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">...
And so on... the js provided is ..
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signupfunc.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
So as far as i understand, var u= _("username").value is the value of the input with the id=username, and if username is not blank then it firstly brings up the checking... before starting the var that is called ajax, it begins the process of POSTing to the page, signupfunc.php, then im not exactly sure the next bit but i think it means something like if something returns from the var ajax then it puts the response return in the unamestatus div ?? then the last bit does as it says? the var ajax sends the value of usernamecheck as the username... but it is not sending the data to the specified page ... can someone point out what im doing wrong advise how to solve this problem ??
and just incase it is needed here is the code that is on the specified page signupfunc.php that is related to the code above..
//Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}

maybe you can try change you code with below jquery ajax code :
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
$.ajax({
url : "signupfunc.php",
type : "POST",
data : "usernamecheck="+u,
dataType : 'text',
success: function(data,textStatus,jqXHR){
alert(data);
}
})
}

Related

Encountering problem while posting and fetching data using php and ajax

My ajax code:
$('#name').keyup(function() {
var usercheck = $(this).val();
$('#nameAvailability').html('<img src="../SPR/assets/img/loading.gif" width="300" />'); //this part is working
$.post("../SPR/backend/username_availability_check.php", {user_name: usercheck} ,
function(data)
{
if (data.status == true)
{
$('#nameAvailability').parent('div').removeClass('has-error').addClass('has-success');
} else {
$('#nameAvailability').parent('div').removeClass('has-success').addClass('has-error');
}
$('#nameAvailability').html(data.msg); // not working
} ,'json');
});
My php code:
<?php
require("connection.php");
if(isset($_POST['user_name']) && $_POST['user_name'] != '')
{
$response = array();
$username = mysqli_real_escape_string($conn,$_POST['user_name']);
echo $username;
$sql = "select username from users where users.username='".$username."'";
$res = mysqli_query($conn, $sql);
$count = mysqli_num_rows($res);
if($count > 0)
{
$response['status'] = false;
$response['msg'] = 'Username already exists.';
}
else if(strlen($username) < 6 || strlen($username) > 15){
$response['status'] = false;
$response['msg'] = 'Username must be 6 to 15 characters';
}
else if (!preg_match("/^[a-zA-Z1-9]+$/", $username))
{
$response['status'] = false;
$response['msg'] = 'Use alphanumeric characters only.';
}
else
{
$response['status'] = true;
$response['msg'] = 'Username is available.';
}
echo json_encode($response);
echo $response;
}
?>
I have used session_start() in my index.php where user inputs his username in the input field with id 'name'
I have checked the given php code by running it individually by passing a custom username from the database and it works fine. So probably there's something wrong with the ajax code.
It is impossible to tell what your clientside code does based on what is posted here.
But in general, for debugging and to check if your serverside code works, do this:
Make a simple form, that POSTS to your PHP script.
<form action="whateveryourphpcodeisnamed.php" METHOD="POST">
<INPUT TYPE="TEXT" NAME="user_name">
<INPUT TYPE="SUBMIT" VALUE="TEST THE USERNAME">
</FORM>
And see what it says back to you.
Be sure to activate error_reporting during development.

Ajax Not Receiving Response From My "Working PHP Script"

I'm currently making a Contact page using a mixture of Ajax, PHP and MySQL.
A Few Quick Notes:
All of the PHP and AJAX code is working. The only thing that I can't get to work is the response coming from the PHP to the AJAX.
This Contact page has been optimized so that, in the case that JavaScript is disabled on a browser. The page will use a simple POST method to complete the action.
I have a few custom functions (e.g. n()) that have been declared earlier in the files that I'm providing clips from. Please just disregard these as they don't effect anything related to the issue.
A break down of each file can be found underneath each block of code.
contact_page.php (where the magic happens)
header('Content-type: application/json');
if(isset($_POST['l'])) {
if($_POST['l'] == 'php') { //This is related to the PHP version of the form validation. The code that handles the AJAX is farther down
$fd = $_POST['fd'];
$i = 0;
while ($i < count($fd)) { //Used to make sure all fields have been filled. Otherwise, return null.
$fd[$i] = n($fd[$i],false);
if(empty($fd[$i])) { $fd[$i] = null; }
$i++;
}
if(isset($fd[0],$fd[1],$fd[2],$fd[3])) {
if(filter_var($fd[1], FILTER_VALIDATE_EMAIL) && strlen($fd[1]) > 6) {
$q1 = "INSERT INTO contact_msg VALUES ('".$fd[0]."','".$fd[1]."','".$fd[2]."','".$fd[3]."',NOW(),'$date-$id');";
$r1 = mysqli_query($dbc1,$q1);
if($r1) {
$h = 'From: Jewl Photography Notifications <contact#jewl-photography.net>' . "\r\n" .
'MIME-Version: 1.0' . "\r\n" .
'Content-type: text/html; charset=utf-8' . "\r\n" .
'Reply-To: contact#jewl-photography.net' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$m = m($fd[0],$fd[2],$fd[3],"$date-$id");
mail('nathan#lmartin.net','New Message From: '.$fd[0],$m,$h);
header('Location: https://jewl-photography.net/Contact?w=SNT');
} else {
header('Location: https://jewl-photography.net/Contact?w=INT_ERR');
}
} else {
header('Location: https://jewl-photography.net/Contact?w=FLS_EMAIL');
}
} else {
header('Location: https://jewl-photography.net/Contact?w=MISS_ALL');
}
}
//Below is the code that handles the AJAX
if($_POST['l'] == 'ajax') {
if(isset($_POST['name'],$_POST['email'],$_POST['subject'],$_POST['message'])) {
$fd = array(n($_POST['name'],true),
n($_POST['email'],false),
n($_POST['subject'],false),
n($_POST['message'],false));
if(filter_var($fd[1], FILTER_VALIDATE_EMAIL)) {
$q1 = "INSERT INTO example_table VALUES ('".$fd[0]."','".$fd[1]."','".$fd[2]."','".$fd[3]."',NOW(),'$date-$id');";
$r1 = mysqli_query($dbc1,$q1);
if($r1) {
echo json_encode('SENT');
$h = '
**Header Info**
';
$m = m($fd[0],$fd[2],$fd[3],"$date-$id");
mail('example#example.net','New Message From: '.$fd[0],$m,$h);
} else {
echo json_encode('ERROR_ADD');
}
} else { echo json_encode('FALSE_EMAIL'); }
} else { echo json_encode('NOT_ALL'); }
}
}
The contact_page.php is pretty simple.
It takes the POST info from the Ajax(shown below).
Runs it through a number of encoding functions (e.g. htmlspecialchars() and the like, represented by n() ).
Also tests for if certain requirements are met. If not, it should send a response back to the AJAX (see Step 6)
Adds it to a SQL table.
Sends an email to the moderator to let them know that a new message has been sent.
Then send's a response back to the Contact page using a json object: echo json_encode('Response Text Here');
Everything works except for step 6. For some reason, the AJAX refuses to receive the response. I'm not getting any PHP, SQL or JavaScript errors or warnings, and my Ajax (as you will see below) is using dataType JSON.
Contact.php (the user-side contact page)
<script>
//This first half isn't ajax, skip down a few lines
//The very bottom of tis block of code is the form's html
$(function() {
$('#fglk').submit(function() {
var e = [];
e[0] = $('#name').val();
e[1] = $('#emal').val();
e[2] = $('#subj').val();
e[3] = $('#mesg').val();
if(e[1].length > 6 && e[1].length < 255) {
$('.err-span').removeClass('error');
$('.err-span').html('');
} else {
$('.err-span').addClass('error');
$('.err-span').html('Provide valid Email!');
e[1] = null;
}
/**AJAX Related code \/ **/
if(e[0] && e[1] && e[2] && e[3]) {
var data = new Object();
data.l = 'ajax';
data.name = e[0];
data.email = e[1];
data.subject = e[2];
data.message = e[3];
var options = new Object();
options.data = data;
options.dataType = 'json';
options.type = 'post';
options.success = function (response) {
if(response == 'SENT') {
$('.err-span').html('Sent!');
$('.err-span').addClass('sent');
$('.err-span').addClass('error');
} else if(response == 'ERROR_ADD') {
$('.err-span').html('An internal error prevented your message from being sent!');
$('.err-span').addClass('error');
} else if(response == 'NOT_ALL') {
$('.err-span').html('Please fill out all fields!');
$('.err-span').addClass('error');
} else if(response == 'FALSE_EMAIL') {
$('.err-span').html('You must provide a valid email!');
$('.err-span').addClass('error');
}
};
options.url = 'https://example.net/php/contact_page.php';
$.ajax(options);
} else {
}
return false;
});
});
</script>
<p style='color: red;'>
<? //These $_GET parameters are for if raw PHP is used to send the message
if($_GET['w'] == 'INT_ERR') {
echo '**Some Text**';
}
if($_GET['w'] == 'FLS_EMAIL') {
echo '**Some Text**';
}
if($_GET['w'] == 'MISS_ALL') {
echo '**Some Text**';
}
if($_GET['w'] == 'SNT') {
echo '**Some Text**';
}
?>
</p>
<form action='https://example.net/php/contact_page.php?l=php' id='fglk' method='post'>
<label>Full Name:</label><br><input type='text' id='name' name='fd[]' required><br>
<label>Email:</label><br><input type='email' id='emal' name='fd[]' required><br>
<label>Subject:</label><br><input type='text' id='subj' name='fd[]'><br>
<label>Message:</label><br><textarea id='mesg' name='fd[]' required></textarea><br>
<span class='err-span'></span>
<input type='submit' name='fd[]' value='Send'>
</form>
Contact.php is pretty self explanatory.
It takes the info from the form.
Runs the email through a basic email validation
Passes it to a few JSON objects.
Runs those objects through the $.ajax() function.
Issues the return false; to prevent the form from sending and reloading the page.
After the PHP runs, the AJAX should then take the response and send a message that is written accordingly.
It doesn't throw any errors in my console. It will show an error if I provide an email that is under 6 chars long (this isn't related to the PHP code at all though). But won't show any of the responses.
I've used the same AJAX code before and it's worked fine, the main difference is the PHP backend.
If you have any questions about the code please let me know!
Thanks for your help!

loop through JSON file using ajax, PHP & Javascript

I'm creating a small game where users must register or login before playing. I have a separate json file that stores already registered users.
Once a user enters their username and password into a field I make an AJAX call to retrieve the data using PHP with the intent of checking whether their details are on file. Firstly I tried sending back a JSON encoded object to parse through in Javascript. This is the code I have so far:
JSON:
{"LogIns":[
{
"Username":"mikehene",
"password":"123"
},
{
"Username":"mike",
"password":"123"
}
]
}
HTML:
<fieldset>
<legend>Please log in before playing</legend>
<form>
Username: <br>
<input type="text" placeholder="Enter a Username" id="username1" name="username"><br>
Password: <br>
<input type="password" placeholder="Enter a password" id="password" name="password"><br>
<input type="submit" value="Submit" onclick="return checkLogin();">
</form>
</fieldset>
PHP:
<?php
$username = $_POST['username'];
$str = file_get_contents('logins.json'); // Save contents of file into a variable
$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
echo json_encode($json);
?>
Javascript & AJAX call:
var usernamePassed = '';
function checkLogin(){
usernamePassed = document.getElementById("username1").value;
callAJAX();
return false;
}
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp.responseText);
}
}
xhttp.open("POST", "LogInReg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed);
}
function myFunction(response) {
var arr = response;
var objJSON = JSON.parse(arr);
var len = objJSON.length;
for(var key in objJSON){
console.log(key);
}
}
But it only prints out "LogIns". I also tried this:
for (var i = 0; i < objJSON.length; ++i) {
if(objJSON[0].Username == usernamePassed){
console.log("found it");
}
else{
console.log("didn't find it!");
}
}
Therefore I tried another approach (parse the data in the PHP file) like so:
foreach ($json['LogIns'][0] as $field => $value) {
if($json['LogIns'][0]['Username'] == $username){
echo "Logged In";
break;
}
else{
echo "No user found";
break;
}
}
But when I enter "mike" as a user name it is echoing "No user found". So I'm lost! I'm new to coding and trying to learn myself. I would love to learn how to do it both methods (i.e. PHP and Javascript).
Everything I've found online seems to push toward JQuery but I'm not quite comfortable/good enough at JQuery yet so would like to gradually work my way up to that.
I haven't even got to the register a user yet where I'm going to have to append another username and password on registration.
Any help would be GREATLY appreciated.
Thanks in advance
Try this
$json = json_decode($str, true);
$password = $_POST['password'];
foreach($json['LogIns'] as $res)
{
if($res['Username']==$username && $res['password']==$password)
{
echo json_encode($res['Username']);
//echo 'user found';
}
}

Many spaces before javascript result

I have a login script that should return 'success' or 'failure' respectively, but it adds many spaces before the result, in the console it shows tha value as "<tons of space> success". This is the PHP for the login script:
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
echo 'success';
exit();
} else {
//$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
//return $error;
$err = 'failure';
echo($err);
exit();
}
} else {
//$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
//return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
exit();
}
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
and the form and JS
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success : function(result) {
console.log(result);
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
but the result always has a lot of spaces for some reason. I'm new to JS, so if this is common, I don't already know.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define("CCore", true);
session_start();
//Load files...
require_once('include/scripts/settings.php');
require_once('include/scripts/version.php');
require('include/scripts/core.class.php');
require('include/scripts/nbbc_main.php');
$parser = new BBCode;
$core = new core;
$admin = new admin;
require_once('include/scripts/layout.php');
require_once('include/scripts/page.php');
//Set Variables...
global $dbc, $parser, $layout, $main, $settings, $core;
$page = new pageGeneration;
$page->Generate();
?>
this is my index, and anything before the page is generated and login() is called, is in there.
I suppose you are using Ajax calls. I had the same problem, but it my case the result hadn't contain spaces, it was returned in new line. The problem was that my script which was requested by Ajax, contained "new line" character before the PHP script. Search your script file for spaces before PHP script starting with <?php //code... If you had included some scripts in the script which returns success note, search them as well.
I dont know if it matters but your
if(result == " success"){ // <<<<<< Here is a Problem maybe
window.location = "/index.php";
}else if(result == " failure"){ // <<<<<< Here is a Problem maybe
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
compares your result from the server which is i.e. "success" with " success". There is space too much.
EDIT:: I dont get ether why you jumps between the response format. Sometimes you echo "success" which is plain and good with your if condition but sometimes you return json encodes strings.
These Responses you can't just compare with plain text. These Responses you have to Parse into a JSON Object. Then you could compare with:
if (parsedJSONobject.result == "success"){}
The comments on the question are most probably correct: the spaces are being (again, probably, nobody can know for sure without reading the whole source) echoed by PHP included before this. For example, if you do:
<?php
// there's a space before the previous line
you'd get that space in the output.
What you can do is a bit of a hack, you include a header, for example:
header('Content-Type: text/html');
just before your success output, this will (yet again, probably) output something like:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
(note the "output started" part) and now you know where to start looking.
HTH.

Set interval with AJAX

The purpose is to display a DIV when you click on a button and then display text inside that DIV that comes from my database. Thing is that data in databse changes, so text inside that div also. I would need a setInterval... with AJAX
I'm new in javascript and don't know the good way to go...
HTML:
<div onClick="showDiv();"> click </div>
<div style="display: none;" id="div">
Info from database:
<span style="display: hidden;" id="data1"> DATA 1 </span>
<span style="display: hidden;" id="data2"> DATA 2 </span>
</div>
javascript:
function showDiv()
{
document.querySelector("#div").style.display = "block";
setInterval(function () {getData()}, 1000);
}
function getData()
{
$.post(
'process.php',
{
},
function(data){
if(data == '1'){
document.querySelector("#data1").style.display = "inline";
}
else if(data == '2'){
document.querySelector("#data2").style.display = "inline";
}
},
'text'
);
return false;
}
//don't know how to just take data from database without sending by POST or GET.
php:
<?php
SELECT x FROM database
if(x == 1)
{echo '1';}
else if(x == 2)
{echo '2';}
?>
Get data using AJAX : Learn here. Your code to setInterval() is correct or you can do this : setInterval(getData,1000);
Display data in spans :
document.getElementById("data1").innerHTML = "your content from database";
document.getElementById("data2").innerHTML = "your content from database";
You're not giving a lot of info so I will give you a basic example of getting data from a mySQL database with jQuery, Ajax and PHP.
First you need to include jQuery to the head of your document
<script src="http://code.jquery.com/jquery-latest.js"></script>
And then use Ajax
function showDiv(){
document.getElementById("div").style.display = "";
setInterval(function (){ getData('something'); }, 1000);
}
jQuery.noConflict();
jQuery(document).ready(function($){
getData = function(variable){
var postVar = variable;
var postVar2 = "exemple";
$.ajax({
type: "POST",
url: "php/file.php",
data: 'variable=' + postVar + "&" +
'variable2=' + postVar2,
success: function(data){
data = $.trim(data);
var dataSplit = data.split("++==09s27d8fd350--b7d32n0-97bn235==++");
if(dataSplit[0] == "1"){
document.getElementById("data1").innerHTML = dataSplit[1];
}
if(dataSplit[0] == "2"){
document.getElementById("data2").innerHTML = dataSplit[1];
}
}
});
}
});
Finally, you need to create an external php file (in this example "file.php" in the folder "php") to get the data from your database with mysqli
<?php
// to prevent error, I check if the post variable is set and
// if it's not only full of spaces
if(isset($_POST['variable']) && preg_replace("/\s+/", "", $_POST['variable']) != ""){
$con = mysqli_connect("hostname", "username", "password", "database_name");
$query = mysqli_query($con, "SELECT * FROM `table_name` WHERE `column_name` = '".$_POST['variable']."'");
$results = array(); $row = 0;
while($info = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$results[$row] = array();
$results[$row]['column_name1'] = $info['column_name1'];
$results[$row]['column_name2'] = $info['column_name2'];
$row++;
}
foreach($results as $result => $data){
echo "1" . "++==09s27d8fd350--b7d32n0-97bn235==++" .
'<div>'.$data['column_name1'].'</div>'.
'<div>'.$data['column_name2'].'</div>';
}
}
?>
Hope it helps!

Categories

Resources