how to post a persian statement with spaces in ajax url - php

I have used ajax as below:
$('.province').on('click', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var valueSelected = valueSelected.replace(/ /gi,"%20");
var valueSelected = encodeURIComponent(valueSelected);
//alert(valueSelected);
$.ajax({
type: 'post',
encoding:"UTF-8",
url: "<?php echo base_url();?>Search/cities_of_province/"+valueSelected,
data: '',
contentType: "charset=utf-8",
success: function (result) {
//alert(result);
$('.city').html(result);
return false;
}
});
return false;
});
valueSelected in above url is a persion statement with space in it. for example it is استان آذربایجان شرقی.
when it is post to the url, just first part(استان) is recieved.
I aslo removed valueSelected.replace(/ /gi,"%20") and encodeURIComponent(valueSelected) but nothing happend.
what is the solution?

I faced no issue like that.. I used no encodeURIComponent no encoding:"UTF-8" no contentType: "charset=utf-8"
Nothing needed. And it works simply perfect. I tested it with following code
I have Html
<input id='yourInputId' value='استان آذربایجان شرقی' />
JavaScript
<script>
var valueSelected = $('#yourInputId').val();
//before ajax request
alert(valueSelected ); // it gives me here =>استان آذربایجان شرقی
//before making ajax reuest plz confirm you get above value correctly here
alert(<?php echo base_url();?>); //it must be valid as well
$.ajax
({
type: "POST",
url: "<?php echo base_url();?>Search/cities_of_province", //should be valid
data: { province : valueSelected },
success: function (result) {
alert(result); //it gives => استان آذربایجان شرقی
},
error:function(a)
{
alert(a.responseText);
}
});
</script>
PHP
<?php
if(isset($_POST['province']))
$v = $_POST['province'];
else
$v = 'Province value not provided from client side';
echo $v;
?>

So it looks like you are using a select input here. If that is the case, you should use alphanumeric/ASCII value key in your options and not the human readable labels. That might look like:
<option value="some_ascii_key">استان آذربایجان شرقی</option>
You can then have a reliable key to use in your AJAX request.
I also think your request should be a GET and not a POST since you are just reading values from API rather than trying to create/update records via API.
Putting it all together, you might have something like this:
// note values for each property/ley may not be important here
// as they are not really needed to validate that the province key
// in option value has not been modified by client,
// which is really what you are using this for.
// If you need to have option label text available in
// javascript you can store that here as shown.
var provinceConfiguration = {
'key1': 'استان آذربایجان شرق';
'key2': 'some other Persian string';
// and so on...
}
$('.province').on('click', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
// perhaps validate that value provided is amongst expected keys
// this used the provinceConfiguration object proposed in this example
if(typeof provinceConfiguration[valueSelected] === 'undefined') {
console.log('Unexpected province key passed');
e.stopPropagation();
return false;
}
// probably can drop this line if defined keys do not need encoding
var valueSelected = encodeURIComponent(valueSelected);
// since you can use default GET setting you can use this shorthand
$.get(
'<?php echo base_url();>Search/cities_of_province/' +
valueSelected,
function(result) {
// console.log(result);
$('.city').html(result);
return false;
}
);
/*
Or more verbose option
$.ajax({
type: 'GET',
// not valid setting key -> encoding:"UTF-8",
url: '<?php echo base_url();>Search/cities_of_province/' + valueSelected,
// default is fine here so not needed -> contentType: "charset=utf-8",
success: function (result) {
// console.log(result);
$('.city').html(result);
return false;
}
});
*/
return false;
});
Note that you should be using console.log() to debug code rather than alert(), as alert actually blocks code execution and may make some debugging more problematic as your debugging mechanism changes how your code executes. This can problem can be exacerbated when debugging asynchronous code.
Your server-side code would obviously need to be updated to understand the province keys as well.

Please take a look at this javascript library. That can be of help to you.
Fix Persian zero-width non-joiner(Replace spaces by half-space)
import { halfSpace } from "persian-tools2";
halfSpace("نمی ‌خواهی درخت ها را ببینیم؟") // "نمی‌خواهی درخت‌ها را ببینیم؟"
Fix Persian characters in URL.
import { isPersian, toPersianChars } from "persian-tools2";
URLfix(
"https://fa.wikipedia.org/wiki/%D9%85%D8%AF%DB%8C%D8%A7%D9%88%DB%8C%DA%A9%DB%8C:Gadget-Extra-Editbuttons-botworks.js",
); // "https://fa.wikipedia.org/wiki/مدیاویکی:Gadget-Extra-Editbuttons-botworks.js"
URLfix("https://en.wikipedia.org/wiki/Persian_alphabet"); // "https://en.wikipedia.org/wiki/Persian_alphabet",
URLfix("Sample Text"); // "Sample Text"

Related

ajax to php $variable

I try to pass this value to my php code, but I do not know how to do it. post method does not work. (I do not know why).
<script>
var val = localStorage.getItem('sumalist');
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function () {
console.log(val);
}
});
</script>
and in my php code, value is not set.
if (isset($_POST["value"])) {
echo "Yes, value is set";
$value = $_POST["value"];
}else{
echo "N0, value is not set";
}
PS: My php code is in the same file in js code.
Check if this works
<?php
if(!empty($_POST)) {
$value = (isset($_POST["value"])) ? $_POST["value"] : NULL;
$return = ($value != NULL) ? "Yes, value is: ".$value : "N0, value is not set";
echo $return;
exit;
}
?>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>
<script>
var val = 'value sent';
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function (ret) {
console.log(ret);
}
});
</script>
Open console for result
Please use console if you're using chrome then open console and try debugging,
And first you run that ajax function in jquery ready function like this
$(document).ready(function (){ $.ajax( replaced for ajax function ) }
If you want to use the response in callback success function, use this:
success: function (ret) {
console.log(ret); //Prints 'Yes, value is set' in browser console
}
In your browser you have Developer Tools - press F12 to open, go to Network tab (FireFox, Chrome, IE - all the same), then reload your page and you will see the line for your AJAX call (if it is performed on load, or trigger your call if this is not the case), select it and right hand you'll see a extra frame where you can see all the details of your request, including request params, headers, response headers, the actual response and many other.
That's the best solution to check your AJAX request without asking uncompleted questions and seeking for the answers in case someone can assemble your full case in his mind.
Believe me - this is the best solution for you and not only for this case!
Of course your JS should be performed when DOM is ready so you have to wrap it in
${function() {
// your code here
});
in case you want to be executed on load.

How to post more than 1 var’s with ajax

I've been googling for a way to do this but everything I have found doesn't help me.
I'm not sure how to post all the below variables, If I select only one of them it'll post just fine as well as putting it into the correct database column.
any help would be much appreciated.
function submit() {
var mm10 = $('#10MM'),
mm16 = $('#16MM'),
mm7 = $('#7MM'),
mm2 = $('#2MM'),
fines = $('#Fines'),
bark = $('#Bark'),
cqi = $('#CQI');
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: ,
success: function(){
$("#successMessage").show();
}
});
};
You can do it in two ways. One using arrays, or two using objects:
function submit() {
var mm10 = $('#10MM').val(),
mm16 = $('#16MM').val(),
mm7 = $('#7MM').val(),
mm2 = $('#2MM').val(),
fines = $('#Fines').val(),
bark = $('#Bark').val(),
cqi = $('#CQI').val();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: [mm10, mm16, mm7, mm2, fines, bark, cqi],
success: function() {
$("#successMessage").show();
}
});
} // Also you don't need a semicolon here.
Also you don't need a semicolon at the end of the function.
Using arrays is easier, if you want more precision, use objects:
function submit() {
var mm10 = $('#10MM').val(),
mm16 = $('#16MM').val(),
mm7 = $('#7MM').val(),
mm2 = $('#2MM').val(),
fines = $('#Fines').val(),
bark = $('#Bark').val(),
cqi = $('#CQI').val();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: {
"mm10": mm10,
"mm16": mm16,
"mm7": mm7,
"mm2": mm2,
"fines": fines,
"bark": bark,
"cqi": cqi
},
success: function() {
$("#successMessage").show();
}
});
} // Also you don't need a semicolon here.
And in the server side, you can get them through the $_POST super-global. Use var_dump($_POST) to find out what has it got.
Kind of like Praveen Kumar suggested, you can create an object. One thing I was curious about, it looks like you're passing jQuery objects as your data? If that's the case, $_POST is going to say something like [object][Object] or, for me it throws TypeError and breaks everything.
var form_data = {};
form_data.mm10 = $('#10MM').val(); // Input from a form
form_data.mm16 = $('#16MM').val(); // Input from a form
form_data.mm7 = $('#7MM').val(); // Input from a form
form_data.mm2 = $('#2MM').text(); // Text from a div
form_data.fines = $('#Fines').text();
form_data.bark = $('#Bark').text();
form_data.cqi = $('#CQI').text();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: form_data,
success: function() {
alert('success');
}
});
}
Then to get those values in your PHP you'd use:
$_POST[mm10] // This contains '10MM' or the value from that input field
$_POST[mm16] // This contains '16MM' or the value from that input field
$_POST[mm7] // This contains '7MM' or the value from that input field
$_POST[mm2] // This contains '2MM' or the value from that input field
And so on...
I tried to put together a jsFiddle for you, though it doesn't show the PHP portion. After you click submit view the console to see the data posted.

check username exists using ajax

I use this code to check username exists in database before or not. code works good and shows available or taken username. now i want to submit button should be disable when user select username that was taken befor and enable when username available . please guide me how.
$(document).ready(function() {
$('#username').keyup(function() {
$.post('adm/chk_uname_avail.php', {
uname : changeuser.username.value
}, function(result){
$('#available').html(result);
})
})
})
I'm using the old $.ajax function and make sure you have a data keyed taken (as example) with boolean type on adm/chk_uname_avail.php and notice that you should return JSON data type from it.
Example of adm/chk_uname_avail.php
<?php
//return response as JSON
header('Content-type:application/json;charset=utf-8');
....
....
....
$data['taken'] = true; //show this response to ajax
echo json_encode($data);
?>
Ajax
$(document).ready(function() {
$('#username').on('keyup', function() {
$.ajax({
type: 'POST',
url: 'adm/chk_uname_avail.php',
data: {uname : changeuser.username.value},
success: function(result) {
var $btn = $('#submiButton');
if (result.taken) {
$btn.prop('disabled', true);
} else {
$btn.prop('disabled', false);
}
//As #Mikey notice, You can just use this as simply as
//$('#submiButton').prop('disabled', result.taken);
}
});
});
});
Use .attr() method of jQuery to make the submit disabled on certain condition.
So you can update your jQuery like this,
$.post('adm/chk_uname_avail.php', {
uname : changeuser.username.value
}, function(result){
$('#available').html(result);
if(/* CHECK FOR CERTAIN CONDITION */) {
$('#submit_btn').attr('disabled','disabled');
}
});
To remove the disabled attribute you can use removeAttr() method of jQuery. Like this,
$('#submit_btn').removeAttr('disabled');
http://api.jquery.com/attr/
https://api.jquery.com/removeAttr/

Passing of javascript variable data to php variable in the same php file

I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:
Javascript:
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "POST",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
Then on my php tag:
<?php
if(isset($_GET['subDir']))
{
$subDir = $_GET['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!
When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
or also:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
Then in the response:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the
Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).
Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:
_POST means that this is an AJAX call
_GET means that this is the normal opening of signage.php
So you would do something like:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
A surer way to check is verifying the XHR status of the request with an ancillary function such as:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* #return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
Now you would have:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
and actually you could offload your AJAX code into another file:
if (isXHR()) {
include('signage-ajax.php');
exit();
}
You are send data using POST method and getting is using GET
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
You have used method POST in ajax so you must change to POST in php as well.
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
Edit your javascript code change POST to GET in ajax type
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "GET",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
when you use $_GET you have to set you data value in your url, I mean
$.ajax({
type: "POST",
url: 'signage.php?subDir=' + val,
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
or change your server side code from $_GET to $_POST

jQuery IF statement not working

Im performing an ajax query to check the name of a car in a mysql database, if a car is found it will return "Car name unavailable", otherwise "Car name available". This text is put into a div with an id of "checkname".
All this runs fine, but when I try to hide the add button if the car name is unavailable it fails to do so and I dont know why :/
function check_name(){
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function(html){
$("#checkname").html(html);
}
});
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml==compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
Any code that relies on the response from the AJAX request, must be called inside a callback to the request.
function check_name() {
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function (html) {
$("#checkname").html(html);
// I placed your code here instead.
// Of course you wouldn't need to set and then get the HTML,
// since you could just do a direct comparison.
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml == compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
});
}
The reason is that by default, an AJAX request is asynchronous, which means that the code that comes after the request will execute immediately instead of waiting for the response to return.
Another possible issue when comparing HTML to keep in mind is white space. If you're doing a string comparison, it must be exactly the same, so if there's whitespace, you'll need to trim it first. You can use jQuery.trim()(docs) to do this.
You have to put the code inside of you AJAX requests success callback, otherwise it will be called before the AJAX call has completed. Putting it inside the success callback means that the code containing the IF statement will only run after the AJAX call has completed. Try:
function check_name(){
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function(html){
$("#checkname").html(html);
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml==compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
});
}
You could probably solve the problem doing what patrick dw suggested (it's likely that the ajax call has not been completed yet (i.e. div content wasn't updated) and the check returns false), but since string comparison can really bring to many errors (like string not matching because of newlines, trailing spaces, case sensitiveness, etc...) I would suggest you use another comparison method.
For example you could add a class using .addClass() if the car is found, and then checking if that div has the "found" class using .hasClass()
I use .post(). The third argument of post() is the returned data from the file where the data was posted.
I pass to validate.php the inputed email address, validate.php checks it and if it is valid, it returns 1.
$('a.post').click(function() {
$.post('validate.php',{email : $("#email-field").val()},
function(data){
if(data==1)
{
//do something if the email is valid
} else {
//do other thing
});
});
Hope this helps.

Categories