I have following code which is working in localhost in windows. But in the server same code fails.
It's the if condition which is not getting executed write even if data==found; I checked the returned data value which is found but cant figure out why the code is not executing properly
function checkAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "ajaxcheck.php",
data:'tran_id='+$("#tran_id").val(),
type: "POST",
success:function(data){
console.log(data);
//var x=data;
$("#loaderIcon").hide();
//console.log((data=="found"));
if(data=="found")
{
$("#singlebutton").prop('disabled', false);
console.log("fail");
$("#tran_id-status").html("Found");
}
else
{
console.log(data);
$("#singlebutton").prop('disabled', true);
$("#tran_id-status").html("");
console.log("ss");
}
},
error:function (){}
});
}
Here is ajaxcheck.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$space=" ";
if(!empty($_POST["tran_id"])) {
$result = mysql_query("SELECT count(*) FROM bank WHERE tran_id ='" . $space.$_POST["tran_id"] . "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0) {
// echo "<span class='status-not-available' id=\"stat\"name=\"stat\" value=\"ok\"> Transaction Details Found.</span>";
echo"found";
}else{
//echo "<span class='status-available' id = \"stat\" name =\"stat\"value=\"not\"> (Enter Valid transaction id to submit)</span>";
echo"notfound";
}
}
?>
The issue is that your data variable is coming back with a new line character. There are two solutions to this 1. trim the returned value. 2. figure out why the php is serving a new line.
Solution 1:
if(data.trim()=="found")
This uses the JS trim function, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim.
Solution 2:
Try removing the ?> from the end of your PHP file (the PHP file will still be valid). This way if there are extra lines after it they won't be served as output and the JS wont receive them.
From the manual:
If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
Related
From the selected value (from the form) I create a variable (var parcela).
var parcela;
$(document).ready(function(){
parcela = localStorage.getItem("parcela");
if (parcela !== '') {
$('#parcela').val(parcela);
}
$("#parcela").on('change',function() {
selectBoxVal_1 = $('#parcela').val();
if (typeof(Storage) !== "undefined") {
localStorage.setItem("parcela", selectBoxVal_1);
} else {
alert('Sorry! No Web Storage support..');
}
location.reload();
});
});
From the created variable (parcela), I create a session variable in PHP.
$.post("phpscripts/session.php", {"parc_id": parcela});
PHP (session.php)
<?php
session_start();
$parcela = $_POST["parc_id"];
$parcela_int = (int)$parcela;
if($_POST){
$_SESSION['parcela_id'] = $parcela_int;
}
?>
After that, the created session variable urge to another php script
query.php
<?php
session_start();
require("common.php");
$user_id = htmlentities($_SESSION['user']['id_korisnika']);
$parc = $_SESSION['parcela_id'];
try
{
$stmt = $db->prepare("SELECT y_cent, x_cent FROM parcele WHERE id_korisnika='$user_id' AND id_parcele='$parc' ");
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
....
This all works perfectly!
However, when I call a php script with query (query.php) in javascript, there is a problem. JS takes the previous session variable instead of the last selected.
$.ajax({
url: 'phpscripts/query.php',
type: 'GET',
success : function(data) {
chartData = data;
//console.log(chartData);
...
Does anyone know what the problem is? I'm trying for two days to solve this ...
Note: The javascript code is contained in a single script.
I solved the problem. I had to extract part of javascript code that calls the php script into a separate script. I called the new JS script with jQuery getScript() Method.
Thank you #knets.
As the title states, I seem to be having an issue with incrementing a variable in my .php file code, it modifies the value in the database, acc_points, to 1 after I increment acc_points by one in the variable above. What the code does is send an ajax request to the php which then updates the data in the mysql database and then returns the data to the js and the js will then alert the data.
The incrementation somehow changes the value of acc_points from 5 to 1. I also considered if the problem had something to do with sessions. I've looked around for relevant information but couldn't find a solution. Would like to find out the real cause of this issue. Thanks!
Here are the codes:
.php file
<?php
require 'dbcon.php';
session_start();
$acc_points = $_SESSION["acc_points"];
$acc_id = $_SESSION["acc_id"];
if(isset($acc_points))
{
$acc_points++;
}
$result = $con->prepare(" UPDATE `points` SET `acc_points` = ? WHERE `acc_id` = ? ");
$result->bind_param("ii", $acc_points, $acc_id);
$result->execute();
if($acc_points != null)
{
$response = $acc_points;
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
else
{
$response = "'Failed. Please try again.'";
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
//connection closed
mysqli_close ($con);
?>
js file
$(document).ready(function() {
$("#qrtest").click(function() {
{
$.ajax({
type: "GET",
url: "http://127.0.0.1/MP/appqrcode.php?callback=?",
dataType: 'JSONP',
async: false,
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function jsonpcallback(response)
{
alert(response.acc_points);
}
})
}
});
});
The first problem is that you are checking the value of $acc_points in the code below, but you are executing the query regardless of whether it's null or not null
if(isset($acc_points))
{
$acc_points++;
} // if condition ends here. Insert command will always be executed.
Then after the comand has been executed you check the value again
if($acc_points != null) /// insert has already happend.
{
}
So you should restructure your code, but better still, you don't need this approach at all. Why not just?
$result = $con->prepare(" UPDATE `points` SET `acc_points` = acc_points+1 WHERE `acc_id` = ? ");
This increments the value already in the database.
I am facing some trouble in passing a simple variable from a php to javascript file.
I have a form which submits through a php file which basically updates the record at the server end. And if the updation is succesful, I just want to pass the message back to the javascript where I can update it on a certain section of the page.
My codes are:
Javascript code - abc.js
function expand_cards(project, SlNo)
{
name = project['project_name'];
j = "ShowForm-"+SlNo+"";
s = "<div class='edit_project_card'>";
s += "<form method='post' action='Edit_Project.php'><div class='project_form'>
// Form Contents
s += "<div class='Form_button'> <input type='submit'> </div>";
s += "</form></div>";
$("#"+j+"").html(s);
response = $.parseJSON(data);
$("#"+j+"").html(response);
}
PHP file - Edit_Project.php
<?php
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
echo json_encode($response);
mysqli_close($connection);
?>
But the problem is the screen is printing $response variable as it is and not exactly passing it back to the javascript function as wished. I know I can use a $.post function which can can receive argument but it's a long form and passing parameters would be difficult in that.
Can anybody help me out here ?
Thanks
Dirty, but it will work:
<script type="text/javascript">
var my_var = <?php echo $some_variable; ?>
// Do something with the new my_var
some_func(my_var);
</script>
I wouldn't do too much detailed stuff with this though, if you can use AJAX that is better.
Note, this can only work on a .php file or one being read as such.
you'll want to do some variable handling in your php side because if the string is empty you'll end up with a
var my_var = ;
which will break the script. so something like:
var my_var = <?php echo "'" . $some_variable . "'";?>
if it's a string or if it's a number:
var my_var = <?php echo (empty($some_variable) ? null : $some_variable);
This is int specific, I'm sure you can come up with a function that will handle it better.
References:
empty function http://php.net/manual/en/function.empty.php
shorthand if http://davidwalsh.name/php-ternary-examples
Since you're submitting the form to the PHP file directly the browser loads the Edit_Project.php file as it would a normal page. If you want a json response to the already loaded page you'll have to use $.post or $.ajax
You can post the whole form simply by using serialize() like this:
$('#form_id').on('submit', function(e) {
// Stop the browser from posting the form
e.preventDefault();
// Post the form via Ajax
$.ajax({
url : 'Edit_Project.php',
type : 'POST',
data : $(this).serialize(),
success : function(response) {
// Here you do the HTML update
$("#"+j+"").html(response.reply);
}
});
});
The Edit_Project.php needs to be changed as well:
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
mysqli_close($connection);
/*
* As SuperDJ suggested, you need to tell the browser that it's
* receiving a JSON ojbect although he did use the wrong content type:
*/
header('Content-Type: application/json');
/*
* According to php.net most decoders should handle a simple string as
* json object but to be safe always encode an array or an object since
* you can't know how the decoder will respond.
*/
echo json_encode(array('reply' => $response));
I am using the following to encode the html source of a ckeditor in a web application.
var updateString = app.getValue('wysiwygHomePage');
var encodedString = encodeURIComponent(updateString);
alert(encodedString);
app.httpRequest("www.xxxx.com/techy/savealldata.php", "GET", function(data, error, httpResponse){
alert(data);
},
{
"updateType":"homePage","updateString":encodedString}, "String", {}, {});
}
Then at the PHP end I am using :
<?php
$updateType = $_GET["updateType"];
$updateString = $_GET["updateString"];
$updateString2 = urldecode($updateString);
echo 'success here '.$updateType .' '.$updateString2 ;
?>
I am adding some coloured tex and the html source for this is:
<p>
<span style="color: rgb(255, 140, 0);">123</span><br />
</p>
<p>
This works okay until I cut and paste more than 32 times.
I then just get error returned from the PHP call.
I presume there are to many chars arriving at the PHP end ???
Any ideas why this is happening ?
Mr WARBY.
UPDATED PHP Code.
<?php
include 'dbdata.php';
$updateType = $_POST["updateType"];
$updateString = $_POST["updateString"];
$updateString2 = urldecode($updateString);
//echo 'success here '.$updateType .' '.$updateString2 ;
if($updateType === 'homePage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 12";
//echo $query5;
echo 'Home Page Updated 2';
mysql_query($query5);
}
if($updateType === 'instructionPage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 13";
echo 'Instruction Page Updated 2';
mysql_query($query5);
}
if($updateType === 'FAQPage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 14";
echo 'FAQ Page Updated';
mysql_query($query5);
}
?>
There are a lot of variables in play here. You need to change your debugging strategy. Instead of testing end to end each time try isolating each component.
In Javascript, call "app.getValue('wysiwygHomePage')", encode the string, decode the string, and put it right back in the editor. Do that in a loop until you can determine if the client-side is mangling anything.
If not, try encoding a complicated string in Javascript, sending it to a PHP script that decodes/re-encodes and echos it back. Do that in a loop several times.
If you still haven't found the problem try making a PHP script that takes a complicated string, INSERTS it, SELECTs it, UPDATEs it in a loop to see if you database encoding or escaping is affecting it.
If at any point you find the string changing when it shouldn't you've probably found your problem.
I'm unable to run my php script at the click of the button.
If I run the script via the terminal, 'php get_funny_status.php' it returns the correct output. However, I'm not able to do this via AJAX. The beginning ajax alert shows up, but I'm not getting any responseText.
Am I missing something?
EDIT: I am testing this application view Preview Browser in Adobe Dreamweaver (I'm not sure if this has anything to do with the issue)
<script>
$( document ).ready(function() {
$( ".nextStatus" ).click(function() {
alert('beginning ajax');
var statusNumber = '5';
$.get('get_funny_status.php?' + statusNumber, function(responseText) {
alert(responseText);
});
});
});
</script>
Here's my php script:
<?php
//initialize DB stuff
$status_text_query = "SELECT * FROM funny_status WHERE STATUS_NUM = '". $_GET['statusNumber']."'";
$result = mysql_query($status_text_query);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo 'num likes: ' . $row['NUM_LIKES'];
echo 'num dislikes: ' . $row['NUM_DISLIKES'];
echo 'status text: ' . $row['STATUS_TEXT'];
echo 'status num: ' . $row['STATUS_NUM'];
}
?>
Fix this from:
$.get('get_funny_status.php?statusNumber', function(responseText) {
alert(responseText);
});
to
$.get('get_funny_status.php?statusNumber='+statusNumber, function(responseText) {
alert(responseText);
});
There are a few issues that I see:
In your PHP, _GET should be $_GET.
$status_text_query = "SELECT * FROM funny_status WHERE STATUS_NUM = '"
. $_GET['statusNumber']."'";
In your AJAX call, you need to send your parameter ?statusNumber=' + statusNumber, ...
$.get('get_funny_status.php?statusNumber=' + statusNumber,
function(responseText) {
Not necessarily a syntax error: I noticed that you're using mysql_* to access the database. This is a bad idea; I'd advise switching to either the mysqli_* functions or to the PDO class. Related to this issue, if I were to set statusNumber to something like "'; DELETE FROM funny_status;--", I would be able to delete all of the data in that table. This is called SQL Injection, and it is a serious security issue.