in the below code I am passing ipdno as a param, and then I am getting the response from server for that this is my code.
php
$('#print').click(function(){
var ipdNo = $('#hid_ipd_id').val();
var param = "ipdNo="+ipdNo;
alert("Param: "+param);
$.ajax({
url: "ipd_bill_print.php", //The url where the server req would we made.
async: true,
type: "POST", //The type which you want to use: GET/POST
data: param, //The variables which are going.
dataType: "html",
success: function(data){
//alert("Result: "+data+"\nRefreshing page... ");
if(data=='success'){
alert("Record updated succcessfully!");
location.reload(true);
}else{
alert("Record could not be updated!");
}
}
});
});
In this code I want to indicate the success when there are some rows, otherwise it should indicate the failure.
ipd_bill_print.php
<?php
require_once("db/include.php");
$ipd_no = $_POST['ipd_no'];
$token = "Empty";
try{
$dbh = getConnection();
$flag = true;
$sql = "SELECT ipd_reg_no
FROM ipd_bill
WHERE ipd_reg_no = ?";
$sth = $dbh->prepare($sql);
$sth->bindParam(1,$ipd_no);
$row = $sth->fetch(PDO::FETCH_ASSOC);
echo $row;
if($row >==0)
$flag = false;
if($flag)
echo "success";
else{
$dbh->rollback();
echo "fail";
}
//echo "\n FLAG: $flag \n";
$dbh->commit();
}catch(PDOException $e){
print($e);
try{
$dbh->rollback();
}catch(PDOException $e){
die($e->getMessage());
}
}
else{ //if ends here..
echo "Outside if...";
}
In JavaScript code you have provided the ipdNo as the AJAX parameter, but in the PHP file you try to access an undefined key named ipd_no through $_POST. I also recommend to change the AJAX dataType from "html" to the "text", because you are just echoing some plain text in the PHP file.
In the PHP file, in order to use the PDO::commit or PDO::rollBack, you need to first invoke PDO::beginTransaction.
Before calling PDOStatement::fetch, you need to execute your statement through PDOStatement::execute.
In the if statement you need to change the syntactically wrong statement of $row >==0 to something like $row!==false && count($row)>0. Finally, consider that you don't have any matching if statement for you last else statement, where you commented //if ends here.., However; It just maybe not visible in you code snippet.
In addition, you are better to always check the returning result from any method call or function invoke.
Related
I'm making a simple login test and the code returns the json response when the fields are empty,but not when the login fails or succeds, like:
Empty Fields - OK
Login Succeded - nope
Login failed - nope
Request:
var loader = $('#trabalhando');
$(function() {
$('form').submit(function(e) {
loader.fadeIn("slow");
e.preventDefault();
$.ajax({
url: 'login.php',
data: $(this).serialize(),
method: 'post',
dataType: 'JSON',
success: function(data){
loader.fadeOut("slow");
console.log(data);
alert(data.resp);
},
error: function(data) {
alert(':(');
loader.fadeOut("slow");
console.log(data);
}
});
});
});
Response:
<?php
header('Content-Type: application/json');
if (isset($_POST['cpf']) && isset($_POST['pass']) && $_POST['cpf'] != "" && $_POST['pass'] != "") {
$cpf = $_POST['cpf'];
$passw = sha1(strrev(md5($_POST['pass'])));
include 'config.php';
$sql = "SELECT * FROM users WHERE cpf = :cp AND passwd = :pw";
$chec = $db->prepare($sql);
$chec->bindParam('cp', $cpf, PDO::PARAM_STR);
$chec->bindParam('pw', $passw, PDO::PARAM_STR);
$chec->execute();
if ($chec->rowCount() > 0) {
echo json_encode(array('resp' => 'nice'));
} else {
echo json_encode(array('resp' => 'nope'));
}
} else {
echo json_encode(array('resp' => 'fields'));
}
?>
Edit: updated the code
You are not binding your parameters properly, so you probably have a PDO error that you're not handling. Change:
$chec->bindParam('cp', $cpf, PDO::PARAM_STR);
$chec->bindParam('pw', $passw, PDO::PARAM_STR);
To:
// notice the colon : in front of var names, so it matches the placeholders!
$chec->bindParam(':cp', $cpf, PDO::PARAM_STR);
$chec->bindParam(':pw', $passw, PDO::PARAM_STR);
In general, database, file and remote server operations (FTP, HTTP, SSH...) are very finicky so when you rely on these, always error check! You should factor out your queries into a specialized function that does proper error checking.
/**
* #param PDO $db The PDO object with which to perform queries
* #param string $sql raw SQL (eg: "select * from t where a = :param" )
* #param array $params Array of parameter names and values eg: [':param' => 'value']
* #param string $error Will be filled with the error details if the DB operations fail
* #return false|PDOStatement FALSE on error, or the statement on success
*/
function query(PDO $db, $sql, array $params, &$error){
try{
// error check every step!
if(!$stmt = $db->prepare($sql)) throw new Exception($db->errorInfo()[2]);
if(!$stmt->execute($params)) throw new Exception($stmt->errorInfo()[2]);
return $stmt; // return the $stmt for further processing
}catch (Exception $e){
$error = $e->getMessage();
return false;
}
}
Now you can perform your queries much more simply:
$stmt = query($db, $sql, $params, $error);
// decide what to do on failure
if(!$stmt) die($error);
// now it's safe to use $stmt to fetch results, count rows...
Update
You said:
the fail is exactaly the same as the success, loader out and alert, but this time with a sad face on the alert
That's expected. success in the Ajax call just means that the server responded normally. It doesn't say anything about what is inside the json string. If you want to trigger the error Ajax callback, your server will need to set an error HTTP response code like this:
http_response_code(401);
echo json_encode(array('resp' => 'nope'));
Update 2
To find out the details of the error triggered by the Ajax call, modify the callback and examine the results:
error: function(jqXHR, textStatus, errorThrown){
console.log('textStatus: ' + textStatus);
console.log('errorThrown: ' + errorThrown);
}
Maybe your server is sending other content along with the JSON that is corrupting the output. Try closing the buffer at the top of your script, and exiting immediately with your echo:
<?php
ob_end_clean(); // at top of script
//try echoing this way
die(json_encode(array('resp' => 'nice')));
die(json_encode(array('resp' => 'nope')));
It would seem like there is either a problem in your config.php file, or with your sql statement
try putting your code into a try catch, and then returning the error as json:
<?php
header('Content-Type: application/json');
if (isset($_POST['cpf']) && isset($_POST['pass']) && $_POST['cpf'] != "" && $_POST['pass'] != "")
{
$cpf = $_POST['cpf'];
$passw = sha1(strrev(md5($_POST['pass'])));
try
{
include 'config.php';
$sql = "SELECT * FROM users WHERE cpf = :cp AND passwd = :pw";
$chec = $db->prepare($sql);
$chec->bindParam(':cp', $cpf, PDO::PARAM_STR);
$chec->bindParam(':pw', $passw, PDO::PARAM_STR);
$chec->execute();
if ($chec->rowCount() > 0)
{
echo json_encode(array('resp' => 'nice'));
}
else
{
echo json_encode(array('resp' => 'nope'));
}
}
catch(Exception $e)
{
echo json_encode($e->getMessage());
}
}
else
{
echo json_encode(array('resp' => 'fields'));
}
?>
Edit: incorporates #BeetleJuice's fix
I know I had already this question asked, but I'm doing something wrong in my code. I know that I need to use JSON, and after going through few pages I understand the theory, but somehow can't make it work here is my code once again (btw I know about my security issues and I'll work on them as soon as I solve my technical issues with JSON):
$(document).on('pageinit',function(){
$("#login").click(function(){
username=$("#usr").val();
password=$("#psw").val();
$.ajax({
type: "POST",
url: "http://imes.**********.com/php/login_check.php",
data: "name="+username+"&pwd="+password,
success: function(html){
//in case of success
if(html=='true')
{
var usr = console.log(data.usr);
var psw = console.log(data.psw);
$.cookie('usr', usr);
$.cookie('psw', psw);
$("#login_message").html("Logged in, congratulation.");
$.mobile.changePage("http://imes.**********.com/userpanel.php");
}
//in case of error
else
{
$("#login_message").html("Wrong username or password");
}
},
beforeSend: function() { $.mobile.showPageLoadingMsg(); }, //Show spinner
complete: function() { $.mobile.hidePageLoadingMsg() }, //Hide spinner
});
return false;
});
And my php:
<?php
session_start();
$username = $_POST['name'];
$password = $_POST['pwd'];
include('mysql_connection.php');
mysql_select_db("jzperson_imesUsers", $con);
$res1 = mysql_query("SELECT * FROM temp_login WHERE username='$username' AND password='$password'");
$num_row = mysql_num_rows($res1);
$res2 = mysql_fetch_array($res1);
if( $num_row == 1 ) {
$arr = array('usr' => $username, 'psw' => $password);
echo json_encode($arr);
echo 'true';
}
else{
echo 'false';
}
?>
Your out put is not valid json, echoing a true or false after the json will cause it to be invalid. You have to insert the success message into the json data.
if( $num_row == 1 ) {
$arr = array('usr' => $username, 'psw' => $password);
echo json_encode(array('data'=>$arr, 'success'=>true);
//echo 'true';
}
else{
echo json_encode(array('success'=>false);
}
then check in your ajax success callback
success: function(json){
//in case of success
if(json.success){
var usr = json.data.usr;
...
}
else{
...
}
Also you should pass your parameters to data as an object so it will be properly encoded.
data: {"name":username,"pwd":password},
Here's what I would do (PHP). First setup your response array, default to success FALSE.
$arr = array('success' => FALSE);
Then your condition overwrites if successful:
if( $num_row == 1 )
{
$arr = array('success' => TRUE, 'usr' => $username, 'psw' => $password);
}
Finally at the end of the script return the result as JSON encoded data.
echo json_encode($arr);
exit();
I would make the following change to your jQuery also:
$.ajax({
type: "POST",
url: "http://imes.**********.com/php/login_check.php",
data: "name="+username+"&pwd="+password,
dataType: 'json', // let's it know the response will be JSON formatted
success: function(json){
if (json.success === true){
// do whatever you want here
}
});
A bit of advice though: you should never pass a user's password to the front-end.There is no need for it, ever.
If it helps, JSON is basically the right-hande-side of a variable definition in JS:
var myvar = ....;
^^^^---- basically JSON
Since you're doing
echo json_encode($var);
echo 'true';
in your PHP code, consider how it'll look from the client side:
var myvar = 'somestring'true;
^^^^---syntax error
if you're outputting JSON for consumption by an AJAX call in your JS code, then the JSON text is the ONLY thing that can be output by the server as its response. Anything else will simply mangle the json string somehow, and make it invalid.
Ajax does not want to recognize my $google['cities'] when called as data.cities.
The output is: 12 undefined undefined.
It works well (output are database records) if i remove $google['number']=12, and define database array just as $google[]=$row.
Any ideas?
PHP:
<?php
$con = mysql_connect("localhost","root","");
if(!$con) {
die("Connection Error: ".mysql_error());
}
mysql_select_db("avtost", $con);
$pasteta = $_POST["white"];
$places = mysql_query("SELECT sDo FROM bstop WHERE sOd='$pasteta'");
mysql_close($con);
$google=array();
while ($row=mysql_fetch_array($places)) {
$google["cities"]=$row;
}
$google['number']=12;
if (mysql_num_rows($places)>0) {
echo json_encode($google);
} else { echo 'Ni rezultatov';}
?>
JQuery:
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
var white = $('#white').val();
$.ajax({
type:"POST",
url:"page.php",
dataType:'json',
data:{white:white},
success: function(data){
var result='';
$.each(data.cities, function(i,e) {
result += '<div>'+e.sDo+'</div>';
});
$("#res").append(data.number);
$("#res").append(result);
}
});
});
});
</script>
you are overwriting the cities key in $google every time you loop for a row in $places.
you can use:
while ($row=mysql_fetch_array($places)) {
$google[]=$row;
}
$google[]=12;
and then simply grab the last value value of the array if you want to get the number key, or just pass the number as a separate variable $number.
Some tips:
1) you should be using prepared statements to secure your code (mysqli prepared). This will give you something like:
// connect to database and check it
// ...
$stmt = $mysqli->prepare('SELECT sDo FROM bstop WHERE sOd=?');
$stmt->bind_param('s',$pasteta);
$stmt->bind_result($sDo);
$stmt->execute();
while($stmt->fetch())
$google['cities'][] = $sDo;
$google['number'] = 12;
$stmt->close();
$mysqli->close();
// ...
2) Improve your variable, table and column names. They are a bit confusing.
3) Instead of returning 'Ni rezultatov', you should return JSON. Such as, {"status":"FAILED"}, subsequently returning {"status":"OK", ... } for successful requests.
I solved it myself:
PHP:
while($row=mysql_fetch_array($places)){
$google['cities'][]=$row;
}
$google['number']=12;
echo json_encode($google);
I am creating a facebook like posting system..
My problem today is it doesn't seem to insert the value i get from the text area into my data base..
here is my java script:
$("#share").click(function()
{
//var typeNew = document.getElementById("content").value;
var update = $( "textarea#content" ).val();
//document.write(update);
if(update.length == 0)
{
alert("empty, please type something.");
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
}
else
{
//$("#flash").show();
$("#flash").html('<img src="loader.gif" />Loading Comment...').fadeIn("slow");
$.ajax({
type: "POST",
url: "post_update.php",
data: 'update=' + update,
success: function(msg)
{
$("#flash").ajaxComplete(function(event, request, settings){
//alert("Successfully Inserted")
$("#flash").hide();
//$(this).html('<meta http-equiv=\"Refresh\" content=\"1; URL=insert.php\">');
});
}
});
}
return false;
});
then here is my php code:
<?php
$post=$_REQUEST['update'];
$post=$_POST['update'];
//echo '$post';
# $db = new mysqli('localhost', 'root', '', 'wall');
if(mysqli_connect_errno())
{
echo "Error! Could not connect to database. Reset fields.";
exit;
}
$sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
$result = $db->query($sql);
if($result){
echo 'OK';
}
else{
echo 'FAIL';
}
$db->close();
?>
can someone tell me what's wrong?
it worked well when the delete function was in error but now that it's functional my share function does not work..
In your PHP code you have the following lines:
$post=$_REQUEST['update'];
$post=$_POST['update'];
You shouldn't have these both. In Your case, You actually need only the second one but for testing, try commenting it out leaving only the $_REQUEST line. Now you can pass parameters by GET too.
To see, if the query is correct, print it out too like this:
echo $sql = "INSERT INTO posts(update,date_posted) VALUES('$post',NOW())";
Now direct your browser to that location your.domain/post_update.php?update=testmessage and see the output.
If everything seems to be working, replace the POST/REQUEST lines with this:
$post=$db->real_escape_string($_POST["update"]);
I ran into this the other day. Use autocommit or start and commit transactions. Also, try a semicolon at the end of your statement (probably not the issue).
http://dev.mysql.com/doc/refman/5.0/en/commit.html
If your $post is coming out to be fine then try:
$post = $db->real_escape_string($_POST["update"]);
if (!db->query("INSERT INTO posts(update,date_posted) VALUES('$post' ,NOW())")) {
echo $db->sqlstate; //show error
}
else {
echo "inserted";
}
Assuming the column type of update is varchar / charand date_posted is datetime:
$sql = sprintf("INSERT INTO posts(update,date_posted) VALUES('%s',NOW())",
mysql_real_escape_string($post));
$result = $db->query($sql);
Please change the column name "update" to anyother. it may works. And Avoid some predefined varibales for column names.
Hope it helps.
I have some ajax code that executes on mouseclick. It calls a file called update.php that does a bunch of stuff, including checking for user permissions, numerous database calls, etc. In the end, I also want to be able to return a few variables from PHP for the callback to use, but not sure how to reference them - or if there's a better way to return this info.
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
success: callback
});
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text("[first variable here]");
$("div.numbert2").text("[second variable here]");
}
From my update.php file (some snippets):
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$value = GiveAccess($user);
// Email - function returns data to variable
$emaillist = emailAdmins($user);
} else {
$message = "Sorry you do not have access";
}
So I'd like to figure out how to use the variables $message, $value and $emaillist in my callback if possible.
I'm wondering if I just need to make multiple $.ajax POST calls, with each .php function that returns a variable having it's own call?
Thanks!
----UPDATE-------
Updated code trying to use the json methods - thanks for all the help - but seems I'm missing one last thing.
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'json',
success: callback
});
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text(data.value);
$("div.numbert2").text(data.emaillist);
and update.php:
$storage = array();
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$storage['value'] = "some user";
// Email - function returns data to variable
$storage['emaillist'] = "some stuff";
header('Content-type: application/json');
echo json_encode($storage);
exit(0);
Thanks again.
You can use a JSON wrapper:
$messages = array();
$messages['value'] = GiveAccess($user);
$messages['emaillist'] = emailAdmins($user);
$messages['message'] = "Sorry you do not have access";
echo json_encode($messages);
And then simply use:
data.value data.emaillist data.message
in your Javascript.
Easiest way would be to use JSON...
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType: 'json',
success: callback
});
function callback(data, status)
{
// $("div").text(data);
if(data.error){
alert(error.message||'Unknown Error');
} else {
$("div.numbert").text(data.access||'No value');
$("div.numbert2").text(data.emailList||'No value');
}
}
PHP:
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
$responseData = array();
// Give access - function returns data to variable
$responseData['access'] = GiveAccess($user);
// Email - function returns data to variable
$responseData['emailList'] = emailAdmins($user);
} else {
$responseData['error'] = array('code' => 403, 'message' => "Sorry you do not have access");
}
header('Content-type: application/json');
print json_encode($responseData);
exit(0);
No, just return a JSON object or a dataset that's delimited that you can parse.
You can return your values using json:
$storage = array();
if ($check_access > 0)
{
// Update database
$sql = "UPDATE db SET access = '1' WHERE user = '$user'";
$result = mysql_query($sql) or die(mysql_error());
// Give access - function returns data to variable
$value = GiveAccess($user);
$storage['value'] = $value;
// Email - function returns data to variable
$emaillist = emailAdmins($user);
$storage['emaillist'] = $emaillist;
} else {
$message = "Sorry you do not have access";
$storage['message'] = $message;
}
header("Content-Type: application/json; charset=utf8");
$return = json_encode($storage);
echo $return;
exit;
You can then iterate over the object and go
function callback(data, status)
{
// $("div").text(data);
$("div.numbert").text(data.value);
$("div.numbert2").text(data.emaillist);
}