Ajax undefined value in PHP - javascript

When I call the function I always get an undefined value, I don't understand what can ruin it.
You are logged in as undefined, Error undefined
Ajax script:
function Submit() {
console.log('asd')
$.ajax({
url: "Server.php",
type: "POST",
dataType: "json",
data: {
name: "Test2",
email: "Test#gmail.com"
},
success: function(data, textStatus, jqXHR) {
console.log("You are logged in as: ", data.name);
$('#user').html("You are logged in as: " + data.name);
},
error: function(request, error, data) {
console.log(arguments);
alert(" Can't do because: " + error + " DATA: " + data);
}
})
}
PHP Script:
<?php
header("Content-type: application/json; charset=utf-8");
$errors = [];
$data = [];
if (empty($_POST['name'])) {
$errors['name'] = 'Name is required.';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email is required.';
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name'];
}
echo json_encode($data);
?>
I tried every solution in vain, so I still get an indefinite value. I’m slowly starting to think there’s nothing wrong with the script.

You want to use data.name but you never return name. hence the undefined.
I've added data.name in the example below and it seems to work fine.
<?php
header("Content-type: text/html; charset=utf-8");
$errors = [];
$data = [];
if (empty($_POST['name'])) {
$errors['name'] = 'Name is required.';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email is required.';
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name'];
}
echo json_encode($data);
?>
Also the parameters used in the succes function are in a different order than you seem to use, in your case the request will have your data in it

the callback parameter not
success:function(request, data, error)
but
success: function(data, textStatus, jqXHR)
data.name of course undefined because it is string
and your Server.php return this
{"success":true,"message":"Success!"}
no data.name but data.success and data.message
so you have to write
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name']; // add this
}

Related

Ajax with validate.js returning undefined result from php

Hello All, I have written a one demo code to check weather the given input user is exist in the list or not using ajax and validate.js, when I'm running the code all functions are executing fine but insted of getting response message in succes function it is jumping to the error function and giving undefined response as sent form php.
Here is my code:
$.validator.addMethod("checkUserExists", function(value, element){
alert("input checking");
var inputElem = $('#hl_form :input[name="username"]'),
data = { "username" : inputElem.val(),"check": "userCheck"},
eReport = ''; //error report
$.ajax(
{
type: "POST",
url: "services.php",
async: true,
dataType: 'json',
data: data,
success: function(result)
{
alert(result);
console.log(result);
if (result.status !== 'true')
{
return '<p>This User is already registered.</p>';
}else{
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
//alert('ajax loading error... ... '+url + query);
return false;
}
});
}, 'User Alread exist in the DB');
My Validate.js Rules and and Message are
Validate Method Rule
username: {
required: true,
checkUserExists:true
}
Validate.js Method Message
username: {
required: "Please enter your Username",
checkUserExists: "User... already exist"
},
My Php Code (service.php)
<?php
header('Content-Type: application/json');
class form_services{
public $sql;
public $returnResult = array();
function checkUser($requestedUser) {
$registeredUser = array('xyz', 'abc', 'def', 'ghi', 'jkl');
if( in_array($requestedUser, $registeredUser) ){
$returnResult["status"] = 'false';
}else{
$returnResult["status"] = 'true';
}
return $returnResult;
}
} //Class Ends Here
$checkRequest = $_POST['check'];
$frmServices = new form_services();
$data = '';
switch ( $checkRequest) {
case 'userCheck': $requestedUser = $_REQUEST['username'];
$data = $frmServices->checkUser( $requestedUser);
echo json_encode($data);
break;
default: echo json_encode($data);
break;
}
?>
Please help me in resolving my issue, i'm getting undefined result in ajax call from php cod.

jQuery serialized data not successfully posting to PHP form handler

I’m trying to post some data via jQuery Ajax to a PHP form handler file. It was working earlier, but I wasn’t getting errors when I should have (ie it was always sending an email), so I modified the mess out of my stuff and now the PHP file is no longer receiving the serialized data. Would greatly appreciate some eyes on this. I have a feeling it’s a stupid syntax error, but I’m not seeing it.
JS (jQuery)
$form.submit(function(e) {
e.preventDefault();
var data = $(this).serialize(),
url = $(this).attr('action');
console.log(data);
$(this).addClass('sending');
$.ajax({
url: url,
type: 'GET',
async: true,
dataType: 'json',
data: data,
success:
function(response) {
console.log("Success: " + data);
if(!response.success) {
formError(response);
} else {
// on success
console.log(`✔ Form submission successful!`);
console.log(response);
// Add success message
$form.append(
'<div class="success-message"><h3>Your Message Was Sent</h3><p>'
+
successMsg
+
'</p></div>'
).delay(10)
.queue(function(){
$(this).find('.success-message').addClass('visible');
$(this).dequeue();
});
$form
.delay(10)
.queue(function() {
$(this)
.removeClass('sending')
.addClass('sent')
.dequeue();
});
$form[0].reset();
}
},
error:
function(xhr, status, error){
console.log("Fail: " + data);
formError(xhr, status, error);
}
});
function formError(xhr, status, error) {
//on failure
console.log('✘ Form submission failed.');
console.log(xhr);
console.log(status);
console.log(error);
if (!$form.hasClass('error')) {
$form
.addClass('error')
.delay(2000)
.queue(function() {
$(this)
.removeClass('error')
.removeClass('sending')
.dequeue();
});
}
};
});
PHP Handler
<?php
$errors = '';
$myemail = '#####';//<-----Put Your email address here.
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$company = $_POST['company'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$data = array($name, $email, $phone, $company, $subject, $message);
if(
empty($name) ||
empty($email) ||
empty($phone) ||
empty($company) ||
empty($message)
) {
$errors .= "\n You must fill out required fields.";
}
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email))
{
$errors .= "\n Invalid email address.";
}
if( empty($errors) ) {
$to = $myemail;
$email_subject = "Contact Form: $name";
$email_body = "<html><body>".
"<p>Name: $name<br>".
"<p>Company: $company<br>".
"Email: $email<br>".
"Phone: $phone<br></p>".
"<p><b>Subject:</b></p>".
"<p>$subject</b></p>".
"<p><b>Message:</b></p>".
"<p>$message</p>".
"</body></html>";
$headers = "From: $myemail\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to,$email_subject,$email_body,$headers);
echo json_encode(array("success" => true, "data" => $data));
} else {
echo json_encode(array("success" => false,"error" => $errors, "data" => $data));
}
?>
The PHP handler is returning data so that I can see what's going on, and then I'm console logging it. Here's what I'm getting:
{success: false, error: "↵ You must fill out required fields.↵ Invalid email address.", data: Array(6)}
data: (6) [null, null, null, null, null, null]
error: "↵ You must fill out required fields.↵ Invalid email address."
success: false
__proto__: Object
In other words, the data isn't actually passing to the PHP file. I'm assuming I have some stupid syntax error, but I'm not seeing it. Help! 🙏🏼
You send GET data in Ajax and you try to get POST in your PHP.
Change type to POST in your Ajax function.
$form.submit(function(e) {
e.preventDefault();
var data = $(this).serialize(),
url = $(this).attr('action');
console.log(data);
$(this).addClass('sending');
$.ajax({
url: url,
type: 'POST',
async: true,
dataType: 'json',
data: data,
success:
function(response) {
console.log("Success: " + data);
if(!response.success) {
formError(response);
} else {
// on success
console.log(`✔ Form submission successful!`);
console.log(response);
// Add success message
$form.append(
'<div class="success-message"><h3>Your Message Was Sent</h3><p>'
+
successMsg
+
'</p></div>'
).delay(10)
.queue(function(){
$(this).find('.success-message').addClass('visible');
$(this).dequeue();
});
$form
.delay(10)
.queue(function() {
$(this)
.removeClass('sending')
.addClass('sent')
.dequeue();
});
$form[0].reset();
}
},
error:
function(xhr, status, error){
console.log("Fail: " + data);
formError(xhr, status, error);
}
});
function formError(xhr, status, error) {
//on failure
console.log('✘ Form submission failed.');
console.log(xhr);
console.log(status);
console.log(error);
if (!$form.hasClass('error')) {
$form
.addClass('error')
.delay(2000)
.queue(function() {
$(this)
.removeClass('error')
.removeClass('sending')
.dequeue();
});
}
};
});

If and else condition inside success in ajax

As the title says I want to run the if and else inside the success condition in Ajax, For example after running the Ajax and sees that there is a record it will go to success then inside the success it must look for the "if statement" and display the alert inside the "if statement" if the statement is true but instead it always display the "else statement" with the alert('no') inside of it, even if there is a record, Thank you
<script>
function renderAttendees(id)
{
///$("#attendeesContent").empty();
var dataString = { "id": id };
$.ajax({
type: 'POST',
url: server+'webservice/crm/viewAttendeesDetails',
data: dataString,
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
cache: true,
success: function(data)
{
if($.trim(data) === 'error')
{
alert('yes');
}
else
{
alert('no');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error connecting to server. " + XMLHttpRequest + ", " + textStatus +", "+ errorThrown);
}
</script>
//My Controller Code
public function viewAttendeesDetails()
{
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
$data = array();
$id = $_POST['id'];
$AttendeesDetails = $this->model->GetAttendeesDetail($id);
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
}
echo json_encode($data);
exit;
}
?>
//My Model Code
db->prepare("SELECT * FROM crm_contact_list WHERE id = :AttendId");
$stmt->bindParam(":AttendId", $id);
$stmt->execute();
return $stmt;
}
catch (Exception $e)
{
return $e->getMessage();
return $stmt;
}
return;
}
?>
//Here is the result of console.log(data);
Object
email:"kyle#localhost.com"
full_name:"Test kim"
id:"1"
interest:"Test"
number:"123456"
position:"Prog"
venueID:"1"
I would return from your controller something like
{status: 'success', data: myArrayWithFoundData}
so when you receive the ajax response you could do a json_decode, and check the status.
So in you controller you would have
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
$rsp_data = {status: 'success', data: $data};
}else{
$rsp_data = {status: 'error', data: null};
}
echo json_encode($resp_data);
Something like that, so in the ajax response you would do a
var a = JSON.parse(data);
and check the a.status for error

jQuery ajax call not triggering success function on Safari 9.1

In a project I have a particular ajax call that works fine on PC Chrome/Firefox, but on Safari 9.1 it fails to trigger the success function.
The ajax call:
$('#new_file_form').submit(function(e) {
e.preventDefault();
var form_data = new FormData($(this)[0]);
$.ajax({
url: '/includes/ajax/file-manager.php',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
success: function(result) {
JSON.parse(result);
alert(result);
if (result == true) {
$('#new_file_form').reset;
$('#new_file_modal').modal('hide');
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-info-sign blue"></i>File successfully saved.',
callback: function() {
location.reload();
}
});
} else if (result == false) {
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-exclamation-sign orange"></i>File not saved.',
callback: function() {
location.reload();
}
});
} else {
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-exclamation-sign orange"></i>Whoa! That escalated quickly..',
callback: function() {
location.reload();
}
});
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
This doesn't throw any errors. The file is uploaded and the data inserted into the database, it's just the success function that sits there and seems to be laughing at me.
Based on the returned error in Safari it seems useful to post the file-manager.php code:
if(!empty($_POST['file_name']) && !empty($_POST['file_type']) && !empty($_POST['file_user'])) { // && !empty($_FILES['file'])
$ownerid = $mysqli->real_escape_string($_POST['file_user']);
$ownertype = 1;
$name = $mysqli->real_escape_string($_POST['file_name']);
$visible = $mysqli->real_escape_string($_POST['visible']);
$filetype = $mysqli->real_escape_string($_POST['file_type']);
$ownerid = filter_var($ownerid, FILTER_SANITIZE_NUMBER_INT);
$visible = filter_var($visible, FILTER_SANITIZE_NUMBER_INT);
$filetype = filter_var($filetype, FILTER_SANITIZE_NUMBER_INT);
$cdate = date('Y-m-d H:i:s');
$edate = $cdate;
$u_file_name = $_FILES['file']['name'];
$u_tmp_file = $_FILES['file']['tmp_name'];
$u_file_type = $_FILES['file']['type'];
$u_file_error = $_FILES['file']['error'];
$u_file_content = file_get_contents($_FILES['file']['tmp_name']);
$upload_result = '';
if($u_file_error == 'UPLOAD_ERROR_OK') {
if($u_file_name == '') {
$upload_result = false;
} else {
$sql = "SELECT path FROM filetypes WHERE id = '$filetype'";
$result = $mysqli->query($sql);
$record = $result->fetch_object();
$file_type_path = $record->path;
$extension = end(explode(".", $u_file_name));
if($ownertype == 1) {
$s_file_name = preg_replace("![^a-z0-9]+!i", "-", $name).'-'.date('Y-m-d_H-i').'.'.$extension;
$s_file_dest = LOCAL_BASE_PATH.'/uploads/'.$ownerid.'/'.$file_type_path;
$s_file_location = $s_file_dest.'/'.$s_file_name;
$s_file_path = '/uploads/'.$ownerid.'/'.$file_type_path.$s_file_name;
}
if(!file_exists($s_file_dest)) {
mkdir($s_file_dest, 0755, true);
}
move_uploaded_file($u_tmp_file, $s_file_location);
$sql = "INSERT INTO files (ownertype, owner, type, visible, extension, name, path, cdate, edate) VALUES ('$ownertype', '$ownerid', '$filetype', '$visible', '$extension', '$s_file_name', '$s_file_path', '$cdate', '$edate')";
$result = $mysqli->query($sql);
$upload_result = true;
}
}
echo json_encode($upload_result);
exit();
}
When I alert the ajax result before parsing it, I get a PHP error:
Strict Standards: Only variables should be passed by reference...

Ajax 200 Success/failed execution

I have an issue with ajax and I am kinda new at this. The issue that I am having is even if log in fails ajax is still running the success block of code. How do I direct the code to return a failed status.
I'm not asking for you to inspect my code just more as a reference. I just need to know how to tell my code to send anything other than a 200 for okay so that I can display the errors on the screen.
I type in false information and the ajax thinks that the login happened but it really didn't.
AJAX Section
jQuery(document).ready(function(){
document.body.style.paddingTop="3px";
$('a[href^="#fallr-"]').click(function(){
var id = $(this).attr('href').substring(7);
methods[id].apply(this,[this]);
return false;
});
var methods = {
login : function(){
var login = function(){
var username = $(this).children('form').children('input[type="text"]').val();
var password = $(this).children('form').children('input[type="password"]').val();
var remember = $(this).children('form').children('input[name="remember"]').val();
var token = $(this).children('form').children('input[name="token"]').val();
if(username.length < 1 || password.length < 1 || token.length < 1){
alert('Invalid!\nPlease fill all required forms');
console.log(token)
} else {
var data = {
username: username,
password: password,
remember: remember,
token: token,
}
$.ajax({
type: "POST",
url: "login.php",
data: data,
dataType: "text",
success: function(data){
$('#error').append('Success');
// $.fallr.hide();
// window.location.href = "http://www.bettergamerzunited.com/members/";
},
error: function(data) {
$('#error').append('falied');
}
});
}
}
$.fallr.show({
icon : 'secure',
width : '400px',
content : '<h4 class="titles">Login</h4>'
+ '<span id="error"></span>'
+ '<form>'
+ '<input placeholder="Username" name="username" type="text"/'+'>'
+ '<input placeholder="Password" name="password" type="password"/'+'>'
+ '<input type="checkbox" name="remember" type="remember"/'+'> Remember Me'
+ '<?php echo $hidden; ?>'
+ '</form>',
buttons : {
button1 : {text: 'Submit', onclick: login},
button4 : {text: 'Cancel'}
}
});
}
};
});
Login Section
require 'core/init.php';
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = New Validate ();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
if ($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
$response = $login;
echo $response; // <-- Im going to have an if statement that determines if $login was true or false. But testing still.
} else {
foreach ($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
This is the class that handles the login.
public function login($username = null, $password = null, $remember = false) {
if(!$username && !$password && $this->exists()) {
Session::put($this->_sessionName, $this->data()->id);
} else {
$user = $this->find($username);
if($user) {
if($this->data()->password === Hash::make($password, $this->data()->salt)) {
Session::put($this->_sessionName, $this->data()->id);
if($remember) {
$hash = Hash::unique();
$hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));
if(!$hashCheck->count()) {
$this->_db->insert('users_session', array(
'user_id' => $this->data()->id,
'hash' => $hash
));
} else {
$hash = $hashCheck->first()->hash;
}
Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
}
return true;
} else {
try{
throw new Exception('The Username or Password combination doesn\'t match. \n Please try again.');
} catch(Exception $e) {
echo $e->getMessage();
}
}
} else {
try{
throw new Exception('The Username you provide does not match anything in our system. Please Try again or Register.');
} catch(Exception $e) {
echo $e->getMessage();
}
}
}
return false;
}
You can add below code for ajax error section ..in this way you will get idea of what's exactly is error and can debug it.
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
}
Use the PHP header function.
header('HTTP/1.0 403 Forbidden'); // or whatever status code you want to return.
There can be nothing else outputted before using the header function.

Categories

Resources