Passing a PHP variable back to ajax - javascript

if($rx==$_SESSION['randomx'] and $ry==$_SESSION['randomy']){
echo "Cestitam, zadeli ste pravilno celico! rabili ste samo:".$_SESSION['poskus'];
}
else{
$razdalija=sqrt(($rx-$_SESSION['randomx'])*($rx-$_SESSION['randomx'])+($ry-$_SESSION['randomy'])*($ry-$_SESSION['randomy']));
echo $_SESSION["poskus"].". Zgresili ste za: ".round($razdalija);
$_SESSION["poskus"]++;
}
Both echos return a sentense how can i differenciete those two sentences?
In the ajax function i want to compare which one came back so i can set the background color.

I would return json instead and use the key to differentiate between the possible outputs.
For example:
$arr = array();
if ($rx==$_SESSION['randomx'] and $ry==$_SESSION['randomy']) {
$arr['good'] = "Cestitam, zadeli ste pravilno celico! rabili ste samo:".$_SESSION['poskus'];
} else {
$razdalija=sqrt(($rx-$_SESSION['randomx'])*($rx-$_SESSION['randomx'])+($ry-$_SESSION['randomy'])*($ry-$_SESSION['randomy']));
$arr['bad'] = $_SESSION["poskus"].". Zgresili ste za: ".round($razdalija);
$_SESSION["poskus"]++;
}
echo json_encode($arr);
Now you can check in javascript which one is set and do what you want to do.
You could also return an additional value that determines the status and a text value for the text, plenty of possibilities. The key is sending back structured data instead of just a text string.

Related

How to print " (quot) instead of " using jquery in input text?

I'm trying to fetch data using jquery but I'm having a problem with htmlentities because it shows " instead of " in jquery.
Here is my code for input text:
<input type="text" name="material_name[]" id="material_name<?=$x?>" autocomplete="off" readonly="true" class="form-control oninput" />
And here's JQUERY Fetching the value
$.ajax({
url: 'fetchSelectedOrder.php',
type: 'post',
data: {productId : productId},
dataType: 'json',
success:function(response) {
// setting the rate value into the rate input field
$("#material_name"+row).val(response.material_name);
} // /success
}); // /ajax function to fetch the product data
}
fetchSelectedOrder.php
<?php
require_once 'checker.php';
$productId = $_POST['productId'];
$sql = "SELECT material_name FROM tbl_materials WHERE m_id = $productId";
$result = $controller->runQuery($sql);
$result->execute();
if($result->rowCount() >= 1) {
$row = $result->fetch(PDO::FETCH_ASSOC);
} // if num_rows
echo json_encode($row);
Data From Database:
I use htmlentities to prevent quote inside database.
How can I fetch " as "?
You can use html_entity_decode() to convert it back to the original text.
However, I recommend that you stop using htmlentities() when storing into the database. You don't need to prevent having quotes in the database. If you're getting syntax errors when you try to store it, you should fix the code to use parametrized statements rather than substituting variables into the string. And if you must substitute variables, you should use a proper escaping function, either mysqli::real_escape_string() or PDO::quote().
If you're trying to prevent XSS, call htmlentities() when you're displaying the output on a web page. If you're using JavaScript to display the results on a web page, use the textContent DOM property or the jQuery .text() method, rather than innerHTML or .html(). If you're assigning to the value property, it never gets executed so you don't need to do any encoding.
You can use the following function to decode html:
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
// handle case of empty input
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
Usage:
$("#material_name"+row).val(htmlDecode(response.material_name));
That will display html as real text.
You could decode the HTML entities coming from the DB on server side.
<?php
require_once 'checker.php';
$productId = $_POST['productId'];
$sql = "SELECT material_name FROM tbl_materials WHERE m_id = $productId";
$result = $controller->runQuery($sql);
$result->execute();
if($result->rowCount() >= 1) {
$row = $result->fetch(PDO::FETCH_ASSOC);
} // if num_rows
// Run html_entity_decode on all $row values
foreach ($row as $k => $v) {
$row[$k] = html_entity_decode($v);
}
echo json_encode($row);
That also is a "patch" for a DB having bad values... But unlike the other answer, which relies on the end user's device, here is a server-side solution.
And please read about prepared statements to prevent injection...

selection the value of an option on a dropdown list

i'm working on this site that allows to students to book seats for training sessions by selectiong theme on a drop down list and clincking on a button. i created a javascript(ajax) script that contains a function which calls a php script that reduces the number of seats on my database.
But unfortunately it's not working... i need your help guys :
here's my javascript :
<select name="Branche" name="clock" id="clock" onchange="count()"></select>
<a onclick="count()" class="button">
<span class="user">Réserver une place</span>
</a>
<script>
function count(){
var place = document.getElementByTagName(clock);
var option = place.options[place.selectedIndex].id;
alert(option);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "count.php?place=" + place,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var reponse = xmlhttp.responseText;
if(reponse == "yes") {
alert("Votre place a été réservé");
} else {
alert("Vous êtes arrivé trop tard !");
}
}
}
}
</script>
and here's my php script :
try {
$db = new PDO('mysql:host=localhost;dbname=projet','root','',array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch(Exception $e){
echo $e->getMessage();
die();
}
$nom = $_GET['place'];
$sq="SELECT place FROM formation WHERE nom='$nom'";
$re = $db->query($sq);
$i = $re->fetch(PDO::FETCH_ASSOC);
if($i > 0){
$sqq="UPDATE formation SET place = place - 1 WHERE nom='$nom'";
$res = $db->query($sqq);
echo 'yes';
} else {
echo 'no';
}
The first errors are in this line:
var place=document.getElementTagName(clock);
You need to find the element by it's id, not its tag name. Also click is an non-existing variable; you should use "clock" with quotes:
var place=document.getElementById("clock");
That way place will be the select element. But then later you use this in building the URL parameter:
xmlhttp.open("GET","count.php?place="+place,true);
But place is not the selected value; it is the select element, so that will not work right. Instead you should send the value you have in the option variable:
xmlhttp.open("GET","count.php?place="+option,true);
This is assuming that the value of option is correct. Without seeing the HTML and your database table content, this is impossible to say at this moment.
The PHP script has an error here:
$i = $re->fetch(PDO::FETCH_ASSOC);
if($i>0){
You use $i as if it is the selected value, but that is not true. fetch() returns an array with values, in this case an array with one value. The comparison as you have it will always return true, even if the selected place value is 0.
Furthermore you should alter your PHP script so you do not concatenate values into an SQL string, as it makes you vulnerable to SQL injection. Instead use prepared statements.
Also, your PHP script is not working well when there is a lot of concurrency. Imagine that there is one seat left and two make the PHP call at the same time, then both will see there is one place left before the other one has decreased the count, and both will get a "yes".
Instead you should first perform the update and check for availability within the update statement. Then check if the statement updated a record. If not, then there were no places left. As an update statement locks the record during the update, only one process can do it at a time.
Suggested PHP code after database connection is established:
$stmt = $db->prepare("UPDATE formation
SET place = place - 1
WHERE nom = ?
AND place > 0");
$stmt->execute(array($_GET['place']));
echo $stmt->rowCount() ? 'yes' : 'no';

How has the return of a PHP-function to look like to be valid for use by AJAX and PHP?

I got an input field. The user-input is getting checked on the fly by some AJAX request. The user is then getting informed whether his/her input is ok or not.
After submitting, the input has to be checked again for the same characteristics as it was checked before by AJAX(in case of JavaScript is deactivated).
AJAX uses "check.php" asynchronously.
<?php
include 'foo.php';
$input= $_POST['input'];
checkSomethingElse(testSomething($input));
?>
Then i got a "submit.php" file that is getting called on submission. It checks the input, and then writes the input into Database.
<?php
include 'foo.php';
$input= $_POST['input'];
checkSomethingElse(testSomething($input));
foo(){
//write input into Database}
?>
The "foo.php" looks like this
<?php
function testSomething(){
//do something
}
function checkSomethingElse(){
//test...
echo value // e.g. echo "true"
return value // e.g. return true
?>
(e.g. validate and sanitize input and other checks)
For the purpose of AJAX/JS/JQuery to use the returned value, it is returned trough "echo".
For the purpose of PHP to use the returned value, it is returned trough "return".
In case of AJAX-request there is everything fine, since it ignores the "return" and uses only "echo". In case of PHP it uses the "return value" and prints out the "echo value".
So the question is:
Is this structure logically and functionally ok? And how can i fix this code to spit out a string trough the "echo", when the user is not using JavaScript?
Thank You.
first of all the first issue i can see is that you are calling echo after return ... which will never happen, because execution of the function ceases once it hits return.
I would suggest just making your functions that return a value and then determine if you need to echo it afterwards ...
<?php
function some_function() {
return "value";
}
$value = some_function();
if (isset($_POST["returnajax"])) {
echo $value;
}
?>
as #rm-vanda suggests - json_encode may be useful to you if you are processing the AJAX request expecting a JSON. In this case it might look something like this...
function some_function() {
return "value";
}
function some_other_function() {
return "another_value";
}
$values = array();
$values[] = some_function();
$values[] = some_other_function();
if (isset($_POST["returnajax"])) {
header("Content-Type: application/json");
echo json_encode($values);
}
the resulting echo would look something like this:
["value","another_value"]
unfortunately, you may find that jquery will not like non well formed json. what i usually do is the following:
if (isset($_POST["returnajax"])) {
header("Content-Type: application/json");
echo json_encode(array("values"=>$values));
}
which would result in:
{"values":["value","another_value"]}
Separate the display logic from the validation logic.
For example:
// validation functions
function testSomthing(){
//test...
return $value; // e.g. return true
}
function checkSomethingElse(){
//test...
return $value; // e.g. return true
}
// calling logic in check.php
include 'foo.php';
$result = false;
if (!empty($_POST['input']) {
$input= $_POST['input'];
$result = checkSomethingElse(testSomething($input));
}
$return = new stdClass();
$return->result = $result;
header("Content-Type: application/json");
echo json_encode($return);
Note: it is not clear from your example why you have nested validation function calls (i.e. checkSomethingElse(testSomething($input))). I don't think it will work that way (because you will pass true/false result to outer function call), but I am showing the code here the same as you do, as I certainly don't have full picture as to function usage to offer up an alternative.
You can check the variable $_SERVER['HTTP_X_REQUESTED_WITH']
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special ajax here echo for example*/
}
else {
/* Not AJAX use return*/
}

how to get the value of array sent from AJAX POST in php?

i am having a probelem with ajax multiple delete. I've sucessfully set the values of the checkbox slected in a variable.
the problem i have to solve is how to get the value of the sent array in php.
here is the ajax post code
<script>
$("#delete-btn").click(function(e){
e.preventDefault();
var id = new Array();
$(".check:checked").each(function() {
id.push($(this).attr('value'));
});
$.post("../ajax/multiDelete.php",{id:id},function(data){
alert(data);
});
});
</script>
now, the php page
<?php
if(isset($_POST['id'])){
$id = array($_POST['id']);
foreach($id as $value){
echo $value;
}
}
?>
when the data is alerted, i only get "array";
i do not know about JSON, so if there is anything i can do without it then your help is most appreciated! thanks : D
Since id is an array and in your code you are wrapping it inside an array again. Instead of that,do this :
<?php
if(isset($_POST['id'])){
// Don't use array($_POST['id']) as id is already an array
$id = $_POST['id'];
foreach($id as $value){
echo $value;
// Here you'll get the array values
}
}
?>
If you want retun array from php - user json_encode()
echo json_encode(array($_POST['id']));
P.S. JS function alert() can`t print arrays or object. Use console.log(data) and you will see result in developer console of your browser.
This is not related to your question, but I just wanted to show you a better way of getting the id values, without creating a new array variable and then pushing items into the array, by using the jQuery .map() method:-
$("#delete-btn").click(function (e) {
e.preventDefault();
// Get all the values in the array 'id' variable
var id = $(".check:checked").map(function () {
return this.value || 0;
}).get();
$.post("../ajax/multiDelete.php", { id: id }, function (data) {
alert(data);
});
});
Hope this helps!
Don't pass array variable in AJAX. Convert id array to JSON using JSON.stringify(id).
In PHP backend,use
<?php $val = json_decode($_REQUEST['id']);
foreach($val as $ids){
echo $ids;
}
use $val array to proceed further in php.
You have to access your checked value by-
<?php
if(isset($_POST['id'])){
$id = array($_POST['id']);
foreach($id as $value){
foreach($value as $value1){
echo $value1;
}
}
}
?>
Because this is an array inside array.

Update my php array in javascript function

I want to update or add new key=>value to my php array in javascript function.
The paging is in ajax, page is not reloaded again.
Actually I am receiving the data in a text file which is uploaded on my server. I parse that file and get a limited number of records, when I click on NEXT then one more file is uploaded on server and I parse it once again and show the data. So, I want that all data to be stored in php array on that page so when next time I go to PREVIOUS record, it doesn't parse the file once again, just show the data from the array.
//php array name is $call_data
var file_data = <?php $content = #file_get_contents("text file name");
$content = rawurldecode($content);
$new_call_data = json_decode( $content );
foreach ($new_call_data->CALLS as $key => $val) {
$call_data['CALLS'][] = $val; $file_rec_start++;
}
echo json_encode( $call_data ); ?>;
i don't see the part, where you split your "content" part into peaces so you have to reload the page, is it missing or is this part in JavaScript?
also you could minify you source:
<?php
$my_contents = file_get_contents('myfile.json');
$my_contents = rawurldecode($my_contents);
$my_array = json_decode($content);
$my_json = json_encode(array_values($my_array->CALLS));
?>
var file_data = <?=$my_json?>;
than you can itterate trough the array in javascript without the need of refreshing the page.
you could use
var results_per_page = 25
var page_available = Math.ceil(file_data.length / results_per_page);
var page = 0;
var page_array = file_data.slice((page * results_per_page), ((page+1)*results_per_page));

Categories

Resources