hai im working in wordpress the simple concept is if the changing password if the user enters the existing password wrong need to alert the user im trying it with json message, response is receiving as undefined unable to parse the data from response.
function choice_update_password(){
global $wpdb;
$old_password=$_REQUEST['old_password'];
$N_password=$_REQUEST['new_password'];
$user = wp_get_current_user();
$encrypt_pass= $user->data->user_pass;
if ($user && wp_check_password( $old_password, $user->data->user_pass, $user->ID) ) {
wp_set_password($N_password, $user->ID);
$url="profile";
$view_profile=site_url($url);
echo json_encode(array("type"=>"success","data"=>"","url"=> $view_profile));
die();
}else{
echo json_encode(array("type"=>"failure","data"=>""));
die();
}
}
and the ajax part
function mail_prop_update($clsfrm) {
var $form = jQuery($clsfrm),$dataType = "json";
$form.on('click', 'input[type=submit]', function(e) {
var $elements = $form.find('input:not(input[type="submit"],input[type="button"],input[type="hidden"],input[type="file"],input[type="text"].not-required),textarea#message');
var $bool = $elements.validate();
var email = $form.find('input[type="email"]').val();
var action = $form.find('input[name="action"]').val();
if ($bool) {
ajax_submit($form, $elements, $dataType);
}
alert(e.responseText.type);
e.preventDefault();
});
}
Related
I am submitting data to a controller function via AJAX, doing what I need to do with the data, and trying to echo it back out to the ajax function.
The issue I am having, is the controller is dumping out the error message and trying to redirect me to the actual function. Obviously the function doesn't have a view, which results in a blank white screen with the response echoed out in the top left corner.
Here is the ajax:
$('#submit_new_split_promo').on('click',function(e){
e.preventDefault();
var id = $(this).data('id');
$('#d_overlay').show();
form = {};
$.each($('#promo-mail-split-add-'+id).serializeArray(),function(k,v){
form[this.name] = this.value;
});
$.ajax({
url:$('#promo-mail-split-add-'+id).attr('action'),
type:"POST",
dataType: "json",
data: form
}).done(function(result){
var res = JSON.parse(result);
if (res == 'Duplicate') {
$('#ms-promo').css('border','3px solid red');
$('#ms-promo').effect('shake');
$('#dynamodal-unique-title').text('That code has been used. Please enter a new Promo Code.');
$('#dynamodal-unique-title').text('That code has been used. Please enter a new Promo Code.').css('color','red').delay(2000).queue(function(next){
$('#dynamodal-unique-title').text('Create Mail Split Promo');
next();
});
return false;
}
$('#mail_split_promo_'+id).modal('toggle');
if (res == false) {
alert('Mail Split Promo did not save. Please try again.');
} else {
$('#add-promo-to-split-'+id).prop('disabled',true);
$('#promo-view-abled-'+id).hide();
$('#promo-view-disabled-'+id).show();
$('#promo-view-disabled-'+id).prop('disabled',false);
}
}).fail(function(){
}).always(function(){
$('#d_overlay').hide();
});
});
Here is the Controllers code
public function addpromo() {
$this->Authorization->skipAuthorization();
$this->request->allowMethod(['get','post']);
$this->autoRender = false;
$data = $this->request->getData();
$mail_split_id = $data['mail_split_id'];
$code = $data['code'];
$result = false;
$doesExist = $this->Promos->findByCode($code)->toArray();
if ($doesExist) {
$result = 'Duplicate';
}
if ($result !== 'Duplicate') {
$MailSplits = $this->getTableLocator()->get('MailSplits');
$mailSplit = $MailSplits->get($mail_split_id);
$entity = $this->Promos->newEmptyEntity();
foreach ($data as $key => $val) {
$entity->$key = $val;
}
$entity->record_count = $mailSplit->record_count;
$result = $this->Promos->save($entity);
if ($this->get_property($result,'id')) {
$promo_id = $result->id;
$MailSplits = $this->loadModel('MailSplits');
$mentity = $MailSplits->get($mail_split_id);
$mentity->promo_id = $promo_id;
$updated = $MailSplits->save($mentity);
if ($this->get_property($updated,'id')) {
$result = true;
} else {
$result = false;
}
$output = [];
exec(EXEC_PATH.'AddPromoToRecordSplits '.$promo_id,$output);
} else {
$result = false;
}
}
ob_flush();
echo json_encode($result);
exit(0);
}
The URL it is trying to redirect me to is: /promos/addpromo when I really just need to stay on the same page, which would be /mail-jobs/view
Response dumped to browser
A couple of things to note:
I have tried adding the function to the controllers policy, and actually authorizing an initialized entity. This has no effect and does not change the issue I am facing.
Something that is more frustrating, I have essentially the same code (ajax structure and controller structure) for other forms on the page, and they work just fine. The only difference seems to be any form that utilizes ajax that is on the page on render, works just fine. The ajax functions I am having an issue with, all seem to be from the forms rendered in Modals, which are different elements. Every form in a modal / element, gives me this issue and that's really the only pattern I have noticed.
Any help is greatly appreciated, I know it's an odd and vague issue.
Thank you!
I have a script running and working, however the insert into members part don't work:
function register_member($username,$name,$email,$password) {
$time = time();
$ip = get_ip();
db()->query("INSERT INTO members (full_name,username,email,password,ip_address,last_active,date_created,banned,active)VALUES(?,?,?,?,?,?,?,?,?)",
$name,$username,$email,$password, $ip, $time, $time,0,1);
//login user
login_user($username, $pass, false);
if (config('auto-follow', '')) {
$users = explode(',', config('auto-follow'));
foreach($users as $user){
$user = get_user($user);
if ($user) {
follow($user['id']);
}
}
}
return true;
}
It seems for me that it can't read the db()->query ("INSERT INTO part. When I remove that query, the signup script can complete reading the function, but if I leave it in, it returns a 500 internal error. Any ideas?
Finally got the php.ini to change, and it is in the js script the error is happening. On this line here: var json = jQuery.parseJSON(result);
$(document).on("submit", "#signup-form", function() {
$(".loader-container").fadeIn();
$(this).ajaxSubmit({
url : baseUrl + 'signup',
success : function(result) {
var json = jQuery.parseJSON(result);
if (json.status == 1) {
//we can redirect to the next destination
window.location.href = json.url;
notify(json.message, 'success');
} else {
notify(json.message, 'error');
$(".loader-container").fadeOut();
}
}
})
return false;
});
I'm trying to implement google sign-in to on my website.
I've done the steps from here Authenticate with Google.
This function executes after i have logged in to google :
function onSignIn(googleUser) {
var googleResponse = googleUser.getAuthResponse();
google_login(googleResponse, true);
};
Google_login function:
function google_login(res) {
var httpObject = getXMLHTTPObject();
var ajax_url = siteURL + 'google_login';
var params = 'token='+encodeURIComponent(res.id_token);
httpObject.open('POST', ajax_url, true);
httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpObject.onreadystatechange = function() {
if (httpObject.readyState == 4) {
if(httpObject.responseText == 'true') {
window.location = httpObject.responseURL;
}
else {
if(httpObject.responseText == '') {
window.location = siteURL + 'login_again';
}
else {
window.location = siteURL + 'google_login_error';
}
}
}
};
httpObject.send(params);
}
And in my model I'm using this code:
private $google_client;
function Google_model() {
parent::__construct();
$this->google_client = new Google_Client(['client_id' => 'my_client_id','client_secret' =>'my_client_secret']);
}
function check_google_user($access_token) {
$payload = $this->google_client->verifyIdToken($access_token);
if ($payload) {
return $payload;
}
return false;
}
In my controller I'm calling check_google_user function.
And here appears a strange behaviour. Sometimes when I try to login I get the payload, and sometimes not (PS: I'm trying to login with the same user in the same day). Am I doing something wrong?
EDIT:
I'm getting this error: Caught exception: Cannot handle token prior to 2017-01-25T16:20:24+0200
Solved this by commenting these lines in firebase JWT.php file:
throw new BeforeValidException(
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
);
I have the following username lookup function that checks if the username is available.
<script language="javascript">
function lookUpUsername(){
var name = document.getElementById('username').value;
//alert(name);
$.post(
'users/ajax_lookUpUsername',
{ username: name },
function(response) {
if (response == 1) {
// alert('username available');
} else {
// setTimeout("alert("Here I am!")", 5000);
alert('Username Already Taken! Please Select Another Name.');
}
});
}
</script>
And here is my AJAX_lookUpUsername function in the controller:
function ajax_lookUpUsername(){
$username = $this->input->post('username');
$this->db->where('username', $username);
$query = $this->db->get('mcb_users');
if ($query->num_rows() > 0){
echo 0;
} else {
echo 1;
}
The code works fine. When a user enters an existing username, it displays an alert message, but, when a user continues without modifying it and clicks on the save button, it gets saved!
Is there any way to redirect the user before saving to the database from the controller?
You can do this by using onsubmit form validation also. But, there is another approach too.
You can do this through controller also. Add the following code in save function of your controller, just before inserting data to database:
$userarraydb = $this->mdl_users->getAllusername();
foreach($userarraydb as $dbusersname)
{
if(($dbusersname->text == $username) && ($dbusersname->id != $user_id) )
{
//echo $this->lang->line('user_name_must_be_unique');
//sleep(1);
?> <script> alert('Record can not be saved! Username must be unique.'); </script> <?php
return false;
}
}
and add following function to your user model:
function getAllusername()
{
$teller_id = $this->session->userdata('user_id');
$this->db->select('username as text, id as id');
$this->db->from('mcb_users');
$result = $this->db->get();
$username = $result->result();
//all user name taneko cha
return $username;
// return $result->result();
}
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();