i created a sencha touch application,in my controller i used the ajax code as
if (condition is true){
Ext.Ajax.request({
url: 'http://localhost/../abc.php?action=check',
params: valuesUser,
method: 'POST',
success: function(response){
var text = response.responseText;
console.log(response.responseText);
if(response.responseText == 'exists')
{
//Ext.Msg.alert('Success', text);
Ext.getCmp('loginform').destroy();
Ext.Viewport.setActiveItem(Ext.create('RegisterForm.view.Main'));
}
else{
Ext.Msg.alert('Success',text);
}
}
failure : function(response) {
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
}
});
}
else{
Ext.Msg.alert('Error', 'All the fields are necessary');
}
my abc.php contains the following code
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db('RegisterForm',$con);
if($_REQUEST["action"]== "check"){
$query = "SELECT name FROM userdetails WHERE name ='" . $_POST['userName'] . "' ";
$queryresult = mysql_query($query);
$count = mysql_num_rows($queryresult);
if($count == 1)
{
echo('values are in the db');
}
else
{
echo("values aren't in the db");
}
}
?
if contion is true in the controller code it goes to abc.php and checks name exists in the db are or n't.if name exist then it should open another view ,otherwise it should display alert msg as values aren't in the db.but by using the above code ,im navigating to another view in both cases (values are in db,values aren't in the db).can anyone help me to do this. thanks in advance...
You need to put condition in your sencha code based on the returned value from PHP. Something like:
if(response.responseText == 'exists')
Ext.Viewport.setActiveItem(Ext.create('RegisterForm.view.Main'));
else
Ext.Msg.alert('Success', text);
Moreover do
echo 'exists';
instead of
echo('values are in the db');
Related
I have a form where a user can input a voucher code:
<form>
<input type="text" name="promo" id="promo">
<div class="promo_check"></div>
</form>
the user can click on my div 'promo_check' which runs the following ajax:
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.promo_check', function() {
var promo = $("#promo").val();
$.ajax({
type: "POST",
url: "process_promo.php",
data: {data:promo},
success: function(data)
{
window.alert(data);
}
});
});
});
</script>
this then executes my mysql query to check if the voucher exists in the database and that the $_SESSION['user_name'] / i.e. the logged in user has the permission to use that voucher.
process_promo.php:
<?php
$username = "mark";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$_SESSION['username'] = 'mark';
$promo = $_POST['data'];
$query = "SELECT * FROM hewden1.supplier_users WHERE promo_code = '$promo'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
if (mysql_num_rows($result) > 0) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}else{
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
} }
}else{
echo 'error';
}
}
?>
this all works fine, if the voucher code matches for that user then it echo's 'correct' and my ajax will show an alert saying 'correct'. Then if the voucher code does not match for the user then it echo's 'not correct for user'.
The problem i have is when the voucher is not valid at all and cannot be found in the database it is suppose to echo 'error' however ajax show a blank/empty alert message instead of showing 'error'.
I think this is because i am using success: in my ajax but when i try to add an error: call back my script stops working. can someone please show me what i'm doing wrong? thanks in advance
Looking at process_promo.php, if you get no result from the database query, then the contents of the while loop never get executed. Putting it another way, inside the while loop you'll never have a mysql_num_rows($result) == 0 condition.
Here I moved your while loop inside your mysql_num_rows check:
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}
else {
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
}
}
}
}
else {
echo 'error';
}
...which also pulls the error report outside the while loop and gives it a chance to execute.
I have writtin this code to check the email availability.
var email = $('#email_reg').val();
if(email && email.length > 0)
{
if(!isValidEmailAddress(email))
{
isValid = false;
$('#msg_email').html('Email is invalid').show();
}
else
{jQuery.ajax({
type: 'POST',
url: 'check_username.php',
data: 'email='+ email ,
cache: false,
success: function(response){
if(response == 1){
$('#msg_email').html('Email already Exists').show();
isValid=false;
}
else {
$('#msg_email').html('').hide();
}
}
});
}
}
else
{
isValid = false;
$('#msg_email').html('Please enter email').show();
}
The php Code is
<?php
require_once('Connections/connection.php');
$username= mysql_real_escape_string($_REQUEST["email"]);
if (!$con)
{
echo 0;
}
else {
mysql_select_db($database_connection, $connection);
$result = mysql_query("SELECT * FROM vendor_logiin WHERE username='" . $username . "'");
$num = mysql_num_rows($result);
echo $num; //it will always return 1 or 0 since we do not allow multiple users with the same user name.
}
mysql_close();
?>
Now all the others work well like when left it empty and give a wrong email format.But the problem is when i give an email Id that already exists. It didnot give error.
I have no idea what is going wrong.
Since you didn't specify dataType the response is probably treated as text or html and in that case it might be wise to do the comparison as a string:
if (response == "1") {...}
instead of a number. Or use parseInt(response, 10) == 1 if you compare it as a number.
Okay so I am trying to get ajax to post to my php file, lookup a mysql field and if it exists echo 'clientsuccess' otherwise echo 'Client already exists'
but on success function it returns both values despite the fact that they're in an php if statement.
I am quite possibly missing something incredibly simply, but any help is greatly appreciated.
PHP:
<?php
session_start();
$clientArray = $_POST['clientArray'];
$clientArray = explode(',', $clientArray);
$count = 0;
foreach($clientArray as $clientField)
{
trim($clientField);
if(empty($clientField)) {
$clientField = '-';
}
}
$con = mysql_connect("localhost",$_SESSION['MysqlUser'],$_SESSION['MysqlPass']);
if (!$con)
{
die('Could not connect with '.$_SESSION['MysqlUser'].mysql_error());
}
mysql_select_db("smeinsti_SPW_Inventory", $con);
$checkclient = mysql_query("SELECT ClientName FROM Clients WHERE ClientName = '".$clientArray[0]."'", $con);
if(mysql_num_rows($checkclient)==0)
{
$sql="INSERT INTO Clients (`ClientName`, `PhoneNumber`, `Email`, `Address`, `OrderDate`)
VALUES
('$clientArray[0]', '$clientArray[1]', '$clientArray[2]', '$clientArray[3]', CURDATE())";
$clientArray[0] = $_SESSION['ClientName'];
echo "clientsuccess";
} else {
echo 'Client already exists';
}
?>
JS:
function NextPage()
{
var ClientData = [];
$('form#order-form.create input[type=text]').each(function() {
ClientData += $(this).val() + ',';
})
alert(ClientData);
var parameters = {
clientArray: ClientData
};
$.ajax({
type: "POST",
async:false,
url: "write_client.php",
data: parameters,
success: function(result){
var res=result;
if(res = 'clientsuccess') {
window.location = 'admin.php?id=7';
} else {
alert('Client already exists');
}
}
});
}
Your condition Equal symbol is not correct! Put '=='
if(res == 'clientsuccess') { //Double Equal to
window.location = 'admin.php?id=7';
} else {
alert('Client already exists');
}
mysql_num_rows returns the number of selected rows and not the fields of a certain row. Use mysql_fetch_row to fetch the row you have selected with your query:
You could also use mysql_result to fetch a row and get a certain field:
$client exist = mysql_result($checkclient, 0, 0);
This fetches the first row (zero based) and returns the first field (zero based).
i have problems with the code below, I'm trying to bring a message of error if the email already exists, but I'm not having success .. Look at the code:
Ajax an jQuery:
<script type="text/javascript">
// Centering the text content
jQuery(window).resize(function () {
boxHeight();
}).load(function() {
boxHeight();
// Show the content and focus the email input
$("#content").fadeIn();
$("#email").focus();
});
jQuery(document).ready(function($){
$('#subscribe').submit(function(e){
e.preventDefault();
email = $('input#email');
email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!email_regex.test(email.val())) {
$('#response', form).fadeIn(500, function() {
$('#response', form).html('<p class="message warning" align="center">Invalid email</p>');
});
return;
} else {
$('#response', form).html('<p class="message">Please Wait...</p>');
}
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(responseText) { if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else { if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
}
});
});
});
</script>
PHP Database connect:
<?php
$host="xxxx"; // Host name
$username="xxxx"; // Mysql username
$password="xxxx"; // Mysql password
$db_name="xxxx"; // Database name
$tbl_name="xxxx"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$email = $_POST['email'];
$query = mysql_query("SELECT email FROM banco_emails WHERE 'email' = '$email'");
if(mysql_num_rows($query) == 1) { // if return 1, email exist.
echo '1';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
The problem is that the ajax code does not show the error message, only the message "Please wait ..." and nothing happens, i don't know why...
Sorry for my bad english.
Thanks in advanced!
Problem solved, the problem was in the php code, I did it and it worked!
$query = mysql_query("SELECT email FROM banco_emails WHERE email = '$email' LIMIT 1");
$email_check = mysql_num_rows($query);
if ($email_check > 0) {
echo '1';
} else if ($email_check == 0) {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
In your success function you incorrectly handle what PHP returns on success. If the email was new and was added to the database, PHP will echo:
<p class="message">Thanks for registering. Our bar is getting crowded!</p>
Your JS parses the response like this:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
The problem here is that you only display the HTML message if responseText is an empty string. You should get rid of the if statement:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
This way the responseText is displayed. And I'm not 100% sure what your submission HTML looks like, but after you show the message you might want to fade out the "please wait" if it would still be visible after you hide the form.
Try to this way:
Make unique email column.
If the email address is already exist its return an error, and you can show the error message to user, on ajax error section.
Here is what I have going on in my AJAX:
$('#submit-button').click(function(){
var twit = $('input#twittername').val();
var email = $('input#email').val();
if((email == "" || email == "you#address.com") && (twit == "" || twit == "#twittername")){
$('p#empty-error').fadeIn();
return false;
}
var datastring = 'email=' + email + '&twit=' + twit;
if(email != "you#address.com"){
$.ajax({
type: 'POST',
url: '/path/to/script1.php',
data: datastring,
success: function(){
$('#signup').fadeOut('slow',function(){
$('#email-response').fadeIn('slow');
});
}
});
return false;
}
if(twit != "#twittername"){
$.ajax({
type: 'POST',
url: '/path/to/script2.php',
data: datastring,
success: function(){
$('#signup').fadeOut('slow', function(){
$('#email-response').fadeIn('slow');
});
}
});
}
return false;
});
AJAX is returning the success function. And I can navigate directly to /path/to/script2.php, and it will add an empty record to my database. But for some reason, the PHP is not actually receiving and inserting the AJAX variable.
This was working before, and I'm unsure at what point it stopped. It's just a bit strange that it is two scripts that were both working, and now neither are.
Script one was written by me, and it inserts a blank record if I navigate straight to it:
<?php
$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pw';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$dbname = 'databasename';
mysql_select_db($dbname, $con);
$sql = "INSERT IGNORE INTO databasename (column) VALUES ('$_POST['twit']')";
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
echo 'record added successfully';
mysql_close($con);
Script two is modified from MailChimp, and this does nothing if I navigate straight to it, which is expected:
function storeAddress(){
// Validation
if(!$_POST['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_POST['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('66a7f17d87e96e439f7a2837e2963180-us1');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "b1ebe7c0ba";
if($api->listSubscribe($list_id, $_POST['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_POST['email']){ echo storeAddress(); }
?>
Any ideas where I'm going wrong?
Also: I can successfully alert the datastring, if that's any help.
Not sure if it is just a typo here, but this line won't work:
$sql = "INSERT IGNORE INTO databasename (column) VALUES ('$_POST['twit']')";
It should be (look at the quotes at the POST variale):
$sql = "INSERT IGNORE INTO databasename (column) VALUES ('".$_POST['twit']."')";
Besides that, you should never put a POST Variable directly into the SQL statement due to security reasons (have a look at SQL injections).
Needed to delete the top "return false." A fun way to spend 4 hours.