Getting letter 'a' in ajax function if data is arabic - php

I have an api which sends arabic string data and needs to display in html web form using jquery $.ajax method but unfortunately ajax receives only a single character i.e 'a' in response as shown below
{code: 200, status: "error", msg: "a", msg_en: "Invalid Username!!"}
but when i execute the api in postman it shows me this
{"code":200,"status":"error","msg":"اسم المستخدم موجود بالفعل","msg_en":"Username already exists!!"}
this is my code in check_user_name.php
<?php
require_once "../admin/utils/config.php";
require_once "../admin/utils/dbClass.php";
$objDB = new MySQLCN;
require_once "../admin/utils/functions.php";
$fun = new mFunctions;
require_once "lang.confg.php";
$response = array();
if( isset($_POST['user_name']) && $_POST['user_name'] != null){
$user = $objDB->_get_user(null,$_POST['user_name'],null,null,null,null,array('visitor','lawyer','admin'));
if( !empty($user) ){
$response['code'] = 200; // successfull request
$response['status'] = 'error';
$response['msg'] = $_lang['user_name_exists'];
$response['msg_en'] = 'Username already exists!!';
}else{
$response['code'] = 200; // successfull request
$response['status'] = 'success';
$response['msg'] = $_lang['user_name_available'];
$response['msg_en'] = 'Username available!!';
}
}else{
$response['code'] = 200; // invalid paramters
$response['status'] = 'error';
$response['msg'] = $_lang['invalid_requests'];
$response['msg_en'] = 'Invalid Username!!';
}
end:
echo json_encode($response);
exit();
this is ajax request
$(document).on("change", 'input[name=user_name]', function(e) {
/* Act on the event */
var user_name = $ (this).val();
if(user_name.length >= 6 || !user_name.length <=1 ){
$.ajax({
type: 'POST',
url: HOST_URL_API+'/check_user_name.php',
dataType: "json",
contentType: "application/json; charset=utf-8",
data : { 'user_name':user_name }, // our data object
success: function(data) {
console.log(data);
if (data.status == "error") {
$('input[name=user_name]').parent().addClass('has-error');
$('input[name=user_name]').parent().find('.help-block').html(data.msg);
$('input[name=user_name]').focus();
// alert(data.msg);
}else{
$('input[name=user_name]').parent().removeClass('has-error');
$('input[name=user_name]').parent().addClass('has-success');
$('input[name=user_name]').parent().find('.help-block').html('');
}
},
error: function(jqXHR, textStatus, errorThrown, data) {
alert(errorThrown);
},
});
event.preventDefault();
}else{
// alert("Username must be at least 6 characters");
}
});
kindly please if anyone have the solution, will be great help , thanks in advance ;)

Try adding below line in php code which may solve issue while rendering unicode characters.
header("Content-Type : application/json; charset=ISO-8859-1");

Please check this solution hope this will solve your problem i simple create index.php and run this i include header("Content-type: application/json; charset=ISO-8859-1"); this solve the problem.
if (isset($_GET['dataa'])) {
$res['code'] =200;
$res['status'] = 'error';
$res['msg'] = (string) "اسم المستخدم موجود بالفعل";
$res['msg_en'] = 'Username already exists!!';
// header ("Content-Type: text/html; charset=utf-8");
header("Content-type: application/json; charset=ISO-8859-1");
echo json_encode($res);die;
}
in same page html and get req for test resonse and append text to body
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "index.php",
type: 'GET',
data : {dataa : 'ss'},
success: function(res) {
console.log(res);
$('body').append(res.msg);
}
});
})
</script>
</body>
</html>
cheers good luck

Problem is solved guys, thanks for your efforts , actually it was the code mistake, there is an another array with same key name was replacing the array key's value, still thanks for your all efforts.

Related

Passing PHP parser errors back in JSON?

I have an HTML page that sends a JQuery Ajax call to a PHP page and is expecting a JSON response. If the PHP has a parser error, the error is returned to the call, but not in JSON format, so it ends up throwing a "JSON.parse: unexpected character" error on the Ajax side.
Is there a way to get the PHP to send the error message back in a JSON-friendly format? (Yes, it sends the error to event.log in the PHP file's directory, but I'd rather not have to jump through the hoops of accessing it each time there's a problem with the script.)
Edit: Somebody asked for the code - what I mean is, something like this:
First, the "bad" PHP script, oops.php:
<?php
$x = "There's no terminating semicolon"
echo json_encode($x);
?>
Now, the HTML page that calls it, oops.html:
<html>
<head><title>OOPS</title></head>
<body>
<div id="text_goes_here"></div>
</body>
<script>
var $outputText = "Text goes here";
$.ajax({
url:"oops.php",
type:"GET",
data: {},
success:function(data) {
outputText = "Success:<br />";
for (var d in data) {
outputText += (data[d] + "<br />");
}
document.getElementById("text_goes_here").innerHTML = outputText;
},
error:function(xhr, status, message) {
outputText = "Error:<br />";
+ "Status: " + status + "<br />"
+ "Message: " + message + <br />";
document.getElementById("text_goes_here").innerHTML = outputText;
},
dataType:"json"
});
</script>
</html>
The problem appears to be, the PHP returns an error message, but not in a JSON format, so the .ajax call's JSON parser doesn't understand what it is and throws an error of its own. I want to be able to pass the script error that the PHP script generated back to the call in a format that the call can read.
Use try-catch block.
This article shows how to write a AJAX handler with exceptions handled.
Here's the PHP code.
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/ajax.inc.php';
try {
if ($_SERVER['REQUEST_METHOD'] !== "POST") {
throw new Exception('Invalid Request', 2000);
} else {
// status is true if everything is fine
exit(json_encode(
array(
'status' => true
)
));
}
} catch(Exception $e) {
echo json_encode(
array(
'status' => false,
'error' => $e -> getMessage(),
'error_code' => $e -> getCode()
)
);
exit;
}
And, the JS code:
function jsonParse() {
try {
var json = JSON.parse(text);
}
catch(e) {
return false;
}
return json;
}
var http = new XMLHttpRequest();
var data = "username=" + name + '&email=' + email;
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = jsonParse(this.responseText);
if (!json || json.status !== true) {
console.log(json.error || 'Something Bad Happened');
return;
}
alert('Everything is Fine!');
}
}
http.open('ajax.php', 'POST', true);
http.send(data);
Thanks.

New validation with jQuery doesn't send tha value

I want to make two verifications to Emails.
First to verify if the email is accepted ( that it is not an incorrect mail like gimil.com homail.com ... etc) and second verification to know if email existed.
I try to do with this jQuery code
$('#signup').validate({
errorElement: 'span',
rules:{
Email: {
required: true,
email: true,
remote: {
url: '/verifiyEmail',
type: 'POST', //Or whatever
data: function(){
return $("#email").val(); // The value of the email field
},
dataType: "JSON",
dataFilter: function(responseData){
alert(responseData.message); // Or whatever
return responseData.isValid; // validation result
}
}
}
}
});
and the PHP code
if(isset($_POST['email'])){
$email = $_POST['email'];
$response = null;
$isInBlackList = Member::Accepted($email);
if($isBlackList){
// User is in the blacklist
$response = array("isValid"=>false, "message"=>"This email is blacklisted!"); // Initialize $response
}
else{
$alreadyExists = ! Member::($email); // You have to implement this.
if(!$alreadyExists){
// Email already exists
$response = array("isValid"=>false, "message"=>"This email is already in user"); // Initialize $response
}
else{
// We found a valid email
$response = array("isValid"=>true);
}
}
header('Content-Type: application/json');
echo json_encode($response);
}else{
$response = array("isValid"=>'error');
header('Content-Type: application/json');
echo json_encode($response);
}
And always the response is error, which means the Email is not being sent through the PHP code
Is there any solution?

Google Invisible reCaptcha not stopping SPAM submits

I have implemented Google reCaptcha on a site, for the newsletter subscription form, and it does not stop spam. I got up to 20 spam subscribers per day!
What am I not doing correct? Please have a look at the code:
HTML
<form method="post" action="databasepage.php" id="formid" >
<div id="g-recaptcha-answer"></div>
<input name="email" placeholder="Email..." type="email" required>
<button class="g-recaptcha" data-sitekey="my_key" data-callback='onReturnCallback'>Submit</button>
</form>
jQuery
<script>
var onReturnCallback = function(response) {
document.getElementById('g-recaptcha-answer').innerHTML = '';
var url='proxy.php?url=' + 'https://www.google.com/recaptcha/api/siteverify';
$.ajax({ 'url' : url,
dataType: 'json',
data: { response: response },
success: function( data ) {
var res = data.success.toString();
if (res == 'true') {
document.getElementById('g-recaptcha-answer').innerHTML = 'Please wait for a redirect.';
document.getElementById("formid").submit();
}
else {
document.getElementById('g-recaptcha-answer').innerHTML = 'Verification incorrect.';
grecaptcha.reset();
}
}
});
};
</script>
proxy.php
<?php
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
header('HTTP/1.0 403 Forbidden');
die('You are not allowed to access this file.');
}
header('Content-type: application/json');
$url=$_GET['url'];
$response=$_GET['response'];
$secret = "secret_key";
$params = array('secret'=> $secret, 'response'=> $response);
$json=file_get_contents( $url . '?secret=' . $secret . '&response=' . $response);
echo $json;
?>
I have tested this with Incognito Mode, I get the step when I have to verify pictures, if I am not logged in Gmail etc., in reCaptcha admin area I have no errors, but I STILL RECEIVE SPAM EMAILS IN MY DATABASE!!!
What is wrong in my approach?

Ajax file upload in Wordpress - can't pass FormData

I've made a script which uses $.ajax and FormData to pass two form objects to PHP. One form object is a text and the other is a file.
It worked well as a stand-alone script. However, after I added it to Wordpress, as a plugin, it keeps giving me "Uncaught TypeError: Illegal invocation".
I can't afford to serialize the formdata, simply because then I won't be able to pass the file to the callback function in PHP.
JS involving FormData before ajax call:
var fd = new FormData();
var file = jQuery(this).find('input[type="file"]');
var caption = jQuery(this).find('input[name=img_caption]');
var individual_file = file[0].files[0];
fd.append("file", individual_file);
var individual_capt = caption.val();
fd.append("caption", individual_capt);
This part above is 100% correct.
Ajax call:
jQuery.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
data: {
action: 'fiu_upload_file',
security: fiuajax.security,
data: fd,
contentType: false,
processData: false,
},
success: function(response){
var dataObj = jQuery.parseJSON(response);
if(dataObj.message == 'error') {
jQuery('.fiu_validation').html('The following error occured: '+dataObj.desc);
}
else if(dataObj.message == 'success') {
jQuery('.fiu_file').val('');
}
console.log(response);
}
});
This is incredibly frustrating since it worked perfectly fine outside of Wordpress. I've tried de-registering Wordpress' jQuery and enqueueing the latest jQuery version, but it made no difference.
To recap:
1) Ajax/jQuery is refusing to pass a form object to PHP
2) Can't serialize the object because I need to preserve the file object
3) Script works outside of Wordpress
4) Tried updating to the newest jQuery version, no change
try this :
jQuery(document).on('click', '#submit', function(e){
e.preventDefault();
var fd = new FormData();
var file = jQuery(document).find('input[type="file"]');
var caption = jQuery(this).find('input[name=img_caption]');
var individual_file = file[0].files[0];
fd.append("file", individual_file);
var individual_capt = caption.val();
fd.append("caption", individual_capt);
fd.append('action', 'fiu_upload_file');
jQuery.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
data: fd,
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
});
php
function fiu_upload_file(){
var_dump($_FILES);
exit();
}
add_action('wp_ajax_fiu_upload_file', 'fiu_upload_file');
add_action('wp_ajax_nopriv_fiu_upload_file', 'fiu_upload_file');
I managed to do it. The code works on the latest version of Wordpress (4.9.4)
First of all, I'm using XMLHttpRequest to send the data and not the jQuery ajax. This means that you can adapt it to just pure JS.
Notice the xhttp.setRequestHeader("enctype","multipart/form-data"); which was essential to pass the FormData using this method.
JS:
var user_id = $('#user_id').val();
var picture = $('#userPic')[0].files[0];
console.log(picture);
if( picture && typeof picture !== undefined ) {
if ( picture['size'] > 1000000 ) {
alert('The Profile Pic can\'t be larger than 1Mb.');
return;
}
if ( picture['type'].indexOf('image') == -1 ) {
alert('The uploaded file needs to be an image.');
return;
}
var data = new FormData();
data.append('user_id', user_id);
data.append('userPic', picture);
// console.log(data);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('Receive:' + this.responseText);
}
};
xhttp.open("POST", location.origin + "/wp-content/themes/search-and-go-child/ajax/upload_user_profile_pic_ajax.php", true);
xhttp.setRequestHeader("enctype","multipart/form-data");
xhttp.send(data);
}
The PHP part is also extremely useful since it requires the files needed to manipulate the received data with the WP core functions.
Here you will also find the code to upload an attachment using the WP core functions.
PHP:
// error_reporting(-1);
// ini_set('display_errors', 'On');
$path = $_SERVER['DOCUMENT_ROOT'];
require_once($path.'/wp-load.php');
require_once( '/home/s24t06b21lk5/public_html/wp-includes/template-loader.php' );
// require_once("/home/s24t06b21lk5/public_html/wp-admin" . '/includes/image.php');
require_once("/home/s24t06b21lk5/public_html/wp-admin" . '/includes/file.php');
// require_once("/home/s24t06b21lk5/public_html/wp-admin" . '/includes/media.php');
$user_id = $_POST['user_id'];
$picture = $_FILES['userPic'];
var_dump($user_id);
var_dump($picture);
$response = array();
if( isset($picture['name']) && $picture['name'] ) {
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
$picture['name'] = preg_replace( '/[^0-9a-zA-Z.]/', '', basename( $picture['name'] ) );
// Upload the file
$upload_overrides = array( 'test_form' => false );
$upload_result = wp_handle_upload($picture, $upload_overrides);
// echo '<pre>'; print_r($upload_result); echo '</pre>' ;
if( $upload_result['url'] ) {
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $upload_result['url'],
'post_mime_type' => $picture['type'],
'post_title' => $picture['name'],
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $upload_result['file'] );
if( $attach_id ) {
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload_result['file'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
// Update the usermeta table with the uploaded avatar
if( !update_user_meta($user_id, 'wp_user_avatar', $attach_id ) || !update_user_meta($user_id, 'wp_zfgrf5v7rw_user_avatar', $attach_id) ) {
$response['result'] = FALSE;
$response['message'] = "The uploaded image could not be associated with the User ID in the database.";
}
else {
$response['result'] = TRUE;
}
}
else {
$response['result'] = FALSE;
$response['message'] = "Wordpress attachment post for the user's image could not created.";
}
}
else {
$response['result'] = FALSE;
$response['message'] = "The file couldn't be uploaded. Check the permissions.";
}
}
die( json_encode($response) );
Thank you.
Works whith any input(one or many simple or multiple), textarea, select in your form (WP 5.0.3)
$('#form').submit(function(e) {
e.preventDefault();
var form = $(this);
var formdata = (window.FormData) ? new FormData(form[0]) : null;
var data = (formdata !== null) ? formdata : form.serialize();
formdata.append("action", "fiu_upload_file");
$.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function(data){
if(data.error == 'true') {
$('.msg').html(data.true);
}
else {
$('.msg').html(data.false);
// your code if you want an action ...
};
}
});
});
and php for only the files
foreach ($_FILES as $file) :
if($file['error'] == UPLOAD_ERR_NO_FILE) :
continue;
endif;
$valid_ext = array( 'jpg' , 'jpeg' , 'png' , 'doc' , 'docx' , 'pdf' , 'xls' , 'xlsx');
$extension_upload = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ( in_array($extension_upload,$valid_ext) ) :
$name_upload = uniqid() . $file['name'];
$url_insert = trailingslashit( plugin_dir_path( dirname( __FILE__ ) ) ) . 'uploads';
wp_mkdir_p($url_insert);
$name_insert = trailingslashit($url_insert) . $name_upload;
$action = move_uploaded_file($file['tmp_name'],$name_insert);
$msg_true = 'Upload ok ';
else :
$msg_error = 'Upload error';
endif;
endforeach;
$result = !isset($msg_error);
$msg = array();
if($result) :
$msg['error'] = 'true';
$msg['true'] = $msg_true;
else :
$msg['error'] = 'false';
$msg['false'] = $msg_error;
endif;
header('Content-Type: application/json');
echo json_encode($msg);
I added
dataType: 'json'
and it helps.
Full listing of your code of Ajax call:
jQuery.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
data: {
action: 'fiu_upload_file',
security: fiuajax.security,
data: fd,
dataType: 'json',
contentType: false,
processData: false,
},
success: function(response){
var dataObj = jQuery.parseJSON(response);
if(dataObj.message == 'error') {
jQuery('.fiu_validation').html('The following error occured: '+dataObj.desc);
}
else if(dataObj.message == 'success') {
jQuery('.fiu_file').val('');
}
console.log(response);
}
});
here some modified code in case you have multiple data and multiple files
var fd = new FormData();
var data = jQuery('#yourformID').serializeArray();
jQuery.each(data,function(key,input){
fd.append(input.name,input.value);
});
var file = jQuery(document).find('input[type="file"]');
jQuery.each(jQuery(file), function(i, obj) {
jQuery.each(obj.files,function(j,file){
fd.append('files[' + j + ']', file);
})
});
fd.append('action', 'fiu_upload_file');

Contact form doesn't transfer data from AngularJS to PHP

I am trying to retrieve data from AngularJS file to PHP file, but I get the error that it's empty.
I can't find any good examples that are dealing with posting data from angularJS to php file and so I need help.
Angularjs file:
angular.module('myApp', ['ajoslin.promise-tracker'])
.controller('help', function ($scope, $http, $log, promiseTracker, $timeout) {
$scope.ph_numbr =/[0-9]+/;
// Form submit handler.
$scope.submit = function(form) {
// Trigger validation flag.
$scope.submitted = true;
// If form is invalid, return and let AngularJS show validation errors.
if (!$scope.toggle || $scope.toggle.length <= 0 || form.$invalid) {
return;
}
// Default values for the request.
$scope.progress = promiseTracker('progress');
var config = {
params : {
//'callback' : 'JSON_CALLBACK',
'name' : $scope.name,
'email' : $scope.email,
'toggle' : $scope.toggle,
'phone' : $scope.phone,
'comments' : $scope.comments
},
tracker : 'progress'
};
$http({
method : 'POST',
url : 'js/contact.php',
data: config,
headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
.success(function(data, status, headers, config) {
if (data.success) {
$scope.name = null;
$scope.email = null;
$scope.toggle = null;
$scope.phone = null;
$scope.comments = null;
$scope.messages = 'Your form has been sent!';
$scope.submitted = false;
} else {
$scope.messages = 'Oops, we received your request, but there was an error processing it.';
$log.error(data);
}
})
.error(function(data, status, headers, config) {
$scope.progress = data;
$scope.messages = 'There was a network error. Try again later.';
$log.error(data);
});
// Hide the status message which was set above after 3 seconds.
var promise = $timeout(function() {
$scope.messages = null;
}, 3000);
$scope.progress.addPromise(promise);
};
});
php file:
<?php
/*error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'js/PHPMailerAutoload.php';*/
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$data = file_get_contents("php://input");
$postData = json_decode($data);
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['toggle']) && isset($_POST['comments'])) {
//check if any of the inputs are empty
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['toggle']) || empty($_POST['comments'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
$email = trim($_POST['email']);
$subject = trim($_POST['toggle']);
//email address settings
$my_address = "*#yahoo.com";
$headers = "From: ".$email;
$message = "Name: " . $_POST['name'] . "\r\n\r\nMessage: " . $_POST["phone"] . "\r\n\r\nMessage: " . stripslashes($_POST['comments']);
$to = $my_address;
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
mail($to, $subject, $message, $headers);
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
?>
The error message that I get is: "Please fill out the form completely" - which means it doesn't get the values.
My other question is how in the AngularJS do I retrieve the data.success value from the php file?
You seem to be getting the data here:
$data = file_get_contents("php://input");
$postData = json_decode($data);
but then you're using $_POST instead. Perhaps this would work:
if (empty($postData['name']) //etc
It looks like you're accessing data.success appropriately and the value should be set to false as your code currently is.
Additional code review:
If there are errors on the server, it's best to return a status code that indicates that. As is, the server is returning 200 (default), which means everything is OK, even though the request is actually failing. That would eliminate the need for data.success. If the server sends status 200, your .success function will fire. If it returns an error status, like 404, then your .error function would fire instead.
I have doubts about your need of the Content-Type header. You might want to reconsider if that's necessary.
On your Angular form, you ought to nest those $scope properties in an object:
$scope.formData = {
name: '',
email: '',
//etc
}
Then, you can simply pass that directly to your $http call and to reset the values you can simply do $scope.formData = {}.

Categories