Error on Ajax javascript - 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.

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.

special character % is transmitted to % at server side through jquery AJAX call: Updated

I have a HTML form as the output of a java that gets a text from database and fill an input of that form with it. In form I can edit the text that on submit
Is sent back to java via a jquery AJAX call. Through java the text is saved in the database.
If I enter test% in text area it is coming as test% at server side.
Let’s say the HTML form looks like this :
<form id="form_used_0" action="#" method="post" onclick="hideAjaxList();">
<textarea name="summary" id=" summary " data-mini="true"><%=HtmlWriter.preformat(summary)%></textarea>
<a id="saveBtn" class="actionBtn" href="#" data-theme="b" onclick="onSave (this);">Save</a>
</form>
On saveBtn click this AJAX call is made:
function onSave(thisHref)
{
var respData = "";
var id = $("#id").attr("value");
var params = $("#form_used").serialize()+"&ajaxAction=SaveHeader"+"&id="+id;
$.post(ajaxURL, params, function(data){
if(data.length >0)
{
respData = data.substring(data.indexOf("|")+1, data.lastIndexOf("|"));
}
}).complete(function(){
if (respData.length > 0)
{
var responseData = respData.split("|");
var status = responseData[0];
var msg = responseData[1];
if (status == 'SUCCESS')
{
showSuccessMsgHeader(msg);
}
else if (status == 'ERROR')
{
showErrorMsgsOnly(msg);
}
}
});
}
I tried using the serializeArray method but now getting 400 Bad request error. I checked the form data in network tab and found that it is showing as unable to decode value beside input field .
function onSave(thisHref)
{
var respData = "";
var id = $("#id").attr("value");
var x = $("#form_used_0").serializeArray();
var paramsArr = "";
$.each(x, function(i, field){
if(i == x.length - 1){
paramsArr = paramsArr + field.name + "=" + field.value;
} else {
paramsArr = paramsArr + field.name + "=" + field.value + "&";
}
});
var params paramsArr +"&ajaxAction=SaveHeader"+"&id="+id;
$.post(ajaxURL, params, function(data){
if(data.length >0)
{
respData = data.substring(data.indexOf("|")+1, data.lastIndexOf("|"));
}
}).complete(function(){
if (respData.length > 0)
{
var responseData = respData.split("|");
var status = responseData[0];
var msg = responseData[1];
if (status == 'SUCCESS')
{
showSuccessMsgHeader(msg);
}
else if (status == 'ERROR')
{
showErrorMsgsOnly(msg);
}
}
});
}
Would it be possible for anyone to help me on the same.
As per jQuery documentation, The .serialize() method creates a text string in standard URL-encoded notation.
You can use Apache Commons StringEscapeUtils.unescapeHtml() to decode the string at server level.
Alternatively, if required you can pass the text from textarea as an additional param, which you can use it.
Thanks.

How come Ajax response is different?

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.

Do I need a captcha for my contact form (to stop spam) if the message is only sent when a user token is validated?

I am building an app for a company with javascript, html and php.(packaged up with phonegap)
The app is only for paying subscribers of the company and the user will only gain access to the app after login details
are validated.
Once login details are validated (on the server side), a JWT token is generated with the user's ID (using the JWT.class.php)
include_once '../includes/JWT.class.php';
$token = array();
$token['userID'] = $loginDetails['userID'];
$data['usertoken'] = JWT::encode($token, 'secret_server_key');
This token is then sent back to client side and stored in local storage.
On every subsequent http request (with ajax) the token is sent to the server side and validated before any
processes are carried out.
I was about to add a captcha to a contact form I have in the app, however now I am wondering if it is necessary?
When the form is submitted all fields are validated first.
If fields are valid then they are sent to story_form_handler.php.
Here is my javascript function called when the form is submitted.
function submitContactForm(e){
e.preventDefault();
var story_subject = $('#contact_input3').val();
var story_message = $('#contact_input4').val();
var contact_email_address = $("#contact_input1").val();
var contact_full_name = $("#contact_input0").val();
var contact_phone = $("#contact_input2").val();
var subjectIsValid = validateInput(story_subject, subjectRegex);
var messageIsValid = validateInput(story_message, messageRegex);
var emailIsValid = validateInput(contact_email_address, emailRegex);
var fullNameIsValid = validateInput(contact_full_name, displayNameRegex);
var phoneNumberIsValid = validateInput(contact_phone, phoneNumberRegex);
if((story_subject == "" || story_subject == null) ||
(story_message == "" || story_message == null) ||
(contact_email_address == "" || ccontact_email_address == null) ||
(contact_full_name == "" || contact_full_name == null)){
//display error
}else if((!subjectIsValid) || (!emailIsValid) || (!phoneNumberIsValid) || (!messageIsValid) || (!fullNameIsValid)){
if(!subjectIsValid){
//display error
}else if(!phoneNumberIsValid){
//display error
}else if(!emailIsValid){
//display error
}else if(!fullNameIsValid){
//display error
}else if(!messageIsValid){
//display error
}
}else{
var token = localStorage.getItem("usertoken");
var params = {'usertoken': token, 'story_subject': story_subject, 'story_message':story_message, 'contact_full_name':contact_full_name, 'contact_email_address':contact_email_address, 'contact_phone':contact_phone};
$.ajax({
url: app_root_url + 'story_form_handler.php',
data: JSON.stringify(params),
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
success: function(data){
var result = data;
var token_is_valid = result.token_is_valid;
console.log("token_is_valid" + token_is_valid);
},
error: function(xhr, status, error) {
//error
}
});
}
}
story_form_handler.php
include_once '../includes/JWT.class.php';
$rawPostData = file_get_contents('php://input');
$json = json_decode($rawPostData);
if(isset($json->usertoken)){
try{
$token = JWT::decode($json->usertoken, 'secret_server_key'); //this will return an error if token has been tampered with
$data = array();
if($token->userID){
//token is valid and therefore user is valid so we go ahead submit the form.
$data['token_is_valid'] = true;
//send contact form
}else{
//token is set but is not valid
$data['token_is_valid'] = false;
echo json_encode($data);
}
}catch(Exception $e) {
$data['token_is_valid'] = false;
echo json_encode($data);
}
}else{
//token is not set.
$data['token_is_valid'] = false;
echo json_encode($data);
}
?>

Error when search a file in CodeIgniter

I have an error when I have tried search a file get from url. I want to search a file in directory it will match with the value get from url if matched controller will return value 'ok' to browser. But I can not see anything appear in my browser.
jquery transmit url to server
var qr_download = function(e){
var img = $('#display').attr('src');
if(img == ''){
alert('Generate a code first!');
return;
}else{
var fn = img.substr(img.lastIndexOf('/')+1,img.length-img.lastIndexOf('/'));
$.ajax({
url: 'download_file/' + fn,
dataType: 'json',
success: function(data){
if(data.error)
alert('Error: ' + data.error);
if(data.success)
alert('Success: ' + data.success);
}
});
return false;
}
my controller
public function download_file($filename){
$this->load->helper('download');
$ext = substr(strrchr($filename,'.'),1);
$list = array();
if(in_array($ext,array('png','jpg','jpeg'))){
$files = scandir('temp/');
for($i=0;$i<count($files);$i++){
if(is_file($files[$i]) && !in_array($files[$i],array('.','..'))){
if($files[$i] == $filename){
//$content = file_get_contents(base_url().'temp/'.$files[$i]);
//force_download($files[$i],$content);
$this->result['success'] = 'ok';
exit();
}
}
}//end for
}else{
$this->result['error'] = 'Not allowed file type';
}
echo json_encode($this->result);
}
Please help me resolve it. Thanks.

Categories