ajax is not calling the function from php page - javascript

I'm having a problem with my code...
function retmsg isn't returning a value if javascript is implemented
<div id="pop">
Elunika
<div class="txt">Its the way to connect with your friends.</div>
<form action="login.php" method="post" id="login">
<input id="email" placeholder="E-mail" type="text" name="em" />
<input id="email" placeholder="Password" type="password" name="pwd"/>
<div class="txt1"><input type="checkbox" name="check" />Keep me logged in | Forgot Password ?</div>
<input id="loginButton" type="submit" value="Login" name="log" />
</form>
<span>Register</span>
<div id="error1"></div>
<div id="termdiv1"></div>
</div>
value returned from retmsg() function should display in div id="error"
login script...
if (isset($c))
{
$q = mysql_query("select * from registeration where email='$a' and password='$b'");
$r = mysql_num_rows($q);
if($r)
{
$_SESSION["Authenticated"] = 1;
$_SESSION['id'] = $a;
echo retmsg(1,"profile.php");
}
else
{
$_SESSION["Authenticated"] = 0;
die (retmsg(0,"Incorrect Information"));
}
}
function retmsg($status,$txt)
{
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
javascript code...
$(document).ready(function(){
$('#login').submit(function(e) {
att();
e.preventDefault();
});
$('#regForm').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
hideshow('loading',1);
error(0);
$.ajax({
type: "POST",
url: "submit.php",
data: $('#regForm').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
}
});
}
function hideshow(el,act)
{
if(act) $('#'+el).css('visibility','visible');
else $('#'+el).css('visibility','hidden');
}
function error(act,txt)
{
hideshow('error',act);
if(txt) {
$('#error').html(txt);
$('#regpop').css('height','419px');
$('#termdiv').css('margin-top','10px');
}
if(!txt) {
$('#regpop').css('height','400px');
$('#termdiv').css('margin-top','-20px');
}
}
function att()
{
hideshow1('loading',1);
error1(0);
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
dataType: "json",
success: function(retmsg){
if(parseInt(retmsg.status)==1)
{
window.location=retmsg.txt;
}
else if(parseInt(retmsg.status)==0)
{
error1(1,retmsg.txt);
}
hideshow1('loading',0);
}
});
}
function hideshow1(el,act)
{
if(act) $('#'+el).css('visibility','visible');
else $('#'+el).css('visibility','hidden');
}
function error1(act,txt)
{
hideshow1('error1',act);
if(txt) {
$('#error1').html(txt);
$('#pop').css('height','290px');
$('#termdiv1').css('margin-top','50px');
}
if(!txt) {
$('#pop').css('height','270px');
$('#termdiv1').css('margin-top','-35px');
}
}
in javascript code
retmsg should return txt parameter to the att function.....
att function is passing retmsg.txt value to the error1 function
part of the function error1 is working as retmsg.txt is not returning value...
rest of the javascript code is working fine...
rest of the code is same as of this...
only function names are different....
ANSWER *ANSWER* ANSWER
javascript code was all correct
made changes in the login script
$q = mysql_query("select * from registeration where email='$a' and password='$b'");
$r = mysql_num_rows($q);
if(!$r)
{
$_SESSION["Authenticated"] = 0;
die (retmsg(0,"Incorrect Information"));
}
else
{
$_SESSION["Authenticated"] = 1;
$_SESSION['id'] = $a;
echo retmsg(1,"profile.php");
}
function retmsg($status,$txt)
{
return json_encode(array('status' => $status, 'txt' => $txt));
}

Related

How can I make a jQuery script aware of a Codeigniter variable?

I have been developing a blogging application with CodeIgniter 3.1.8 and Twig. I am currently working on making a newsletter subscription system.
I have created a table named newsletter with 3 columns: id, email and subscription_date.
The newsletter subscription form:
<div id="messags" class="is-hidden h-text-center">
<div class="success is-hidden alert-box alert-box--success">You have successfully subscribed to our newsletter</div>
<div class="fail is-hidden alert-box alert-box--error">Sorry, the newsletter subscription filed</div>
</div>
<form name="newsletter" method="post" action="{{base_url}}newsletter/subscribe" id="newsletterForm" class="group" novalidate>
<input type="email" value="{{set_value('email') | striptags}}" name="email" class="email" data-rule-required="true" placeholder="Your Email Address">
<input type="submit" name="subscribe" value="subscribe">
</form>
The Newsletter_model model:
class Newsletter_model extends CI_Model {
public function subscriber_exists() {
$query = $this->db->get_where('newsletter', ['email' => $this->input->post('email')]);
return $query->num_rows() > 0;
}
public function add_subscriber() {
$data = [
'email' => $this->input->post('email'),
'subscription_date' => date('Y-m-d H:i:s')
];
return $this->db->insert('newsletter', $data);
}
}
As you can see above, I use the subscriber_exists() to make sure there are no duplicate emails.
The Newsletter controller is quite simple:
class Newsletter extends CI_Controller {
public function __construct(){
parent::__construct();
}
public function subscribe(){
$data['is_new_subscriber'] = true;
if (!$this->Newsletter_model->subscriber_exists()) {
$this->Newsletter_model->add_subscriber();
} else {
$data['is_new_subscriber'] = false;
}
}
}
The problem
I use jQuery AJAX to submit the form and the script is unaware of the is_new_subscriber variable:
(function($) {
// Add subscriber via AJAX
$("#newsletterForm").validate({
rules: {
email: {
email: true
}
},
submitHandler: function(form) {
var form = $("#newsletterForm"),
$fields = form.find('input[type="email"]'),
url = form.attr('action'),
data = form.serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function() {
$('#messags').slideDown(250).delay(2500).slideUp(250);
if (is_new_subscriber == true) {
$fields.val('');
$('#messags .success').show();
} else {
$('#messags .fail').show();
}
}
});
}
});
})(jQuery);
UPDATE
Adding echo json_encode($data) to the subscribe() and changing the submitHandler to the below ddi not splve the issue:
submitHandler: function(form) {
var form = $("#newsletterForm"),
$fields = form.find('input[type="email"]'),
url = form.attr('action'),
data = form.serialize();
$.ajax({
dataType: "json",
type: "post",
url: url,
data: data,
success: function() {
$('#messags').slideDown(250).delay(2500).slideUp(250);
$fields.val('');
if (data.is_new_subscriber == true) {
$('#messags .success').show();
} else {
$('#messags .fail').show();
}
}
});
}
How can I fix this issue?
Your code doesn't do anything with the $data variable, after you populate it. You could for example return it JSON-encoded.
public function subscribe(){
$data['is_new_subscriber'] = true;
if (!$this->Newsletter_model->subscriber_exists()) {
$this->Newsletter_model->add_subscriber();
} else {
$data['is_new_subscriber'] = false;
}
echo json_encode($data);
}
Then, in the success callback of your JS code you need to reference it:
...
success: function(data) {
$('#messags').slideDown(250).delay(2500).slideUp(250);
if (data.is_new_subscriber == true) {
$fields.val('');
$('#messags .success').show();
} else {
$('#messags .fail').show();
}
}
...
Here is what worked for me:
In the controller, I added echo json_encode($data):
class Newsletter extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function subscribe(){
$data['is_new_subscriber'] = true;
if (!$this->Newsletter_model->subscriber_exists()) {
$this->Newsletter_model->add_subscriber();
} else {
$data['is_new_subscriber'] = false;
}
echo json_encode($data);
}
}
The script:
(function($) {
// Add subscriber via AJAX
$("#newsletterForm").validate({
rules: {
email: {
email: true
}
},
submitHandler: function(form) {
var form = $("#newsletterForm"),
$fields = form.find('input[type="email"]'),
url = form.attr('action'),
data = form.serialize();
$.ajax({
dataType: "json",
type: "post",
url: url,
data: data,
success: function(response) {
$('#messags').slideDown(250).delay(2500).slideUp(250);
$fields.val('');
if (response.is_new_subscriber === true) {
$('#messags .success').show();
$('#messags .notnew').hide();
} else {
$('#messags .notnew').show();
}
},
error: function() {
$('#messags .fail').show();
}
});
}
});
})(jQuery);
The HTML:
<div id="messags" class="is-hidden h-text-center">
<div class="success is-hidden alert-box alert-box--success">You have successfully subscribed to our newsletter</div>
<div class="notnew is-hidden alert-box alert-box--info">You are already subscribed</div>
<div class="fail is-hidden alert-box alert-box--error">Sorry, the newsletter subscription filed</div>
</div>

Codeigniter-POST not working via ajax

I have a form, whose values I am trying to post after serializing to a controller via ajax. Below is the form:
Form
<form method="post" id="frm_reg_student" class="stop-propagation registration-form">
<input type="hidden" name="register[user_type]" value="2">
<input type="hidden" name="register[status_id]" value="1">
<div class="stud_register_error"></div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label for="input" class="control-label font-12 font-blue">First Name <span>*</span></label>
<input type="text" class="form-control" required="required" placeholder="Your First Name" name="register[first_name]">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label for="input" class="control-label font-12 font-blue">Last Name <span class="req">*</span></label>
<input type="text" class="form-control" required="required" placeholder="Your Last Name" name="register[last_name]">
</div>
</div>
</div>
</form>
js
$(".js-btn_reg_student").click(function(e){
e.preventDefault();
var serialData= $( "#frm_reg_student" ).serialize();
alert(serialData);
$.ajax ({
type: "POST",
url: '<?=base_url()?>index.php/register/signup/',
data: serialData,
success: function(result) {
alert(result);
output = JSON.parse(result);
if(result) {
if( 'success' == output.type ) {
location.href = output.location;
} else {
$('.stud_register_error').html(output.message);
}
}
}
});
});
Controller
public function signup(){
if($_SERVER["REQUEST_METHOD"]=="POST"){
print_r($_POST);
}
}
Here, $_POST comes out to be empty, it never goes inside the loop. If you see in the JS, I have included an alert with the serialized data, which even shows me the proper serialized data. I believe it is something wrong with the way I am posting it.
Any help!
Try on ajax
$(".js-btn_reg_student").click(function(e){
var formdata = $( "#frm_reg_student" ).serialize();
$.ajax({
type: "post",
url: "<?php echo base_url('register/signup');?>",
data: formdata,
dataType: 'json',
success: function(json) {
if (json[success]) {
alert(json['post']);
} else {
}
}
});
e.preventDefault();
});
And controller
public function signup() {
$data = array(
'success' => false,
'post' => ''
);
if ($this->input->server("REQUEST_METHOD") == 'POST')
{
$data['success'] = true;
$data['post'] = $_POST;
}
echo json_encode($data);
}
Try
$('#js-btn_reg_student').click(function () {
$.ajax ({
type: 'post',
url: '<?php echo base_url(); ?>index.php/test/signup/',
data: $('#frm_reg_student').serialize(),
dataType: 'json',
success: function(result) {
if(result.status == 'success')
{
alert(result.name);
}
else
{
alert(result.status);
}
}
});
});
And in Controller
public function signup ()
{
if($this->input->post())
{
$data = array('status' => 'success');
$data['name'] = $this->input->post('register[first_name]');
}
else
{
$data = array('status' => 'failed');
}
echo json_encode($data);
}
Try it and let me know if it works or not :)
Try to use below code.
$(".js-btn_reg_student").click(function(e){
e.preventDefault();
var serialData= $( "#frm_reg_student" ).serialize();
alert(serialData);
$.ajax ({
url: '<?=base_url()?>index.php/register/signup/',
method : 'POST',
data: serialData,
success: function(result) {
if(result) {
if( 'success' == output.type ) {
location.href = output.location;
} else {
$('.stud_register_error').html(output.message);
}
}
}
});
});
I think all the answers were correct in their own way. I figured out that it might be possible that it is not getting the DOM upon submit so I simply put it in document.ready and it worked!
Thanks

Ajax does not return any result

My Ajax function does not return any result
<div id="container">
<div id="connexion">
<form method="post" action="">
<input type="text" id="login">
<input type="password" id="password"><br />
<input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
<span id="errormess"></span>
</form >
</div>
</div>
$(document).ready(function(){
$("#ok").click(function() {
var login = $("#login").val();
var password = $("#password").val();
var dataString = 'login='+ login + '&password=' + password;
$.ajax({
type: "POST",
url: 'login.php',
data: dataString,
dataType: "json",
success: function(data) {
if (data == 0) {
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
}//success
});//ajax
return false;
});//ok
});//document
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$userId= $row["id"];
$today=time();
$week=strftime('%W',$today) ;
}
$arr = array(
'userId' => $userId,
'week' => $week,
);
echo json_encode($arr);
}
The issue is because the button click is submitting the form in the standard manner, meaning your AJAX request is prevented from completing. It's better practice to hook to the submit event of the form.
Also note that your PHP code will never return 0, it would be better to have a error handler should the AJAX not complete as expected. Finally, your current code is wide open to attack; you should look in to using SSL and using prepared statements to avoid SQL injection.
That said, here's a fix for your AJAX issues:
<div id="container">
<div id="connexion">
<form id="myform" method="post" action="">
<input type="text" id="login">
<input type="password" id="password"><br />
<input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
<span id="errormess"></span>
</form>
</div>
</div>
$("#myform").submit(function(e) {
e.preventDefault(); // stop standard form submission
$.ajax({
type: "POST",
url: 'login.php',
data: {
login: $("#login").val(),
password: $("#password").val()
},
dataType: "json",
success: function(data) {
$('#errormess').html(data);
}
error: function() {
$('#errormess').html("problem");
}
});
});
I think you are giving the data parameter wrongly. It should be like
var dataString = {"login": login,
"password": password}
HTML
<div id="container">
<div id="connexion">
<form method="post" action="">
<input type="text" id="login">
<input type="password" id="password">
<br />
<input name="Submit" type="button" id="ok" value="OK" class="btn ">;
<br /> <br />
<span id="errormess"></span>
</form >
</div>
</div>
JS
$(document).ready(function(){
$("#ok").click(function(e) {
e.preventDefault();
var login = $("#login").val();
var password = $("#password").val();
var dataString = {"login": login,
"password": password}
$.ajax({
type: "POST",
url: 'login.php',
data: dataString,
dataType: "json",
success: function(data) {
if (data == 0) {
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
}//success
});//ajax
return false;
});//ok
});//document
Also change the input type from submit to button and have and e.preventDefault() in your JS.
javascript code :
$(document).ready(function(){
$("#ok").click(function(e) {
e.preventDefault();
var data = (this.form).serialize(); // added code
$.ajax({
url: 'login.php',
data: data,
dataType:'json',
type:'POST',
async:false,
success: function(data) {
if (data.success == 0) { // added code
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
},
error: function(data) { // if error occured
}
});
});//ok
});//document
php code :
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND
password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$userId = $row["id"];
$today = time();
$week = strftime('%W', $today);
}
$arr = array(
'userId' => $userId,
'week' => $week,
);
echo json_encode($arr);
} else { // added code
$arr = array("success" => '0');
echo json_encode($arr);
}
Please do check. I have modified the response from PHP as well as jquery code.

jQuery-Ajax : insert data from php

I have this code:
for my view:
<b><input type="text" id="pagibigno" onclick="window.location.assign('#')"/></b>
<div id="pagibig_form">
<div class="err" id="add_err"></div>
<form>
<label>Pagibig Number:</label>
<input type="text" id="signpagibigno" name="signpagibigno" value="signpagibigno" />
<input type="text" id="txtpagibigno" name="txtpagibigno" />
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
</div>
addField.php
<?php
include 'dbconn.php';
$signpagibigno = $_GET['signpagibigno'];
$txtpagibigno = $_GET['txtpagibigno'];
echo "INSERT INTO `employer_profile` (`id`, `pagibig_no`, `buss_name`, `sss_no`, `div_code`, `address`, `zip_code`, `tin`, `contact_no`)
VALUES (NULL, '$txtpagibigno', NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
$sql = $conn->prepare("INSERT INTO `employer_profile` (`id`, `pagibig_no`, `buss_name`, `sss_no`, `div_code`, `address`, `zip_code`, `tin`, `contact_no`)
VALUES (NULL, '$txtpagibigno', NULL, NULL, NULL, NULL, NULL, NULL, NULL)");
// mysql_query($sql);
$sql->execute();
?>
popup.js
$(document).ready(function ()
{
$("#pagibigno").click(function ()
{
$("#shadow").fadeIn("normal");
$("#pagibig_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function ()
{
$("#pagibig_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function ()
{
pagibigno = $("#txtpagibigno").val();
$.ajax(
{
type: "GET",
url: "addField.php",
data: data,
success: function (html)
{
if (pagibigno != '')
{
$("#pagibig_form").fadeOut("normal");
$("#shadow").fadeOut();
}
else
{
$("#add_err").html("Please complete the field");
}
},
beforeSend: function ()
{
$("#add_err").html("Loading...")
}
});
return false;
});
});
when I run the dataField.php the data save to my database. but when I use the view, where the ajax takes place the data did not save.
I read this link for this codes Alert in Jquery pagination
Please help. thanks
You are not passing the data to the php page. See the jquery code below :
$(document).ready(function () {
$("#pagibigno").click(function () {
$("#shadow").fadeIn("normal");
$("#pagibig_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function () {
$("#pagibig_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function () {
txtpagibigno = $("#txtpagibigno").val();//Getting value from text field
signpagibigno = $("#signpagibigno").val();//Getting value from text field
$.ajax({
type: "GET",
url: "addField.php",
data: "txtpagibigno="+txtpagibigno+"&signpagibigno="+signpagibigno,//Passing the values to the php page
success: function (html) {
if (pagibigno != '') {
$("#pagibig_form").fadeOut("normal");
$("#shadow").fadeOut();
} else {
$("#add_err").html("Please complete the field");
}
},
beforeSend: function () {
$("#add_err").html("Loading...")
}
});
return false;
});
});

Ajax success: {return false;}

I want to return false from $.ajax when success is complete:
$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
success: function(result) {
return false;
}
});
This doesn't work. Is there a work around?
From your post I guess that you call a function that contains the $.ajax() and try to return false to that function. but you can't do that such way, because AJAX is asynchronous.
It's better to call a function from the ajax success function like following:
$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
success: function(result) {
var returned = true;
if(some_condition_not_satisfied) {
returned = false;
} else {
}
// call a function
calledFromAjaxSuccess(returned);
}
});
function calledFromAjaxSuccess(result) {
if(result) {
alert('TRUE');
} else {
alert('FALSE');
}
}
Maybe you could try something like this (values 1 and 0 should be changed to the ones that you use):
success: function(result){
if(result === '1'){
// do something
}
else
return false;
}
just use asunc false it can work fine i have implemented like that only
just try it
$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
async: false, //=>>>>>>>>>>> here >>>>>>>>>>>
success: function(result) {
return false;
}
});
it is working fine try it once
<form action="yourpage" method="post" onsubmit="return matchpass();">
<div>
<label> Name</label>
<input type="text" name="name" id="name">
</div>
<div>
<label> Email ID</label>
<input type="email" name="email" id="email">
</div>
<div>
<label> Mobile No</label>
<input type="text" name="mob" maxlength="10" onkeyup="check_if_exists();" autocomplete="off" id="mob">
</div>
<div>
<button type="button" >Send</button>
</div>
<span id="err"></span>
<div>
<label> OTP</label>
<input type="password" name="otp" id="otp" maxlength="6" placeholder="****">
<span id="err2"></span>
</div>
<div>
<input type="reset" value="Reset" class="reset-btn">
<input type="submit" name="submit" id="submit" value="Submit" >
</div>
</form>
<input type="hidden" id="otpcheck"/>
<script>
function matchpass()
{
$.ajax({
type:"post",
url: "yourpage",
data:{ mobile:mob,otp:otp},
success:function(data)
{
if(data==1)
{
document.getElementById("otpcheck").value=1; //important
}else{
document.getElementById("err2").style.color = "red";
document.getElementById("err2").innerHTML = "invalid OTP Number ";
document.getElementById("otpcheck").value=0; //important
}
}
});
if(document.getElementById("otpcheck").value==0){
return false;
}
}
I face this problem. then i found the actual solution. use async : false, inside ajax call
function thisisavailavailusername(uname){
var dataString = 'username='+ uname.value;
var trueorfalse = false;
$.ajax({
type: "post",
url: "/BloodBook/checkavailableusername",
data: dataString,
cache: false,
async : false, //user this then everything ok
success: function(html){
if(html=="true"){
$('#validusername').html('Available');
trueorfalse = true;
}else{
$('#validusername').html('Not Available');
trueorfalse = false;
}
},
error: function() {
alert("Something Wrong...");
}
});
return trueorfalse;
}

Categories

Resources