Accessing JSON values in JQUERY/AJAX based on condition - php

Please be patient because I know this question might have been answered but I have not been able to find it. I have been working on a project & lately I just started using AJAX.
My JSON is coming from PHP, which includes errors and success, now the issue is how do I access success(if the registrattion is successful to display as Text(not alert)) and display errors when registration fails.
What conditions should be used?
<div class="remodal" data-remodal-id="RegisterModal">
<div class="popup-1">
<div class="popup-content" id="register_container">
<div id="register_title" class="popup-title text-purple">Sign Up</div>
<div class="reg-notification">
<p>You Successfully registered to our website and now you can login and use our services</p>
Continue
</div>
<div id="json"></div>
<form id="register-form" action="register.php" method="POST">
<div class="form-grp">
<!--<label>Username</label>-->
<input type="text" id="username" name="username" placeholder="Username">
</div>
<div class="form-grp">
<input type="email" name="register_email" id="register_email" placeholder="Email">
</div>
<div class="form-grp">
<input type="password" id="register_password" name="register_password" placeholder="Password">
</div>
<div class="form-grp">
<input type="password" id="confirm_password" name="confirm_password" placeholder="Retype Password">
</div>
<div class="btn-grp">
<button type="submit" name="submit" class="button-purple" id="do_register">Sign Up</button>
<button class="button-white" style="margin-left: 30px;" data-remodal-target="LoginModal">Login to access</button>
</div>
</form>
</div>
This is my PHP below
if (strlen($password) >= 8 && strlen($password) <= 60) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$account->addUser($username, $password, $email);
if ($account->userExist()) {
$message['email'] = "Email Address Is Already Registered!";
} else {
$account->create();
$message['type'] = "success";
}
} else {
$message = 'Invalid email!, Please enter a valid Email';
}
header('Content-Type: application/json');
$response = ['message' => $message];
echo json_encode($response);
// echo json_encode($message);
//echo $message;
and this is my AJAX
$.ajax({
type: 'POST',
url: 'register.php',
dataType: 'json',
data: formData,
success: function (data) {
$("#json").html(data["message"]);
//response = response.slice(0, -1);
//response = JSON.parse(response);
//var json = JSON.parse(response);
//var resdata = response;
//var json = $.parseJSON(response);
//if (resdata) {
//alert(resdata['success']);
//alert(json['success']);
// $("#register-form").addClass("remove-form");
// $("#register_container").addClass("register-container-active");
// $("#register_title").html("Register was Successful");
// $(".reg-notification").addClass("show-reg-notification");
//}else if (resdata['email']) {
//alert(resdata['email']);
//}
//alert(json['email']);
//$("#msg").html(json.email);
//}
console.log(response);
},
error:function(error){
console.log(error);
}
});
As you can see all the codes I commented are failed codes, I like to display the message coming from PHP in my #json ID.
What I like to do is get the 'success' encoded from PHP to my HTML through AJAX, if user registration is successful, also get the 'email' error out if user exists.
I have no idea what condition to use in AJAX to test this or how to go about it and I know it will be something simple.
But I may be to clustered in the head to figure it ..as I keep looking at :(

You need to modify your php response first.
$response = [];
if (strlen($password) >= 8 && strlen($password) <= 60) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$account->addUser($username, $password, $email);
if ($account->userExist()) {
$response['type'] ="error";
$response['msg'] = "Email Address Is Already Registered!";
} else {
$account->create();
$response['type'] = "success";
$response['msg']="You are signed in successfully";
}
} else {
$response['type'] ="error";
$response['msg'] = 'Invalid email!, Please enter a valid Email';
}
echo json_encode($response);
}
//output
{"type":"success","msg":"You are signed in successfully"}
//ajax
$.ajax({
type: 'POST',
url: 'register.php',
dataType: 'json',
data: formData,
success: function (data) {
$("#json").html(data["msg"]);
//get the response type simply as data['type'] this will give you success or error
console.log(data);
},
error:function(error){
console.log(error);
}
});

$.ajax({
type: 'POST',
url: 'register.php',
dataType: 'json',
data: formData,
success: function (data) {
console.log(data.message.email);//that will print email already registered
var result=data.message.email;
if(result=="success"){
$("#json").empty();//incase it has previous data
$("#json").append(result);//that will append data in your div
}
else{
$("#json").empty();//incase it has previous data
$("#json").append(result);//that will append data in your div
}
},
error:function(error){
console.log(error);
}
});

Related

Post and display data on the same page using PHP (MVC) AJAX

I'm trying to post input data and display it on the same page (view_group.php) using AJAX but I did not understand how it works with MVC, I'm new with MVC if anyone could help me it would be very helpful for me.
view_group.php
<script type = "text/javascript" >
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
var status_content = $('#status_content').val();
$.ajax({
type: "POST",
url: "view_group.php",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {}
});
});
}); </script>
if(isset($_POST['postStatus'])){ $status->postStatus($group_id); }
?>
<form class="forms-sample" method="post" id="form-status">
<div class="form-group">
<textarea class="form-control" name="status_content" id="status_content" rows="5" placeholder="Share something"></textarea>
</div>
<input type="submit" class="btn btn-primary" id="submit" name="submit" value="Post" />
</form>
<span id="result"></span>
my controller
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
}
first in the ajax url you must set your controller url , then on success result value will be set on your html attribute .
$.ajax({
type: "POST",
url: "your controller url here",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {
$('#result).text(result);
}
});
Then on your controller you must echo the result you want to send to your page
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
echo $status;
}

$_POST data is not passing to my function in Wordpress via AJAX

I have created an AJAX function in Wordpress. The function is called on form submission. The function is run, but it is not receiving any of the form data that I have submitted. What am I missing?
PHP Function
I have added the PHP function here, which is called successfully via AJAX. This form creates a new user successfully, but only when I create the variables manually (eg. see $new_user_data['user_login'] = 'This Text Works';). For some reason, the $_POST data isn't coming through to the function.
add_action("wp_ajax_register_user", __NAMESPACE__ . "\\register_user");
add_action("wp_ajax_nopriv_register_user", __NAMESPACE__ . "\\register_user");
function register_user() {
// NONCE VERIFICATION
if ( !wp_verify_nonce( $_REQUEST['nonce'], "rtr_register_nonce")) {
exit("Oops! This is embarassing!");
}
// Get all post data for the user.
$new_user_data = array();
$new_user_data['first_name'] = sanitize_text_field($_POST['first-name']);
$new_user_data['last_name'] = sanitize_text_field($_POST['last-name']);
$new_user_data['user_email'] = $_POST['email'];
$new_user_data['user_pass'] = sanitize_text_field($_POST['password']);
$new_user_data['user_login'] = 'This Text Works';
$new_user_data['role'] = 'subscriber';
// Create the User
$registered_user = wp_insert_user( $new_user_data );
$result['user'] = $registered_user;
// AJAX CHECK
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
JQuery
function registerUser(){
var nonce = $('#regForm').attr("data-nonce");
var formData = $('#regForm').serialize();
$.ajax({
url: rtr_register_user.ajaxUrl,
type: 'post',
dataType: 'json',
data : {action: 'register_user', nonce: nonce, formData: formData},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("form-tab");
// Exit the function if any field in the current tab is invalid:
if (n === 1 && !validateForm()) {
return false;
}
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form... :
if (currentTab >= x.length) {
//...the form gets submitted:
//document.getElementById("regForm").submit();
registerUser();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
$('#nextBtn').click(function () {
nextPrev(1);
});
$('#prevBtn').click(function () {
nextPrev(-1);
});
Form
<?php
$nonce = wp_create_nonce("rtr_register_nonce");
$link = admin_url('admin-ajax.php?action=register_user&nonce='.$nonce);
?>
<form id="regForm" <?php echo 'data-nonce="' . $nonce . '"'; ?> action="<?php echo $link; ?>" method="post" enctype="multipart/form-data">>
<div class="my-3 text-center">
<span class="form-step">1</span>
<span class="form-step">2</span>
</div>
<div class="form-tab">
<p><input name="first-name" placeholder="First Name" oninput="this.className = ''"></p>
<p><input name="last-name" placeholder="Last Name" oninput="this.className = ''"></p>
<p><input name="dob" type="date" oninput="this.className = ''"></p>
</div>
<div class="form-tab">
<p><input name="email" type="email" placeholder="Email" oninput="this.className = ''"></p>
<p><input name="password" type="password" placeholder="Password" oninput="this.className = ''"></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" class="btn btn-brand" id="prevBtn">Previous</button>
<button type="button" class="btn btn-brand" id="nextBtn">Next</button>
</div>
</div>
</form>
Seems you are not triggering registerUser() check following script works fine for me
jQuery(document).ready(function($) {
jQuery('body').on('click', '#nextBtn', function() {
registerUser();
});
});
function registerUser(){
var nonce = jQuery('#regForm').attr("data-nonce");
var formData = jQuery('#regForm').serialize();
jQuery.ajax({
url: ajaxurl,
type: 'post',
dataType: 'json',
data : {action: 'register_user', nonce: nonce, formData: formData},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
}
add method="post" to your 'form' - 'get' is the default https://stackoverflow.com%2Fquestions%2F2314401%2Fwhat-is-the-default-form-http-method&usg=AOvVaw1dKc3hW4K6r5SwQurLztBw
The "user_login" is a username of the user so probably it doesn't accepts space too.
See also WP Insert Post
Please try passing some username such as "custom_user" and see the result.
Hope this might work.
Ok it was a bit of help from everyone here. But yes, I was calling the AJAX correctly, but not actually submitting the form. I added a .on(submit) to the form and then added a listener to the form to perform the AJAX call on submit. Here's the amendments below.
function nextPrev(n) {
var x = document.getElementsByClassName("form-tab");
if (n === 1 && !validateForm()) {
return false;
}
x[currentTab].style.display = "none";
currentTab = currentTab + n;
if (currentTab >= x.length) {
// ADDED THIS SUBMIT() HERE
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
// ADDED AN EVENT LISTENER TO TRIGGER THE AJAX CALL HERE
$('#regForm').on('submit', function () {
var nonce = $('#regForm').attr("data-nonce");
var formData = $('#regForm').serialize();
$.ajax({
url: rtr_register_user.ajaxUrl,
type: 'post',
dataType: 'json',
data: {
action: 'register_user',
nonce: nonce,
formData: formData
},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
});

php can't get multiple ajax submit data

I have a form and it have 2 submit button.
<form name="posting" id="posting" method="post" action="posting_bk.php" role="form">
<input type="text" name="title" id="title" class="form-control" required="required">
....some form fields...
<input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview and Post" />
<input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save as Draft" /></center>
</form>
i am using ajax to send/receive data.
$('#posting input[type="submit"]').on("click", function(e) {
e.preventDefault;
var btn = $('#publish');
var el = $(this).attr('id');
$.ajax({
type: 'post',
url: $('form#posting').attr('action'),
cache: false,
dataType: 'json',
data: {
data: $('form#posting').serialize(),
action: el
},
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
if (data.success == false) {
var arr = data.errors;
$.each(arr, function(index, value) {
if (value.length != 0) {
$("#validation-errors").append('<div class="alert alert-danger"><strong>' + value + '</strong><div>');
}
});
$("#validation-errors").show();
btn.button('reset');
} else {
$("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto Edit. <div>');
$('#title').val('');
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
btn.button('reset');
}
});
return false;
});
this is my php file. posting_bk.php
if ($_POST['action'] == 'publish') {
if($title == 'test'){
array_push($res['errors'], 'data received by php.');
}else{
array_push($res['errors'], 'No data received by php.');
}
$res['success'] = true;
echo json_encode($res);
}
elseif ($_POST['action'] == 'save') {
array_push($res['errors'], 'Save button clicked.');
$res['success'] = true;
echo json_encode($res);
}
All the time if i click on publish button i am getting
No data recived by php
When I check in firebug it is showing data under post.
Like this
action publish
data title=test&
I am not sure what am i doing wrong here. Please advise.
Change the AJAX call to use:
data: $('form#posting').serialize() + '&action=' + el,\
Then access the parameter using
$title = $_POST['title'];
The way you're doing it, the form data is being nested a level down in the POST data, so you would have had to do:
$data = parse_str($_POST['data']);
$title = $data['title'];

Cancel submit jquery

This is a part of the code from a form requesting data to check if the email alredy exist. The thing is, the program is supposed to return 0 if there is no any mail like this. It dont work properly, because the program keep sending the data, even if the mail is not correct.
If you want more info, or i am missing something let me know. Thanks in advance.
$(document).ready(function () {
$("#enviar").click(function(e) {
e.preventDefault();
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = false;
}else{
$("form").unbind('submit').submit();
}
}
});
if (error){
return false;
}
});
});
And here is my compruebaEmail.php
<?php require_once('connections/vinoteca.php'); ?>
<?php
mysql_select_db($database_vinoteca, $vinoteca);
$user = $_POST['b'];
if(!empty($user)) {
comprobar($user);
}
function comprobar($b) {
$sql = mysql_query("SELECT * FROM usuarios WHERE email = '".$b."'");
$contar = mysql_num_rows($sql);
if($contar == 0){
echo 0;
}else{
echo 1;
}
}
?>
And here goes the POST
<form method="POST" name="form1" action="validarUsu.php">
<div class="row">
<span class="center">Email</span>
</div>
<div class="row">
<input type="text" name="email" id="email2" value="" size="32" />
</div>
<div class="row">
<span class="center">Contraseña</span>
</div>
<div class="row">
<input type="password" name="password" id="id2" value="" size="32" />
</div>
<div class="row">
<span id="error"> </span>
</div>
<div class="row">
<input type="submit" value="Acceder" id="enviar" size="20">
</div>
<div class="row">
Recuperar contraseña
</div>
</form>
The problem is you're returning false from your Ajax function. You need to return false from your click function. Give this a try:
$("#enviar").click(function() {
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = true;
}
}
});
if (error)
return false;
});
If all you want is canceling the submitting event, then :
Either :
1 - Add the event arg to your click handler :
$("#enviar").click(function(event){
2 - use event.preventDefault(); when you want to cancel the submit message :)
or change the "return false;" location so that it will be triggered in the "click" handler scope and note the "success" scope e.g with a boolean that would represent if there is an error (EDIT : that is Styphon' solution)
Documentation here : http://api.jquery.com/event.preventdefault/

Displaying login error on same page when using a class (php)

I have a form to login
<div class="fade_bg">
<div class="actionDiv">
<form id="login_form" action="./classes/login/Authenticator.php" method="post">
<p>username: <input type="text" name="username" /></p>
<p>password: <input type="password" name="password" /></p>
<p>
<input type="submit" name="adminLogin" value="Log in" id="adminLogin" />
<input type="submit" name="cancelLogin" value="Cancel" id="cancelLogin" />
</p>
</form>
</div>
</div>
Notice the form action is './classes/login/Authenticator.php.' The PHP script is by itself with no HTML or anything.
What I want is for an error message to display inside
<div class="actionDiv">
If the user enters an empty form or the wrong credentials. I've tried using AJAX, but it didn't work.
The login itself works. I just need to print the errors.
Here is the AJAX I used:
$('#adminLogin').on('click', function() {
$.ajax ({
type: 'post',
url: './classes/login/Authenticator.php',
dataType: 'text',
data: $('#login_form').serialize(),
cache: false,
success: function(data) {
if(data == 'invalid credentials')
$('body').html(data);
else
$('.fade_bg').fadeOut(200);
},
error: function(msg) {
alert('Invalid username or password');
}
});
});
The form is probably getting submitted by the browser. You can prevent the default action.
$('#login_form').submit(function(e){
e.preventDefault();
//perform ajax request here.
});
Prevent the submit button from submitting the form:
$('#adminLogin').on('click', function(event) {
event.preventDefault();
...
And if you want to display the return message in the .actionDiv, then do so in your ajax success callback:
if(data == 'invalid credentials')
$('.actionDiv').append($('<p/>').text(data));
...
For client side validation you need to check before $.ajax call this condition
You have to also give id to both input fields
$(document).ready(function(){
$('#adminLogin').on('click',function() {
//alert("hello");
var name = $("#username").val();
var error = 0 ;
if(name == ""){
$("#errUsername").fadeIn().text("Username required.");
$("#username").focus();
error++;
}
var password= $("#password").val();
if(password== ""){
$("#errPassword").fadeIn().text("Password required.");
$("#password").focus();
error++;
}
if(error > 0)
{
error = 0;
$('.actionDiv').append($('<p/>').text('invalid credentials'));
return false;
}
$.ajax ({
type: 'post',
url: 'login.php',
//dataType: 'text',
data: $('#login_form').serialize(),
cache: false,
success: function(data) {
alert(data);
if(data == 'invalid credentials')
{
$('.actionDiv').append($('<p/>').text(data));
return false;
}
},
error: function(msg) {
alert('Invalid username or password');
}
});
});
});
You need to add these two <span> tags near to Username and Password inputs respectively so that client side errors can be show in these two spans
Then on Server side When you check submitted form like
<?php
$uname = isset($_POST['username']) ? $_POST['username'] : "";
$pswd = isset($_POST['password']) ? $_POST['password'] : "";
//perform query operation whether Username with valid password is exist or not
if($notExist)
echo "invalid credentials";
else
echo "success";
?>
And when $.ajax response comes then you can inform user about invalid credentials in success like
if(data == 'invalid credentials')
$('.actionDiv').append($('<p/>').html(data));

Categories