Trouble using jQuery post inside non jQuery function - javascript

I have the following script inside a HTML page:
<script>
function Test(){
alert("i got here");
var username = document.registration_form.username.value;
alert(username);
$.post("checkname.php", { name: username }, function(data) {
alert("and here");
alert(data);
if (data = "0"){
alert('That username is already in use, please choose another');
return false;
};
if (data = "1") {
return true;
};
});
};
</script>
I'm trying to get the function test to return true or false if a username is already in my database.
checkname.php contains the following:
<?
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_POST['name'];
$sql="SELECT * FROM members WHERE username='".$myusername."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count >= 1){
echo "0";
}
else {
echo "1";
}
?>
I've tried hardcoding a name and running the PHP and it works fine.
For some reason though when I run Test() the first 2 alerts come through fine, showing me the username enetered, but none of the subsequent alerts appear.
Oooo and jQuery has been added in the header like so:
<script src="create/js/jquery-1.4.4.min.js" type="text/javascript" ></script>
<script src="create/js/jquery-ui-1.8.7.custom.min.js" type="text/javascript"></script>
Any help much appreciated :)

First of all, your return statements from the callback to $.post will not return from your Test() function. You should call Test with a callback function that deals with the data from the server, something like this:
function Test(username, callback) {
$.post("checkname.php", {name: username}, callback);
}
Test(document.registration_form.username.value, function(data) {
if(data == "0") {
// Do something
} else {
// Do something else
}
});
Brad is also correct about the comparison - you're currently assigning "0" to data. You should get the alerts though, I think, even with the other errors. Maybe you need the absolute path to the checkname.php script? E.g. "/checkname.php" (note the slash)?

Off-hand, you should be using == for comparison in javascript. A single = is an assignment, == is a comparison. So having said that, if (data = "0"){ would become if (data == "0"){.
Other than that, I don't see anything too fishy. You're allowed to use jQuery functions within "traditional" javascript function(){}'s.
Also, make sure you sanitize the input from the $_POST['name'] using something like mysql_real_escape_string.

The problem may be that the PHP script is returning a new line before or after it prints 0 or 1. So the string returned wouldn't equal "0" or "1".
Try to change it to output JSON instead.
if($count >= 1){
$ret = 0;
}
else{
$ret = 1;
}
echo json_encode(array('status' => $ret));
And then change your $.post to:
$.post("checkname.php", { name: username }, function(data) {
alert("and here");
alert(data);
if(data.status = 0){
alert('That username is already in use, please choose another');
}
if(data.status = 1) {
alert('That username is not already in use');
}
}, 'json');
NOTE: The return false and return true don't do anything. You cannot return from an AJAX call.

Related

How come Ajax response is different?

I can't find the reason why my ajax response is different when I console.log the response. Any ideas?
Page1 is used in account update form while page2 is used in registration form.
page1.js:
function ajaxCheckDupEmail(){
if(valid_email === true){
return $.ajax({
type:'POST',
url:'ajax/page1.php',
data:{ 'email': email, 'email_login': email_login },
success:function(response){
//some code
}
});
}else{
//other code
}
}
$.when(ajaxCheckDupEmail()).done(function(a1){
console.log(a1);
if(a1[0] === 'false'){
//submitting form
//some code
}
});
NOTE: email and email_login is a js var where I store userinput in, I used valid_email to check if email is valid
page1.php:
if(isset($_POST["email"]) && !empty($_POST["email"])){
$email = trim_strip_data($_POST["email"]);
$email_login = trim_strip_data($_POST["email_login"]);
$prep_data_email = $db->prepare("SELECT email FROM user WHERE email = :email");
$prep_data_email->execute(array(":email" => $email));
$row_count = $prep_data_email->rowCount();
if($row_count === 1 && $email !== $email_login){
echo "true";
}else{
echo "false";
}
}
NOTE: trim_strip_data() is a custom function to trim white spaces although I don't think it is necessary in this case
page2.js:
function ajaxCheckDupEmail(){
if(valid_email === true){
return $.ajax({
type:'POST',
url:'ajax/page2.php',
data:{ 'email': email },
success:function(response){
// some code
}
});
}else{
//other code
}
}
function ajaxCheckDupUsername(){
if(username !== ""){
return $.ajax({
type:'POST',
url:'ajax/page2.php',
data:{ 'username': username },
success:function(response){
// some code
}
});
}else{
//other code
}
}
$.when(ajaxCheckDupUsername(), ajaxCheckDupEmail()).done(function(a1, a2){
console.log(a1);
console.log(a2);
if(a1[0] === 'false' && a2[0] === 'false'){
//submitting form
//some code
}
});
NOTE: email is a js var where I store userinput in, I used valid_email to check if email is valid
page2.php:
if(isset($_POST["email"]) && !empty($_POST["email"])){
$email = trim_strip_data($_POST["email"]);
$prep_data_email = $db->prepare("SELECT email FROM user WHERE email = :email");
$prep_data_email->execute(array(":email" => $email));
$row_count = $prep_data_email->rowCount();
if($row_count === 1){
echo "true";
}else{
echo "false";
}
}
if(isset($_POST["username"]) && !empty($_POST["username"])){
$username = trim_strip_data($_POST["username"]);
$prep_data_username = $db->prepare("SELECT username FROM users WHERE username = :username");
$prep_data_username->execute(array(":username" => $username));
$row_count = $prep_data_username->rowCount();
if($row_count === 1){
echo "true";
}else{
echo "false";
}
}
NOTE: trim_strip_data() is a custom function to trim white spaces although I don't think it is necessary in this case
The problem is I get 2 different response results (depending on result true/false).
In page1.js I get:
true
In page2.js I get:
true,success,[object Object]
true,success,[object Object]
It looks like I get an response object in page2.js but why I don't get one in page1.js?
https://api.jquery.com/jquery.when/#jQuery-when-deferreds
You are dealing with promises, and a promise always returns a promise.
So I would double check page1 isn't returning the object too.
E.g. open dev tools and run the following;
$.when().done(function( x ) { alert('done')});
you will see it returns an object, this is the promise.
but for
true,success,[object Object]
I don't see where success is coming from, are you missing some code?
On a side note...
if(valid_email === true)
is the same as
if(valid_email)
sorry, it was just bugging me.

Return value from php to javascript

I writing a registration/login form, I am sending user info via POST to a PHP that is looking in a DB. I would like that the PHP returns an ok or wrong value to the js and I don't now how to do it.
Here my js:
ui.onClick_regsubmit=function()
{
var fname=document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var affiliation=document.getElementById('affiliation').value;
var data = new FormData();
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
data.append("fname",fname);
data.append("lname",lname);
data.append("password",password);
data.append("mail",mail);
data.append("affiliation",affiliation);
xhr.open( 'post', 'PHP/registration.php', false );
xhr.send(data);
window.alert(affiliation);
}
And the php:
<?php
mysql_connect('localhost','root','') or die('Cannot connect mysql server');
mysql_select_db('ChemAlive_login') or die('cannot connect database');
$lname=$_POST['lname'];
$fname=$_POST['fname'];
$password=$_POST['password'];
$mail=$_POST['mail'];
$affiliation=$_POST['affiliation'];
$q=mysql_query("select * from login where mail='".$mail."' ") or die(mysql_error());
$n=mysql_fetch_row($q);
if($n>0)
{
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password) echo "ok";
else echo "wrong";
}
else
{ $insert=mysql_query("insert into login values('".$fname."','".$lname."','".$mail."','".$password."','".$affiliation."')") or die(mysql_error());}
?>
I would like to return to js this ok or wrong value. How to do it?
xhr.onload=function()
{
if (xhr.status==200)
{
alert(xhr.response);
}else
{
alert("unknown server error");
}
}
it will be better if the server sends a response code, and javascript will transfer this code to the text. For example:
onload=function()
{
switch(xhr.response)
{
case "0":{alert("unknown error")};break;
case "1":{alert("email is already used")};break;
...
}
}
I think thought it is clear
I do not have the rep to comment or I'd ask for details, but if you can consider using ajax, it could look something like this:
php:
$doit = //your query;
if($doit){
$youdid = 'ok';
}
else{
exit('1');
}
js:
$(document).ready(function () {
var foo = $("#formfield")val();
$.ajax({
"foo":foo;
type: 'POST',
url: 'some.php',
success: function(responseText) {
if(responseText == "1") {
alert("Leave instantly");
};
}
else {
alert("One of us");
}
If you want to return either ok or wrong to the JavaScript to handle you could do something like this in your registration.php page:
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password){
header('Content-Type: application/json');
echo json_encode(array('password' => 'ok'));
}else{
header('Content-Type: application/json');
echo json_encode(array('password' => 'wrong'));
}
I have not fully testing this, but the idea is to set the header to return json and then send it a JSON string.
Does that make sense?
Like I said in my comment below I have only used jQuery for AJAX. But here is a little something of what I know about XMLHttpRequest and my undertsanding of how you would test what you get back.
You can set up a listener for when you get a response back onreadystatechange and then put the response in a variable var pass = xhr.response and then just output the text to an alert box like alert(pass.password).
if (xhr.onreadystatechange === 4 && xhr.status === 200){
var pass = xhr.response;
//should output either ok or wrong
alert(pass.password);
}
Read more about XMLHttpRequest here
Let me know if that works.

How to call on a Javascript function after form submission in PHP

I'm just starting to learn javascript today and I was wondering how to call on a javascript function in PHP after it is done submitting a form to the database. My javascript code is basically an alert box saying that your account has been created. Any response wold help. Here is the section of the PHP code that I want to insert the function into (everything else really doesn't matter) and javascript code insert, if you require anything else please tell me. Thanks a lot!
PHP:
<?php
class Registration
{
**FORM VALIDATION AND SUBMISSION NOT INCLUDED**
if ($query_check_user_name->num_rows == 1)
{
$this->errors[] = "Sorry, that user name is already taken. Please choose another one.";
}
else
{
// write new users data into database
$query_new_user_insert = $this->db_connection->query("INSERT INTO users (user_name, user_password_hash, user_email) VALUES('" . $this->user_name . "', '" . $this->user_password_hash . "', '" . $this->user_email . "');");
if ($query_new_user_insert)
{
$this->registration_successful = true;
$this->messages[] = "Registration successful! Please go back to the login page and login in with your new username and password.";
echo "<script type='text/javascript'>myFunction()</script";
}
else
{
$this->errors[] = "Sorry, your registration failed. Please go back and try again.";
}
}
}
else
{
$this->errors[] = "Sorry, no database connection.";
}
}
}
else
{
$this->errors[] = "An unknown error occurred.";
}
}
}
?>
Javascript:
<script>
function myFunction()
{
var r = confirm("Registration Successful!\nYou will now be redirected to the login page");
if(r == true)
{
location.assign("http://yhsaa.org/members/index.php");
}
}
</script>
Try this:
echo "<script type='text/javascript'>window.onload = function()
{
myFunction();
}
</script>";
What is happening is that this code creates and event on window object called onload. This event will be fired when your html has finished loading. Then it will call your function myFunction(). This behaviour will make sure that your function was declared before its called, so its avoids not declared exception for your function.
Its like changing this:
myFunction(); // At this time JS doesn't know that you have an function called myFunction()
function myFunction() {};
to this:
function myFunction() {};
myFunction(); // At this time JS already know your function myFunction() and it will call it.
Your script contains an error, you don't close the script tag correctly !

Jquery if statement not working even if the statement is true

I have a simple if statement where when i send this certain data to the database, i want the php code to send bake a code that tells javascript its ok to continue, but if the php script sends back a bad code, javascript is to now move forward and display a certain text or something.
The php code works fine but for some reason my javascript files would not work at all.
My javascript is suppose to ajax request to parse.php and receive the data that parse.php sends back to it, if parse.php says 200 its suppose to load in specific items.
Here is the code for one of my systems:
$(document).ready(function(){
$("#chatForm").submit(function(){
var chatHash = $("#chatHash").val();
var body = $("#chatPoster").val();
var by = $("#userBy").val();
if(chatHash != "" && body != ""){
$.post('parse.php',{chatHash: chatHash, body: body, userBy: by},function(data){
if(data == "200"){ // Right here is where its messing up
$("#chatPoster").val("");
$.get('getChatMessages.php?hash=' + chatHash,function(data2){
$(".allMsgs").html(data2);
});
} else {
alert('Critical error');
}
});
} else {
alert('Error');
}
});
});
Here is the code for the parse.php page:
$chat = new ChatSystem;
if(isset($_POST['chatHash']) && isset($_POST['body']) && isset($_POST['userBy'])){
$chat->sendMessage($_POST['userBy'],$_POST['chatHash'],$_POST['body']);
}
Here is the code from the class ChatSystem that the parse.php page is referring to:
public function sendMessage($user,$hash,$body){
global $db;
$date = date("Y-m-d");
$time = date("H:i:s");
$timestamp = "$date $time";
if(empty($user) == false && empty($hash) == false){
$db->query("INSERT INTO chat_messages VALUES('','$user','$body','$timestamp','','0','$hash')") or die("error");
echo '200';
}
}
Even though my php code works perfectly the javascript still messes up. My php code sends back 200 like i ask it to but yet the jquery messes it up
Have a look here, http://api.jquery.com/jquery.post/.
You need a second parameter to the success callback function to be able to catch the response status code.
I.E. function(data,statusCode){ // check the status code here}

running a php function inside javascript code [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I hope to run a php code inside a javascript code too and I do like that :
<?php function categoryChecking(){
return false;
}?>
....
function openPlayer(songname, folder)
{
if(<?php echo categoryChecking() ?> == true)
{
if (folder != '')
{
folderURL = "/"+folder;
}else
{
folderURL = '';
}
var url = "/users/player/"+songname+folderURL;
window.open(url,'mywin','left=20,top=20,width=800,height=440');
}else{
alerte('you should click on a subcategory first');
}
}
....
<a href='javascript:void();' onClick="openPlayer('<?php echo $pendingSong['id']; ?>','')">
finally I get this error instead the alert message "you should click on a subcategory first"
ReferenceError: openPlayer is not defined
openPlayer('265','')
You're reduced your test case too far to see for sure what the problem is, but given the error message you are receiving, your immediate problem has nothing to do with PHP.
You haven't defined openPlayer in scope for the onclick attribute where you call it. Presumably, the earlier JS code is either not inside a script element at all or is wrapped inside a function which will scope it and prevent it from being a global.
Update: #h2ooooooo points out, in a comment, that your PHP is generating the JS:
if( == true)
Check your browser's error console. You need to deal with the first error messages first since they can have knock on effects. In this case the parse error in the script will cause the function to not be defined.
Once you resolve that, however, it looks like you will encounter problems with trying to write bi-directional code where some is client side and some is server side.
You cannot run PHP code from JavaScript, because PHP is a server-side language (which runs on the server) and JavaScript is a client-side language (which runs in your browser).
You need to use AJAX to send a HTTP request to the PHP page, and then your PHP page should give a response. The easiest way to send a HTTP request using AJAX, is using the jQuery ajax() method.
Create a PHP file ajax.php, and put this code in it:
<?php
$value = false; // perform category check
echo $value ? 'true' : 'false';
?>
Then, at your JavaScript code, you should first add a reference to jQuery:
<script type="text/javascript" src="jquery.js"></script>
Then, use this AJAX code to get the value of the bool:
<script type="text/javascript">
$.ajax('ajax.php')
.done(function(data) {
var boolValue = data == 'true'; // converts the string to a bool
})
.fail(function() {
// failed
});
</script>
So, your code should look like this:
function openPlayer(songname, folder) {
$.ajax('ajax.php')
.done(function (data) {
var boolValue = data == 'true'; // converts the string to a bool
if (boolValue) {
if (folder != '') {
folderURL = "/" + folder;
} else {
folderURL = '';
}
var url = "/users/player/" + songname + folderURL;
window.open(url, 'mywin', 'left=20,top=20,width=800,height=440');
} else {
alert('you should click on a subcategory first');
}
})
.fail(function () {
// failed
});
}

Categories