PHP file not successfully receiving AJAX variable - php

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.

Related

Register made in PHP and AJAX not working

Basically, I made a login/register with PHP and Ajax to work with phonegap. The login works, if I try to create an account with the same email as an existing one, it responds, but when I try to create a new account, it says registration failed.~
Above there is the code
PHP code
<?php
$con = mysqli_connect("localhost","root","", "login") or die("connection error");
$email = $_POST['email'];
$password = $_POST['password'];
if(isset($_POST['register']))
{
$register = mysqli_num_rows(mysqli_query($con, "SELECT * FROM users WHERE email='$email'"));
if($register == 0)
{
$insert = mysqli_query($con,"INSERT INTO users (email,password) VALUES ('$email','$password')");
if($insert)
echo "success";
else
echo "error";
}
else if($register != 0)
echo "exist";
}
else if(isset($_POST['login']))
{
$login = mysqli_num_rows(mysqli_query($con, "SELECT * FROM users WHERE email='$email' AND password`='$password'"));
if($login != 0)
echo "success";
else
echo "error";
}
mysqli_close($con);
?>
AJAX code
// this is login code
$("#loginButton").click(function(){
var email= $.trim($("#email").val());
var password= $.trim($("#password").val());
$("#status").text("Authenticating...");
var loginString ="email="+email+"&password="+password+"&login=";
$.ajax({
type: "POST",crossDomain: true, cache: false,
url: url,
data: loginString,
success: function(data){
if(data == "success") {
$("#status").text("Login Success..!");
localStorage.loginstatus = "true";
window.location.href = "app.html";
}
else if(data == "error")
{
$("#status").text("Login Failed..!");
}
}
});
});
$("#registerButton").click(function(){
var email= $.trim($("#email").val());
var password= $.trim($("#password").val());
$("#status").text("Creating New Account...");
var dataString="email="+email+"&password="+password+"&register=";
$.ajax({
type: "POST",crossDomain: true, cache: false,
url: url,
data: dataString,
success: function(data){
if( data == "success")
$("#status").text("Registered Success");
else if( data == "exist")
$("#status").text("Account is already there");
else if( data == "error")
$("#status").text("Register Failed");
}
});
Make sure you have internet access permission enabled in config.xml
it took me a good time to find out the issue. and it is very simple mistake, check your SELECT query for syntax error.
1 queries executed, 0 success, 1 errors, 0 warnings
Query: SELECT * FROM users WHERE email='ali#akashif.co.uk' AND
password`='123'
Error Code: 1064 You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '`='123'
there is an extra ` after the password which is breaking the query. and query is failing resulting mysqli_num_rows to always return 0.

My database is not updating

So,
I am a beginning 'nerd' and my job is now to make a kind of schedule where people can put their name in the input. I work with JS with the following code:
var timeoutId; $('form input').on('input propertychange change', function() {
console.log('Invoer bewerking');
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
saveToDB();
}, 1000); }); function saveToDB() { console.log('Opslaan naar Database');
form = $('.formulier24');
$.ajax({
url: "ajax.php",
type: "POST",
data: form.serialize(),
beforeSend: function(xhr) {
$('.HowAbout').html('Opslaan...');
},
success: function(data) { console.error(data) ;
var jqObj = jQuery(data);
var d = new Date();
$('.HowAbout').html('Opgeslagen om: ' + d.toLocaleTimeString());
},
}); } $('.formulier24').submit(function(e) {
saveToDB();
e.preventDefault(); });
and the AJAX file is as the following code:
<?php include ('connect.php'); if(isset($_POST['formulier24'])) {
$userName = $_POST['userName'];
$hours = $_POST['hours'];
$sql = "UPDATE evenement SET userName = '$userName' WHERE hours = '$hours'";
mysql_select_db('u7105d15197_main');
$retval = mysql_query($sql, $conn);
if (!$retval) {
die('Could not update data: ' . mysql_error());
}
echo " Updated data successfully\n";
mysql_close($conn); } ?>
The website says it is saving, but the updated information won't show up in the database. Does anybody know what I am doing wrong in this situation? P.S. it is a auto update form without a button.
I suspect your problem is that your UPDATE query is trying to update a row that doesn't exist. A REPLACE query will insert data, or replace it if there is a conflict with a table key.
While you're fixing that, you may as well toss out the code you have above. Give me 30 seconds with that web page and I could erase your whole database. (For example, what would happen if someone posted Hours as foo' OR 1=1 OR 'foo?)
It's a matter of personal preference, but I find PDO much easier to work with. It's less verbose and allows for much easier building of prepared statements, which are an essential security measure for any web application. It also allows you to use modern error handling methods like exceptions.
<?php
/* this block could be in a separate include file if it's going to be reused */
$db_host = "localhost";
$db_name = "u7105d15197_main";
$db_user = "user";
$db_pass = "asldkfjwlekj";
$db_opts = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
);
$conn = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass, $db_opts);
if(isset($_POST['formulier24'])) {
$sql = "REPLACE INTO evenement SET userName = ?, hours = ?";
$parameters = array($_POST["userName"], $_POST["hours"]);
try {
$stmt = $conn->prepare($sql);
$result = $stmt->execute($parameters);
$return = "Updated data successfully!";
} catch (PDOException $e) {
$return = "Could not update data! Error: " . $e->getMessage();
}
header("Content-Type: application/json");
echo json_encode($return);
}

Developing the login page in Phonegap using Ajax and on server MySQL

I have been stuck with this problem for days already. I used Ajax group of web development techniques to call the php file from the server. It appears that the success method was not called. Here is my code:
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
//$("#submitButton",form).attr("disabled","disabled");
var e = $("#email", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
//var str = form.serialize();
//alert(str);
$.ajax({
type: 'POST',
url: 'http://prefoparty.com/login.php',
crossDomain: true,
data: {email: e, password :p},
dataType: 'json',
async: false,
success: function (response){
alert ("response");
if (response.success) {
alert("you're logged in");
window.localStorage["email"] = e;
window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location.replace(main.html);
}
else {
alert("Your login failed");
//window.location("main.html");
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "main.html";
}
});
}
else {
//if the email and password is empty
alert("You must enter email and password");
}
return false;
}
In php, I used a typical MySQL call and as I run this file from Google Chrome browser. It returned the JSON correctly. Here is my php:
<?php
require_once('includes/configinc.php');
$link = mysql_connect(DB_HOSTNAME, DB_USERNAME,DB_PASSWORD) or die("Could not connect to host.");
mysql_select_db(DB_DATABASE, $link) or die("Could not find database.");
$uname = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM User_Profile WHERE Email = '$uname' AND Password = 'md5($password)'";
$result=mysql_query($sql);
$num_row = mysql_num_rows($sql);
$row=mysql_fetch_array($result);
if (is_object($result) && $result->num_rows == 1) {
$response['success'] = true;
}
else
{
$response['success'] = false;
}
echo json_encode($response);
//echo 'OK';
?>
Please check my code and point out where I did wrong.
Thank you all in advance :)
Adding
header("access-control-allow-origin: *")
to the Top of your PHP page will solve your problem of accessing cross domain request

Ajax post success function returning both success and error

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).

navigating to another view if count=1 in php file using sench

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');

Categories