PHP Function can't read jquery POST data? - php

Alright so I have this function
<?php
/**
* #author Mitchell A. Murphy
* #copyright 2011
*/
include ('func_lib.php');
connect();
echo (check($_POST['input']) ? 'true' : 'false');
function check($args)
{
$args = strtolower($args);
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (preg_match($checkemail, $args))
{
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
echo "type=email:";
if (mysql_num_rows($res) > 0)
{
return true;
} else
{
return false;
}
} else
{
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
echo "type=username:";
if (mysql_num_rows($res) > 0)
{
return true;
} else
{
return false;
}
}
}
?>
The function should be accessed by this jquery script:
$('form.register .submit').click(validateRegister);
function validateRegister() {
//Variables
var emailExists = false;
var userExists = false;
var $error = "";
//Executes functions
email();
function email() {
var $error = $('#email .error');
var input = $('#email input').val();
var emailRE = /^.*#.+\..{2,5}$/;
if (input.match(emailRE)) {
$error
.html('<div>Proper Email Format: <span>Hello#Yoursite.com</span></div>')
.animate({
'left': '-130px',
'opacity': '0'
});
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'includes/checkExist.php',
data: input,
statusCode: {
404: function () {
alert('page not found');
}
},
success: function (data) {
alert(data);
},
error: function () {
alert("error bro");
}
});
}
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
} else if (emailExists == false) {
alert("Email doesnt exist!");
}
} else {
//Email doesn't match
$error
.html('<div>Proper Email Format: <span>Hello#Yoursite.com</span></div>')
.animate({
'left': '-150px',
'opacity': '1'
});
}
}
return false;
}
But for some reason the script (js) isn't sending any data? if so, how do i reference it. I am the backend developer but the designer who did the javascript left me to fix this. I know the php works because I made a test form to send the data with this html markup:
<form action="includes/checkExist.php" method="post">
<input type="text" name="input" />
<input type="submit" name="submit" />
</form>
And that works...so why is the input from jquery returning as NULL?

See that checkExisting_email() don't return anything, so emailExists = checkExisting_email(); will not set emailExists. This data will only be provided on the callback function, which today only display the result on an alert().
To make things easier, use jQuery ajax validation field remote. Check the documentation and sample.

You need to pass in a key/value pair for the "data", not just the value.
As is, your form is going to be posted with a querystring looking like this:
target.php?asdf#hotmail.com
it should be:
data: { input: input },
This will set the querystring to look like:
target.php?input=asdf#hotmail.com
Also, since you are getting the value out of an element by ID, you dont need to specify the input tag.
var input = $('#email').val();

Related

Codeigniter Ajax Post not working

Hello guys im trying to create a simple voting for comments like and dislike but i want to do that with jquery Ajax so i don't want to refresh the page when someone like it.
And this is my jquery code
$(document).ready(function(){
$(".vote-btn").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
// alert(upOrDown); = provides --> id,name
// var all = 'voteId:'+upOrDown[0]+ ',upOrDown:' +upOrDown[1];
// alert(all);
$.ajax({
type: "POST",
url: "http://localhost/Dropbox/cipr/index.php/demo",
cache: false,
dataType:'json',
data:{'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
}else{
alert('Sorry Unable to update..');
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
this is my Controller code Demo.php
<?php
class Demo extends CI_Controller {
function Demo(){
parent::Controller();
$this->load->model('sygjerimet');
}
public function index(){
$voteId= $this->input->post('voteId');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='voteup' || true){
$updateRecords = $this->sygjerimet->updateUpVote($voteId);
}else{
$updateRecords = $this->sygjerimet->updateDownVote($voteId);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
}
And this is my model code sygjerimet.php
<?php
Class Sygjerimet extends CI_Model
{
function shtoSygjerimin()
{
$permbajtja = $this->input->post('idea');
$data = array(
'permbajtja' => $permbajtja
);
$this->db->insert('pr_sygjerimet', $data);
}
function updateDownVote($voteId){
$sql = "UPDATE pr_sygjerimet set vote_down = vote_down+1 WHERE ID =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
function updateUpVote($voteId){
$sql = "UPDATE pr_sygjerimet set vote_up = vote_up+1 WHERE ID =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
}
And this is my view Code
<?php
$query = $this->db->query('SELECT * FROM pr_sygjerimet');
foreach ($query->result() as $row)
{
echo "<div class='sygjerimi'>";
echo htmlspecialchars($row->permbajtja);
if(!$log_in):
echo '<br>';
echo ' <button id="'.$row->ID.'_votedown" class="vote-btn"><i class="fa fa-thumbs-down">'.htmlentities($row->vote_down).'</i></button> ';
echo ' <button id="'.$row->ID.'_voteup" class="vote-btn"><i class="fa fa-thumbs-up">'.htmlentities($row->vote_up).'</i></button> ';
endif;
echo "</div>";
}
?>
That's it guys when i cilck vote it executes this code
alert('Error while request..');
If anyone can help that would be Great :) Thanks
Most likely this is the CI CSRF protection; if you use POST, CI automatically checks the CSRF hidden field and since you are building the ajax post yourself, it's not sending the hidden field so it bags on you.
Check the several $config['csrf_*'] lines in your config/config.php file. You can disable (but I don't recommend this). You can also serialize the form in jQuery and send that, and it should work for you, and keep you a bit more protected from CSRF attacks.
Just to rule this in or out, you can disable the 'csrf_protection' and if it works then, you can enable it again and then change your javascript to serialize the form and use that as your data with your ajax post.
try this
$.ajax({
//pull the toke csrf like this
data:{'<?php echo $this->security->get_csrf_token_name();?>':'<?php echo $this->security->get_csrf_hash();?>'},
});

How to check if email exists

I'm trying to get an error that says that the email exists already and I'm trying to use jquery. I'm using ajax and it does work, because when I use firebug and I go to the console it says that the email address exists but I would like that to appear on the page.
index.php
<div class="register-newsletter">
<form id="myForm">
<input type="email" name="email" id="email" value="enter email address" required>
<input type="image" value="SUBMIT" id="sub" src="images/register.jpg">
</form>
<a class="newsletter" href="javascript:void(0);">Add to e-mailing list</a>
This is my jquery
$("#email").click(function(){
if($.trim($(this).val() ) == "enter email address"){
$(this).val("");
}
})
$("#email").blur(function(){
if($.trim($(this).val() ) == ""){
$(this).val("enter email address");
}
})
$("#sub").click(function () {
var email = $.trim($("#email").val());
if(email == "" || !isValidEmailAddress(email)){
alert('enter valid email');
return false;
}
var ajaxid = ajax("ajax/userInfo.php","email="+encodeURIComponent(email));
$("#result").html($.trim(ajaxid));
});
$("#myForm").submit(function () {
return false;
});
function clearInput() {
$("#myForm :input").val('');
}
$('p').hide();
$('#myForm').hide();
$(".newsletter").click(function(){
$(".newsletter").hide();
$('#myForm').show();
});
$('#myForm').submit(function(){
$('#myForm').hide();
$('p').show();
});
and this is my userInfo.php
<?php
include("../config.php");
global $_NEWSLETTER_CUSTOMERS_TABLE;
$email = $_POST['email'];
//$email = html_entity_decode(str_replace("'", "\'", $_POST["email"]));
$query = mysql_query("SELECT * FROM $_NEWSLETTER_CUSTOMERS_TABLE WHERE `email` = '".$email."'");
if(mysql_num_rows($query) >0){
echo '<span class="exists">Email address arleady exists</span>';
} else {
if(mysql_query("INSERT INTO $_NEWSLETTER_CUSTOMERS_TABLE(email) VALUES('$email')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
}
You are attempting to append the data incorrectly. jQuery's ajax() method takes a function that will be called upon the success of the request, called success. At the moment, you are trying to append ajaxid, (which contains ajax()s return value, not the result of the request) to #result.
var ajaxid = ajax("ajax/userInfo.php","email="+encodeURIComponent(email));
$("#result").html($.trim(ajaxid));
Should be more like:
var ajaxid = ajax("ajax/userInfo.php", {
data:"email="+encodeURIComponent(email),
success:function(d){
$("#result").html($.trim(d));
}
});
Use jQuery.post() inside your click handler:
$.post('ajax/userInfo.php', { email: email }, function(data) {
alert(data.message);
}, 'json');
And in your PHP file instead of echo use:
$response = array();
$response['message'] = mysql_query("...") ? 'success' : 'fail';
return json_encode($response);
You must return the value, eg JSON
Your JS
$("#sub").click(function () {
$.ajax({
url : "ajax/userInfo.php",
dataType : "json",
error : function(request, error) {
alert("Erreur : responseText: "+request.responseText);
},
success : function(data) {
alert(data.email_exist);
$("#result").html(data.email_exist);
}
});
});
AND your PHP
if(mysql_num_rows($query) >0){
$result = array(
'email_exist' => 'Email address arleady exists'
);
}
json_encode($result);

how to do i get returned data from ajax call

I am getting a undefined on the username from $sql which should be the returned data from the query.
$('#userlist').on('change', function () {
var selected = $("select option:selected").text();
console.log(selected);
// use ajax to run the check
$.ajax({
url: '/php/connect/userdropdowncheck.php',
type: 'JSON',
data: selected,
success: formfill,
error: function (xhr, status, err) { console.log(xhr, status, err); }
});
function formfill(sql) {
var username = sql['UserLogin'];
var email = sql['UserEmail'];
var admin = sql['admin'];
var firstname = sql['firstname'];
var lastname = sql['lastname'];
var title = sql['title'];
var company = sql['company'];
console.log(username);
if (username.length > 0) {
console.log('Found user');
console.log(username);
$('#username').html($username);
}
else {
console.log('Failed to find user');
}
}
});
PHP code:
<?php
session_start();
include 'anonconnect.php';
// username and password sent from form
$myusername= $_POST['selected'];
$sql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$sql->execute(array(':login' => $myusername));
$user = $sql->fetch();
/*** close the database connection ***/
$dbh = null;
if($user->rowCount() == 1){
echo 1;
echo json_decode($user);
else {
echo 0;
}
?>
It is pulling the text from the selected drop down just fine and passing it but the function on the return cannot find it.
your jquery code could be:
function formfill(sql) {
var username = sql['UserLogin'];
var email = sql['UserEmail'];
var admin = sql['admin'];
var firstname = sql['firstname'];
var lastname = sql['lastname'];
var title = sql['title'];
var company = sql['company'];
console.log(username);
if (username.length > 0) {
console.log('Found user');
console.log(username);
$('#username').html($username);
}
else {
console.log('Failed to find user');
}
}
$('#userlist').on('change', function () {
var selected = $("select option:selected").text();
$.ajax({
url: '/php/connect/userdropdowncheck.php',
type: 'POST',
data: {UserLogin:selected},
success: function(data){
formfill(data)
},
error: function (xhr, status, err) { console.log(xhr, status, err); }
});
});
and your php code:
<?php
session_start();
include 'anonconnect.php';
// username and password sent from form
$myusername= $_POST['UserLogin'];
$sql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$sql->execute(array(':login' => $myusername));
$user = $sql->fetch();
/*** close the database connection ***/
$dbh = null;
if($sql->rowCount() == 1){
//echo 1; //if you echo this it will cause that your jquery code will not be able to read the response as JSON and serialize it in array
echo json_encode($user); // php array to json object
} else {
echo 0;
}
?>
If you using JSON type, you can serialize your javascript array and then pass to php.
Ex: var jsonString = JSON.stringify(Array);
In php, use json_decode() and json_encode()
Ex: $data = json_encode($sql)

Jquery, Codeigniter 2.1 - How to check if update is succesfull

How can I see if the update, after JQuery post, is succesfull?
JQuery code:
var code = $('#code'),
id = $('input[name=id]').val(),
url = '<?php echo base_url() ?>mali_oglasi/mgl_check_paid';
code.on('focusout', function(){
var code_value = $(this).val();
if(code_value.length < 16 ) {
code.after('<p>Code is short</p>');
} else {
$.post(url, {id : id, code : code_value}, function(){
});
}
});
CI controller:
function mgl_check_paid()
{
$code = $this->input->post('code');
$id = $this->input->post('id');
$this->mgl->mgl_check_paid($code, $id);
}
CI model:
function mgl_check_paid($code, $id){
$q = $this->db->select('*')->from('ad')->where('id_ad', $id)->where('code', $code)->get();
$q_r = $q->row();
if ($q->num_rows() != 0 && $q_r->paid == 0) :
$data['paid'] = 1;
$this->db->where('id_ad', $id);
$this->db->update('ad', $data);
return TRUE;
else :
return FALSE;
endif;
}
I need to check if update is successful and show appropriate message.
CI controller:
function mgl_check_paid()
{
$code = $this->input->post('code');
$id = $this->input->post('id');
// could also return a json or whatever info you want to send back to jquery
echo ($this->mgl->mgl_check_paid($code, $id)) ? 'yes' : 'no';
}
Jquery
var code = $('#code'),
id = $('input[name=id]').val(),
url = '<?php echo base_url() ?>mali_oglasi/mgl_check_paid';
code.on('focusout', function(){
var code_value = $(this).val();
if(code_value.length < 16 ) {
code.after('<p>Code is short</p>');
} else {
$.post(url, {id : id, code : code_value}, function(data){
// display the data return here ... simple alert
//$('.result').html(data); // display result in a div with class='result'
alert(data)
});
}
});
You may also want to read more # http://api.jquery.com/jQuery.ajax/ (if you want to do better error checking like failure)
First of all, mad props, I <3 CI and jQuery. Secondly, you need to echo in order to return data to your jQuery post.
Gimmie 5 to fix something at work and i'll edit this answer with more detail.

Trying to send data to mysql, receiving callback issue

This is a mailing list script. It works by itself without jquery but I am trying to adapt it to work with ajax. However, without success. When the $.sql part is commented out it returns the variables in the url string successfully. However, when I uncomment that part of the js file and introduce the PHP into things it simply refreshes the page with the email address still in the input box. By itself, the PHP works so I'm at a loss as to where I'm going wrong. Here's what I have... any help would be appreciated.
Form :
<form name="email_list" action="" id="maillist_form">
<p><strong>Your Email Address:</strong><br/>
<input type="text" name="email" id="email" size="40">
<input type="hidden" name="sub" id="sub" value="sub">
<p><input type="submit" value="Submit Form" class="email_submit"></p>
</form>
JQuery :
$(function() {
$('#maillist_form').submit(function() {
var email = $("input#email").val();
if (name == "") {
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") {
$("input#sub").focus();
return false;
}
var dataString = $("#maillist_form").serialize();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function() {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block');
});
}
});
return false;
});
});
PHP :
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["sub"] == "sub")) {
if ($_POST["email"] == "") {
header("Location: mailing_list_add2.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo '';
} else {
echo 'Invalid Email Address';
exit;
}
// check that the email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// cleans all input variables at once
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
// add record
$add_sql = "INSERT INTO subscribers (email) VALUES('$email')";
$add_res = mysqli_query($mysqli, $add_sql)
or die(mysqli_error($mysqli));
$display_block = "<p>Thanks for signing up!</p>";
// close connection to mysql
mysqli_close($mysqli);
} else {
// print failure message
$display_block = "You're email address - ".$_POST["email"]." - is already subscribed.";
}
}
}
?>
I won't put the include code in here because I'm assuming it is correct - unless the introduction of the jquery means this needs to be adapted as well.
Your AJAX is not catching back the result:
$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function(response) {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block').html(response); //just an example method.
//Are you sure the selector is the same?
//Can also be $(this).html(response);
}
});
And as noted by gdoron, there's no "name" variable. Maybe you meant "email" and "sub", respectively?
PHP response, also, isn't echoed back. Just put:
echo $display_block;
You don't echo an data from the server, not trying to get data in the success callback, and the fadeIn callback just have a selector,.
You check for the wrong variable:
var email = $("input#email").val();
if (name == "") { // Didn't you mean email?
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") { // Didn't you mean sub?
$("input#sub").focus();
return false;
}
How can it work!?

Categories