How come Ajax response is different? - javascript

I can't find the reason why my ajax response is different when I console.log the response. Any ideas?
Page1 is used in account update form while page2 is used in registration form.
page1.js:
function ajaxCheckDupEmail(){
if(valid_email === true){
return $.ajax({
type:'POST',
url:'ajax/page1.php',
data:{ 'email': email, 'email_login': email_login },
success:function(response){
//some code
}
});
}else{
//other code
}
}
$.when(ajaxCheckDupEmail()).done(function(a1){
console.log(a1);
if(a1[0] === 'false'){
//submitting form
//some code
}
});
NOTE: email and email_login is a js var where I store userinput in, I used valid_email to check if email is valid
page1.php:
if(isset($_POST["email"]) && !empty($_POST["email"])){
$email = trim_strip_data($_POST["email"]);
$email_login = trim_strip_data($_POST["email_login"]);
$prep_data_email = $db->prepare("SELECT email FROM user WHERE email = :email");
$prep_data_email->execute(array(":email" => $email));
$row_count = $prep_data_email->rowCount();
if($row_count === 1 && $email !== $email_login){
echo "true";
}else{
echo "false";
}
}
NOTE: trim_strip_data() is a custom function to trim white spaces although I don't think it is necessary in this case
page2.js:
function ajaxCheckDupEmail(){
if(valid_email === true){
return $.ajax({
type:'POST',
url:'ajax/page2.php',
data:{ 'email': email },
success:function(response){
// some code
}
});
}else{
//other code
}
}
function ajaxCheckDupUsername(){
if(username !== ""){
return $.ajax({
type:'POST',
url:'ajax/page2.php',
data:{ 'username': username },
success:function(response){
// some code
}
});
}else{
//other code
}
}
$.when(ajaxCheckDupUsername(), ajaxCheckDupEmail()).done(function(a1, a2){
console.log(a1);
console.log(a2);
if(a1[0] === 'false' && a2[0] === 'false'){
//submitting form
//some code
}
});
NOTE: email is a js var where I store userinput in, I used valid_email to check if email is valid
page2.php:
if(isset($_POST["email"]) && !empty($_POST["email"])){
$email = trim_strip_data($_POST["email"]);
$prep_data_email = $db->prepare("SELECT email FROM user WHERE email = :email");
$prep_data_email->execute(array(":email" => $email));
$row_count = $prep_data_email->rowCount();
if($row_count === 1){
echo "true";
}else{
echo "false";
}
}
if(isset($_POST["username"]) && !empty($_POST["username"])){
$username = trim_strip_data($_POST["username"]);
$prep_data_username = $db->prepare("SELECT username FROM users WHERE username = :username");
$prep_data_username->execute(array(":username" => $username));
$row_count = $prep_data_username->rowCount();
if($row_count === 1){
echo "true";
}else{
echo "false";
}
}
NOTE: trim_strip_data() is a custom function to trim white spaces although I don't think it is necessary in this case
The problem is I get 2 different response results (depending on result true/false).
In page1.js I get:
true
In page2.js I get:
true,success,[object Object]
true,success,[object Object]
It looks like I get an response object in page2.js but why I don't get one in page1.js?

https://api.jquery.com/jquery.when/#jQuery-when-deferreds
You are dealing with promises, and a promise always returns a promise.
So I would double check page1 isn't returning the object too.
E.g. open dev tools and run the following;
$.when().done(function( x ) { alert('done')});
you will see it returns an object, this is the promise.
but for
true,success,[object Object]
I don't see where success is coming from, are you missing some code?
On a side note...
if(valid_email === true)
is the same as
if(valid_email)
sorry, it was just bugging me.

Related

Jquery AJAX POST is returning ERROR 500 - Google Text to Speech Module

I have a text to speech module made using google's API, However, it used to work fine (converting user-entered text to speech). But since yesterday I come across this error at Jquery Ajax POST showing error 500 in the console.
The Code goes as :
Index Page code:
//On click of speak button after adding text in input fields
$('#speak').click(function (e) {
let _speakBtn = $(this);
// prevent double click
if (_speakBtn.attr('disabled')){
return false;
}
_speakBtn.attr('disabled','disabled');
// validate is content not empty
if ($("#content").val().length < 1 || $.trim($("#content").val()) === ''){
$("#content").addClass('is-invalid');
_speakBtn.prop('disabled',false);
return false;
}else{
$("#content").removeClass('is-invalid');
}
// validate is language not empty
if ($("#language").val().length !== 5 || $.trim($("#language").val()) === ''){
$("#language").addClass('is-invalid');
_speakBtn.prop('disabled',false);
return false;
}else{
$("#language").removeClass('is-invalid');
}
// validate is voice quality not empty
if (($("#voice_quality").val() !== 'WaveNet' && $("#voice_quality").val() !== 'Standard') || $.trim($("#voice_quality").val()) === ''){
$("#voice_quality").addClass('is-invalid');
_speakBtn.prop('disabled',false);
return false;
}else{
$("#voice_quality").removeClass('is-invalid');
}
// validate is gender not empty
if (($("#gender").val() !== 'Female' && $("#gender").val() !== 'Male') || $.trim($("#gender").val()) === ''){
$("#gender").addClass('is-invalid');
_speakBtn.prop('disabled',false);
return false;
}else{
$("#gender").removeClass('is-invalid');
}
// validate is artist not empty
if ($("#artist_name").val().length < 2 || $.trim($("#artist_name").val()) === ''){
$("#artist_name").addClass('is-invalid');
_speakBtn.prop('disabled',false);
return false;
}else{
$("#artist_name").removeClass('is-invalid');
}
$.post('<?= rtrim(TTS_APP_BASE_URL,'/') ?>/ajax.php', $('.ajax_post').serialize(), function (_response) {
try {
_response = JSON.parse(_response);
if (_response.success){
//download audio _response.data.link
$('#downloadBtn').attr('data-toggle', 'modal');
$('#downloadForm').attr('action', _response.data.down_link);
//play audio
$('#rk_player').prop('hidden', false);
$('#rk_player #rk_source').attr('src', _response.data.play_link);
$('#rk_player').get(0).load();
$('#rk_player').get(0).play();
}else{
alert(_response.message);
}
}catch (e) {
console.error(e);
}
_speakBtn.prop('disabled',false);
});
});
In the above form the error occured at $.post('<?= rtrim(TTS_APP_BASE_URL,'/') ?>/ajax.php', $('.ajax_post').serialize(), function (_response) { line as the data is not being posted to ajax.php
The Ajax.PHP code :
/*
if($_SERVER['REQUEST_METHOD'] !== 'POST'){
http_response_code(404);
die();
}
*/
define('HAS_ACCESS', TRUE);
require_once 'tts_app.php';
tts_app.php code goes as:
//disable direct access to this file
defined('HAS_ACCESS') or die('silence is golden');
require 'partials/bootstrap.php';
use Classes\HandleResponseClass;
use Google\Cloud\TextToSpeech\V1\AudioConfig;
use Google\Cloud\TextToSpeech\V1\AudioEncoding;
use Google\Cloud\TextToSpeech\V1\SynthesisInput;
use Google\Cloud\TextToSpeech\V1\TextToSpeechClient;
use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams;
// Authenticating with keyfile data.
/*echo "<br>";
print_r( $_ENV);
exit();*/
require_once 'config.php';
$text = trim($_POST['text']);
$language_code = trim($_POST['language']);
$voiceList = TTS_APP_VOICES_LIST;
$selectLanguage = isset($voiceList[$language_code]) ? $voiceList[$language_code]:'';
$artisteName = trim($_POST['artist_name']);
$gender = trim($_POST['gender']);
if(empty($_POST['rate'])) {
$rate = 1;
} else {
$rate = $_POST['rate'];
}
if(empty($_POST['pitch'])) {
$pitch = 1;
} else {
$pitch = $_POST['pitch'];
}
$voice_quality = $_POST['voice_quality'];
$u_id = $_POST['u_id'];
// validate request
if (empty($text) || empty($selectLanguage) || empty($voice_quality) || empty($gender) || empty($artisteName) || empty($rate) || empty($pitch)){
$response['success'] = false;
$response['message'] = 'Required fields are empty';
$response['data'] = [];
echo json_encode($response);
exit();
}
$textToSpeechClient = new TextToSpeechClient();
$input = new SynthesisInput();
$input->setText($text);
$voice = new VoiceSelectionParams();
$voice->setLanguageCode($language_code);
if (!empty($artisteName)){
$voice->setName($artisteName);
}
if (!empty($gender)){
$voice->setSsmlGender($gender == 'Female' ? 2:1);
}
$audioConfig = new AudioConfig();
if (!empty($rate)){
$audioConfig->setSpeakingRate($rate);
}
if (!empty($pitch)){
$audioConfig->setPitch($pitch);
}
$audioConfig->setAudioEncoding($voice_quality == 'WaveNet' ? AudioEncoding::OGG_OPUS:AudioEncoding::MP3);
$resp = $textToSpeechClient->synthesizeSpeech($input, $voice, $audioConfig);
// handle response file
$responseClass = new HandleResponseClass($resp);
$responseClass->saveFiles(TTS_APP_BASE_PATH);
/*=-=-= sending response -=-=-*/
$response = [
'success' => false,
'message' => 'something went wrong, please check your internet connection and try again later',
'data' => [],
];
if($responseClass->fileSaved()) {
$response['success'] = true;
$response['message'] = '';
$response['data'] = [
'down_link' => rtrim(TTS_APP_BASE_URL,'/').'/download.php?file='.urlencode($responseClass->getFileName()),
'play_link' => rtrim(TTS_APP_BASE_URL,'/').'/'.$responseClass->getDirName().'/'.$responseClass->getFileName().'.mp3',
];
echo json_encode($response);
exit();
}
echo json_encode($response);
exit();
The error I m getting :
jquery-3.5.1.min.js:2 POST https://vdofy.com/tts-test/ajax.php 500
send # jquery-3.5.1.min.js:2
ajax # jquery-3.5.1.min.js:2
S.<computed> # jquery-3.5.1.min.js:2
(anonymous) # index?content_get= Test to speech tesing:1496
dispatch # jquery-3.5.1.min.js:2
v.handle # jquery-3.5.1.min.js:2
Not sure why am I getting this error as I have not changed anything since it was working fine.
Please share your thoughts on what could have gone wrong.
Response code 500 is a server side error, So check for errors in your server side PHP code, check error logs or turn on php error reporting to find what is causing the error.

Error on Ajax javascript

When I click on the button the data are sent, no problem with that but I don't see the success message and when I look the console, it write this error.
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data mailchimp_v3.js:100:16
The error is in relation with this line on the javascript
data = jQuery.parseJSON(response);
How to resolve this error and to have the message success.
Thank you.
the form to send information
<?php echo HTML::form('mailchimp', OSCOM::link('ext/api/mailchimp_v3/subscribe.php'), 'post', 'novalidate data-mailchimp="' . $mailchimp_list_anonymous . '" data-redirect="'. OSCOM::link('index.php') .'"'); ?>
<div class="col-md-12">
<?php echo HTML::inputField('email', '', 'required id="email" placeholder="' . OSCOM::getDef('entry_email_address') . '" email data-validation-email-message="' . OSCOM::getDef('enter_valid_email_address') . '" required data-validation-required-message="' . OSCOM::getDef('enter_email_address') . '""', 'email'); ?>
</div>
<div class="col-md-12">
<?php echo HTML::button(OSCOM::getDef('button_submit'), 'fa fa-send', null, 'info',null,null); ?>
</div>
<?php
echo '</form>';
?>
the script
$(document).ready(function(){
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
function validateField(element,name,value){
var required = element.attr('required');
var email = element.attr('email');
if(typeof required !== typeof undefined && required !== false){
if(value.length == 0){
element.addClass('error');
element.after('<span class="field-error">' + element.attr('data-validation-required-message') + '</span>')
return false;
}
}
if(typeof email !== typeof undefined && email !== false){
if(!re.test(value)){
valid = false;
element.addClass('error');
element.after('<span class="field-error">' + element.attr('data-validation-email-message') + '</span>')
return false;
}
}
return true;
}
$('form[data-mailchimp]').each(function(){
var form = $(this);
var list = form.attr('data-mailchimp');
var url = form.attr('action');
var redirect = form.attr('data-redirect');
function success(){
if(typeof redirect !== typeof undefined && redirect !== false){
window.location = redirect;
}
}
if(!list) return;
form.submit(function(e) {
e.preventDefault();
//Reset errors and such
form.removeClass('loading');
form.find('.field-error').remove();
form.find('.form-error').html('');
var fields = form.serializeArray();
var data = {
list : list,
email : "",
timestamp_signup : (new Date).getTime(),
merge_fields : {},
interests : {}
}
//Validate all of the fields
for(var i = 0; i < fields.length; i++){
var field = fields[i];
if(!validateField(form.find('[name='+field.name+']'),field.name,field.value)) return;
if(field.name.indexOf('email') > -1){
data.email = field.value;
}
}
//All good
form.addClass('loading');
if(data.email == ""){
form.find('.form-error').html('Please provide a valid email address.');
return;
}
$.post(url, data, function(response) {
data = jQuery.parseJSON(response);
form.removeClass('loading');
//Member already exists
if(data.status != null && data.status == 400 && data.title == "Member Exists"){
form.addClass('success');
success();
console.log('member exists already');
}
else if(data.id && data.id.length > 0){
form.addClass('success');
success();
console.log('member added');
}
else{
form.find('.form-error').html('There was an error submitting the form.');
}
});
});
});
});
More information
<anonyme> http://...../mailchimp_v3.js:100:16
r.Callbacks/i https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:27978
r.Callbacks/j.fireWith https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:28749
A https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:4:14201
.send/c/< https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:4:16491
Foolow to comment data = response; seems correct, and I have no error, but I don't see the message : success
It could be either of the 2 things.
Not a valid JSON (maybe invalid JSON string)
Your response is already a JSON, and you are trying to parse it again.
Get rid of data = jQuery.parseJSON(response); and try using the response as is.
Simplest thing to do is to console.log(response) to see what the response is.

Return value from php to javascript

I writing a registration/login form, I am sending user info via POST to a PHP that is looking in a DB. I would like that the PHP returns an ok or wrong value to the js and I don't now how to do it.
Here my js:
ui.onClick_regsubmit=function()
{
var fname=document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var affiliation=document.getElementById('affiliation').value;
var data = new FormData();
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
data.append("fname",fname);
data.append("lname",lname);
data.append("password",password);
data.append("mail",mail);
data.append("affiliation",affiliation);
xhr.open( 'post', 'PHP/registration.php', false );
xhr.send(data);
window.alert(affiliation);
}
And the php:
<?php
mysql_connect('localhost','root','') or die('Cannot connect mysql server');
mysql_select_db('ChemAlive_login') or die('cannot connect database');
$lname=$_POST['lname'];
$fname=$_POST['fname'];
$password=$_POST['password'];
$mail=$_POST['mail'];
$affiliation=$_POST['affiliation'];
$q=mysql_query("select * from login where mail='".$mail."' ") or die(mysql_error());
$n=mysql_fetch_row($q);
if($n>0)
{
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password) echo "ok";
else echo "wrong";
}
else
{ $insert=mysql_query("insert into login values('".$fname."','".$lname."','".$mail."','".$password."','".$affiliation."')") or die(mysql_error());}
?>
I would like to return to js this ok or wrong value. How to do it?
xhr.onload=function()
{
if (xhr.status==200)
{
alert(xhr.response);
}else
{
alert("unknown server error");
}
}
it will be better if the server sends a response code, and javascript will transfer this code to the text. For example:
onload=function()
{
switch(xhr.response)
{
case "0":{alert("unknown error")};break;
case "1":{alert("email is already used")};break;
...
}
}
I think thought it is clear
I do not have the rep to comment or I'd ask for details, but if you can consider using ajax, it could look something like this:
php:
$doit = //your query;
if($doit){
$youdid = 'ok';
}
else{
exit('1');
}
js:
$(document).ready(function () {
var foo = $("#formfield")val();
$.ajax({
"foo":foo;
type: 'POST',
url: 'some.php',
success: function(responseText) {
if(responseText == "1") {
alert("Leave instantly");
};
}
else {
alert("One of us");
}
If you want to return either ok or wrong to the JavaScript to handle you could do something like this in your registration.php page:
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password){
header('Content-Type: application/json');
echo json_encode(array('password' => 'ok'));
}else{
header('Content-Type: application/json');
echo json_encode(array('password' => 'wrong'));
}
I have not fully testing this, but the idea is to set the header to return json and then send it a JSON string.
Does that make sense?
Like I said in my comment below I have only used jQuery for AJAX. But here is a little something of what I know about XMLHttpRequest and my undertsanding of how you would test what you get back.
You can set up a listener for when you get a response back onreadystatechange and then put the response in a variable var pass = xhr.response and then just output the text to an alert box like alert(pass.password).
if (xhr.onreadystatechange === 4 && xhr.status === 200){
var pass = xhr.response;
//should output either ok or wrong
alert(pass.password);
}
Read more about XMLHttpRequest here
Let me know if that works.

Chech Username(Email) Availability with LiveValidation.Custom Function

I have a problem with checking for e-mail availability with the custom function of LiveValidation: it keeps sending back that the e-mail is already in use even if it isn't.
Can someone please help me out of this ?
-- EDIT--
I figured out that the function check_availability can't return the true or false from the Ajax call. So I'm almost there I just need to make the function return the right bool value.
This is my code until now:
JS File:
//function to check username availability
var check_availability = function(){
//get the username
var email = $('#email').val();
//use ajax to run the check
$.post("checkEmail.php", { email: email },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
return true;
}else{
//show that the username is NOT available
return false;
}
});
// Validation
var mail = new LiveValidation('email', { validMessage: "Ok!" });
mail.add( Validate.Custom,{failureMessage:"E-mail is al in gebruik!",
against: function(){ return check_availability() }
});
checkEmail.php file:
<?php
require_once 'db_config.php';
//Controleren of e-mail adress al in gebruik is
$sql_select_email = "SELECT email from tblUsers WHERE email = '".mysql_real_escape_string($_POST['email'])."'";
if (($result_select_email = mysql_query($sql_select_email)) === false)
{
# als de query fout is -> foutafhandeling
echo showSQLError($sql_select_email,mysql_error(),'Fout bij het opvragen van de gegevens.');
}
else
{
//Query gelukt
$count_email = mysql_num_rows($result_select_email);
if($count_email > 0)
{
// Not available
echo 0;
}
else
{
// Available
echo 1;
}
}
?>
Try this..
//function to check username availability
check_availability = function(){
//get the username
var email = $('#email').val();
//declare the return value for the $.post call
var return_value = null;
// make the $.post call synchronous !!important
$.ajaxSetup({async: false});
//use ajax to run the check
$.post("checkEmail.php", { email: email },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
return_value = true;
}else{
//show that the username is NOT available
return_value = false;
}
});
// return the result (true or false)
return return_value;
// Validation
var mail = new LiveValidation('email', { validMessage: "Ok!" });
mail.add( Validate.Custom,{failureMessage:"E-mail is al in gebruik!",
against: function(){ return check_availability() }
});
This should work. I tested it. sort of... ha!
The problem was that you cannot return a value from within the scope of the $.post call. You must first declare the return variable outside the scope of the $.post call. Then you can assign the value of that variable from within the $.post. But also the $.post call must be set to "synchronous". ie - $.ajaxSetup({async: false});
If I'm not mistaken, ajax result would be a string. result == "1" not result == 1.
You could also do result == parseFloat(result)

Trouble using jQuery post inside non jQuery function

I have the following script inside a HTML page:
<script>
function Test(){
alert("i got here");
var username = document.registration_form.username.value;
alert(username);
$.post("checkname.php", { name: username }, function(data) {
alert("and here");
alert(data);
if (data = "0"){
alert('That username is already in use, please choose another');
return false;
};
if (data = "1") {
return true;
};
});
};
</script>
I'm trying to get the function test to return true or false if a username is already in my database.
checkname.php contains the following:
<?
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_POST['name'];
$sql="SELECT * FROM members WHERE username='".$myusername."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count >= 1){
echo "0";
}
else {
echo "1";
}
?>
I've tried hardcoding a name and running the PHP and it works fine.
For some reason though when I run Test() the first 2 alerts come through fine, showing me the username enetered, but none of the subsequent alerts appear.
Oooo and jQuery has been added in the header like so:
<script src="create/js/jquery-1.4.4.min.js" type="text/javascript" ></script>
<script src="create/js/jquery-ui-1.8.7.custom.min.js" type="text/javascript"></script>
Any help much appreciated :)
First of all, your return statements from the callback to $.post will not return from your Test() function. You should call Test with a callback function that deals with the data from the server, something like this:
function Test(username, callback) {
$.post("checkname.php", {name: username}, callback);
}
Test(document.registration_form.username.value, function(data) {
if(data == "0") {
// Do something
} else {
// Do something else
}
});
Brad is also correct about the comparison - you're currently assigning "0" to data. You should get the alerts though, I think, even with the other errors. Maybe you need the absolute path to the checkname.php script? E.g. "/checkname.php" (note the slash)?
Off-hand, you should be using == for comparison in javascript. A single = is an assignment, == is a comparison. So having said that, if (data = "0"){ would become if (data == "0"){.
Other than that, I don't see anything too fishy. You're allowed to use jQuery functions within "traditional" javascript function(){}'s.
Also, make sure you sanitize the input from the $_POST['name'] using something like mysql_real_escape_string.
The problem may be that the PHP script is returning a new line before or after it prints 0 or 1. So the string returned wouldn't equal "0" or "1".
Try to change it to output JSON instead.
if($count >= 1){
$ret = 0;
}
else{
$ret = 1;
}
echo json_encode(array('status' => $ret));
And then change your $.post to:
$.post("checkname.php", { name: username }, function(data) {
alert("and here");
alert(data);
if(data.status = 0){
alert('That username is already in use, please choose another');
}
if(data.status = 1) {
alert('That username is not already in use');
}
}, 'json');
NOTE: The return false and return true don't do anything. You cannot return from an AJAX call.

Categories