From a form (HTML), I send via AJAX a flag to indicate the action and a object that contains the information to save in PHP.
In the HTML file:
function Mandar_DATOS(QueHacer,OBJEvento){
// alert (OBJEvento.IdPaciente);
$.ajax({
type:'POST',
url:'./php/eventos.php?QueHacer='+QueHacer,
data:OBJEvento,success:function(msg){
if(msg){
.//mostrar en pantalla la informacion
}
},error:function(){
alert("No se guardo...");
}
});
}
in the PHP file (eventos.php)
$la_conexion = Conexion::ObtenConexion();
$QueHacer=(isset($_GET['QueHacer']))?$_GET['QueHacer']:'LEER';
switch ($QueHacer){
case 'GUARDAR':
$CadenaSQL=$la_conexion->prepare("INSERT INTO "
. "AgendaVideo(id, IdPaciente, IdMedico, title, start, end, color, textColor) "
. "VALUES(:id, :IdPaciente, :IdMedico, :title, :start, :end, :color, :textColor)");
$RESULTADO=$CadenaSQL->execute(array(
"id"=>$_POST['id'],
"IdPaciente"=>$_POST['IdPaciente'],
"IdMedico"=>$_POST['IdMedico'],
"title"=>$_POST['title'],
"start"=>$_POST['start'],
"end"=>$_POST['end'],
"color"=>$_POST['color'],
"textColor"=>$_POST['textColor']
));
echo json_encode($RESULTADO);
break;
case....
this code only returns false, but does not mark any error
If you want to return an error you need to call a method/function to output the error. Here below between the comments I'm using https://www.php.net/manual/en/pdo.errorinfo.php which just returns the error related to the last sql statement that has been run
$la_conexion = Conexion::ObtenConexion();
$QueHacer=(isset($_GET['QueHacer']))?$_GET['QueHacer']:'LEER';
switch ($QueHacer){
case 'GUARDAR':
$CadenaSQL=$la_conexion->prepare("INSERT INTO "
. "AgendaVideo(id, IdPaciente, IdMedico, title, start, end, color, textColor) "
. "VALUES(:id, :IdPaciente, :IdMedico, :title, :start, :end, :color, :textColor)");
//start error handling code
if (!$CadenaSQL) {
echo "\nPDO::errorInfo():\n";
print_r($la_conexion->errorInfo());
}
//end error handling code
$RESULTADO=$CadenaSQL->execute(array(
"id"=>$_POST['id'],
"IdPaciente"=>$_POST['IdPaciente'],
"IdMedico"=>$_POST['IdMedico'],
"title"=>$_POST['title'],
"start"=>$_POST['start'],
"end"=>$_POST['end'],
"color"=>$_POST['color'],
"textColor"=>$_POST['textColor']
));
//start error handling code
if (!$RESULTADO) {
echo "\nPDO::errorInfo():\n";
print_r($la_conexion->errorInfo());
}
//end error handling code
echo json_encode($RESULTADO);
break;
case....
Related
I have a react app that makes a post request to the following code.
<?php
require_once('dbSURL.php');
$stm = $db->prepare("INSERT INTO urlshortener (longUrl, shortId, userIp, userCountry, userCity, userOS, userAgent, createDate) VALUES (:longUrl, :shortId, :userIp, :userCountry, :userCity, :userOS, :userAgent, :createDate)");
$stm->bindParam(':longUrl', $_POST['longUrl']);
$stm->bindParam(':shortId', $_POST['shortId']);
$stm->bindParam(':userIp', $_POST['userIp']);
$stm->bindParam(':userCountry', $_POST['userCountry']);
$stm->bindParam(':userCity', $_POST['userCity']);
$stm->bindParam(':userOS', $_POST['userOS']);
$stm->bindParam(':userAgent', $_POST['userAgent']);
$stm->bindParam(':createDate', $_POST['createDate']);
if ($stm->execute()) {
echo "success";
} else {
echo "failure: ".$stm->errorInfo()[2];
};
// $stm->execute();
// echo 'Error: %s.\n', $stm->errorCode(), $stm->errorInfo();
?>
After checking the request from dev tools I can see that the data are sent but when I get the data from the database all the fields are null.
Any help?
I have a page that makes an Ajax call, which retrieves, JSON encodes and returns data from a database. The page was working, but in the midst of making some changes, it's now failing. (Should note that I'm working with a test site and test database as I make the changes.)
The errorThrown parameter of the error case shows me "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data."
Here's the function with the Ajax call. (I've enhanced what's in the alerts for debugging purposes. I'll rip that back out once things are working.)
function acceptConfCode(){
var emailAddr = $('#email').val();
var confCode = $('#confcode').val();
var fnargs = "ConfirmCode|'" + emailAddr + "'," + confCode ;
$.ajax({
url: 'retrievedata.php',
type: "POST",
async: true,
data: {"functionname":"confirmcode","arguments":fnargs},
dataType: "JSON",
success: function (obj) {
if (!obj.error) {
$('#logininfo').hide();
$('#emailrow').hide();
$('#coderow').hide();
$('#reviewactions').show();
updateListOfActions(obj);
}
else {
success = false;
alert("The confirmation code you entered didn't match or has expired. Please try again. Type 1");
}
},
error: function(xhr, textStatus, errorThrown) {
success = false;
alert("The confirmation code you entered didn't match or has expired. Please try again. Type 2. textStatus = " + textStatus + "; errorThrown = " + errorThrown);
}
});
};
The retrievedata PHP page is mostly a CASE statement. The relevant case is this (again with added debugging code):
case 'confirmcode':
if ($argcount <2) {
$returnval = 'too few arguments';
}
else {
$returnval = confirmcode($argsarray[0], $argsarray[1]);
echo "Back from confirmcode\r\n";
var_dump($returnval);
}
break;
At the end of the page, it returns $returnval.
The key action is in the confirmcode function, which runs a MySQL SP to confirm that the user has a valid email and code, and then calls another function to retrieve the actual data. Here's confirmcode. As the commented out pieces show, I've checked results along the way and I am getting what I expect and it's getting JSON encoded; I've ran the encoded JSON back through JSON_decode() in testing to confirm it was decodable.
function confirmcode($spname, $params, $errorstring = 'Unable to send requested data') {
$conn = connect2db();
$query = "SELECT ".$spname."(".$params.") as result";
//echo $query."\r\n";
$result = mysqli_query($conn, $query);
$allresult = "unknown";
if (!$result) {
$errmessage = mysqli_error($conn);
$allresult = $errmessage;
$allresult = json_encode($allresult);
//echo $errmessage;
die( print_r( mysql_error(), true));
}
else {
//echo "In else case\r\n";
//retrieve list of action submissions
$resultobj = mysqli_fetch_object($result);
if ($resultobj->result == 1) {
//echo "In success subcase\r\n";
$allresult = getsubmissions($conn);
//echo "After getsubmissions\r\n";
//print_r($allresult);
}
else {
//echo "In failure subcase\r\n";
$result = array('error'=>true);
$allresult = $result;
}
//echo "Before JSON encode\r\n";
$finalresult = json_encode($allresult);
//echo "After JSON encode\r\n";
//echo json_last_error_msg()."\r\n";
//var_dump($finalresult);
$allresult = $finalresult;
return $allresult;
}
}
Finally, here's getsubmissions, again with some debugging code:
function getsubmissions($conn) {
echo "In getsubmissions\r\n";
$query = "CALL GetSubmissions()";
$submissions = mysqli_query($conn, $query);
if (!$submissions) {
echo "In failure case\r\n";
$errmessage = mysqli_error($conn);
$allresult = $errmessage;
$allresult = json_encode($allresult);
echo $errmessage;
die( print_r( mysql_error(), true));
}
else {
echo "In success case\r\n";
$rows = array();
while ($row = mysqli_fetch_assoc($submissions)) {
$rows[] = $row;
}
$allresult = $rows; //json_encode($rows);
}
//print_r( $allresult);
return $allresult;
}
What's really weird is I have another page in the site that retrieves almost exactly the same data through an Ajax call with no problem. The one that works contains a few additional fields, and doesn't contain two date fields that are in this result.
In addition, the live version of the site retrieves exactly the same data as here, except from the live database rather than the test database, and it works. While this version of the code has some additional things in it, the only differences in the relevant portions are the debugging items. (That is, I've made changes, but not in the part I'm showing here.) That leads me to think this may be an issue with the test data rather than with the code, but then why does the other page work in the test site?
UPDATE: To try to see whether this is a data problem, I cut the test data way down so that it's only returning a couple of records. I grabbed the generated JSON and ran it through JSONLint.COM and it says it's valid.
UPDATE 2: With the reduced data set, here's the string that's returned from retrievedata.php to the Ajax call:
[{"ActionSource":"https:\/\/www.voterheads.com\/","ActionSourceName":"Wall-of-us","Title":"Sign up to get notified about local meetings","Description":"Sign up at www.voterheads.com to get notified about local meetings. When we did, using the free option, this is what happened: a page popped up with a list of municipality meetings in the zip code we entered. We clicked on one of the meetings, and presto! -- instant access to the date, time, location, and agenda of the meeting. Pretty awesome.","StartDate":null,"EndDate":null,"UrgencyDesc":"Anytime","UrgencyColor":"#00FF00","UrgOrder":"5","DurationDesc":"Ongoing","DurOrder":"6","CostDesc":"Free","CostOrder":"1","Issues":"Advocacy","Types":"Learn","States":"ALL","iID":"20"},{"ActionSource":"https:\/\/actionnetwork.org\/forms\/ctrl-alt-right-delete-newsletter-2","ActionSourceName":"Ctrl Alt Right Delete","Title":"Sign up to learn what the \"alt-right\" is up to","Description":"Understand how the right operates online. Sign up for a weekly newsletter.","StartDate":null,"EndDate":null,"UrgencyDesc":"Anytime","UrgencyColor":"#00FF00","UrgOrder":"5","DurationDesc":"An hour or less","DurOrder":"2","CostDesc":"Free","CostOrder":"1","Issues":"Advocacy","Types":"Learn","States":"ALL","iID":"25"}]
As noted above, JSONLint.COM says it's valid JSON.
I've found a solution, though I'm just starting to understand why it works. On retrievedata.php, I uncommented:
echo $returnval;
just before the Return statement and it's working again. So I think the issue is that since retrievedata is a page, but not a function, the return statement didn't actually return anything. I needed code to actually return the JSON-encoded string.
Here is my ajax code.
I cannot see any error in my code, but AJAX doesn't work.
It doesn't return anything from that page...
function addCash(){
var cash =$('#cash_amount').val();
var date =$('#cash_date').val();
var debiter =$('#debiter').val();
if(cash == '' || date =='' ){
alert("Please Fill All Fields");
}
else{
$.ajax({
type: 'POST',
dataType:'JSON',
url: 'getCustomers.php',
data: 'type=cash_received&cash='+cash+'&date='+date+'& debiter='+debiter,
success:function(data){
console.log(data);
alert("Cash Added Successfully");
}
});
}
}
PHP Code "getCustomers.php"...inside a function using ajax is an issue?
$cash= $_REQUEST['cash'];
$date= $_REQUEST['date'];
$debiter= $_REQUEST['debiter'];
$query="INSERT INTO `received_payment`(`debiter`, `amount`, `date`) VALUES ('".$debiter."', '".$cash."', '".$date."')";
$result = $mysqli->query($query) or ($error=$mysqli->error.LINE);
$arr = array();
if(!$result){
$arr['result'] = isset($error) ? $error : 'error';
}
else{
$arr['result'] ="ok";
}
$json_response = json_encode($arr);
ob_clean();
echo $json_response;`
Because, you are using die anf if your query fails then your script will die and hence no response will be made. So change the below line,
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
to
$result = $mysqli->query($query) or ($error=$mysqli->error.__LINE__);
and you can return this error in response like,
if(!$result){
$arr['result'] = isset($error) ? $error : 'error';
}
Also in your insert query, fields and their values are not matching, you should use it like,
$query="INSERT INTO `received_payment` (`debiter`, `amount`, `date`)
VALUES ('".$debiter."', ".$cash."', '".$date."')";
And try to pass data from AJAX (you have space before debiter key in your data string) like,
data: {type:'cash_received',cash:cash,date:date,debiter:debiter},
An extra comma in INSERT query.
$query="INSERT INTO `received_payment`(`debiter`, `amount`, `date`,) VALUES ('".$cash."', '".$date."', '".$debiter."')";
Change to:
$query="INSERT INTO `received_payment`(`debiter`, `amount`, `date`) VALUES ('".$cash."', '".$date."', '".$debiter."')";
It is giving an error actually, but since you gave die() the code is getting exited. So you are not getting anything from Server.
in AJAX request you have mentioned accept only JSON data content. So in some case it may happens server returns response with Warning and Error if PHP error is on.
So in server side PHP script before echo response in json format you can use ob_clean() for flushing all unexpected output which is sent by error or warning.
$json_response = json_encode($arr);
ob_clean();
echo $json_response;
Please remove quotes at the end of the line
echo $json_response;`
I have sendlike.php that handled liking, and works so far!
<?php
//include db configuration file
include_once("config.php");
//Include functions
include_once("functions.php");
// http://stackoverflow.com/questions/21065502/ajax-a-href-onclick-get-php-variable-and-execute-php-file
// For practice
$uid_fk = 1;
//check $_POST["content_txt"] is not empty
if(isset($_GET["like"]) && strlen($_GET["like"])>0)
{
//Add IP, date. Set the Foreign key
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("Y-m-d H:i:s");
$comment_id_fk = $_GET["like"]; // '".$comment_id_fk."', What comment has been liked?
// $_SESSION["user_id"] '".$uid_fk."', What user has liked it? Get the users uid
// Insert sanitize string in record
$insert_row = $mysqli->query("INSERT INTO comment_likes (comment_id_fk, uid_fk,date,ip)
VALUES('".$comment_id_fk."','".$uid_fk."','".$date."','".$ip."')");
if($insert_row)
{
//Count the amount of likes again
$count_likes=$mysqli->query("SELECT COUNT(*) as TOTAL_COMMENT_LIKES FROM `comment_likes`
WHERE comment_id_fk='".$comment_id_fk."'");
$row_array=$count_likes->fetch_array(MYSQLI_ASSOC);
//Record was successfully inserted, respond result back to index page
// This should probably in the fute go thruh functions.php comment_func_bar
$my_id = $mysqli->insert_id; //Get ID of last inserted row from MySQL. Will this cause problems when alot of ppl liking / posting / commenting etc??
echo '' . $row_array['TOTAL_COMMENT_LIKES'] .' Unlike';
$mysqli->close(); //close db connection
}else{
//header('HTTP/1.1 500 '.mysql_error()); //display sql errors.. must not output sql errors in live mode.
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}
}
elseif(isset($_GET["delike"]) && strlen($_GET["delike"])>0 && is_numeric($_GET["delike"]))
{ //do we have a delete request? $_POST["recordToDelete"]
//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete = filter_var($_GET["delike"],FILTER_SANITIZE_NUMBER_INT);
//try deleting record using the record ID we received from POST
$delete_row = $mysqli->query("DELETE FROM comment_likes WHERE comment_id_fk='".$idToDelete."' AND uid_fk ='".$uid_fk."'"); //uid_fk is $_SESSION[user_id] actually
if(!$delete_row)
{
//If mysql delete query was unsuccessful, output error
header('HTTP/1.1 500 Could not delete record!');
exit();
}
$mysqli->close(); //close db connection
}
else
{
//Output error
header('HTTP/1.1 500 Error occurred, Could not process request!');
exit();
}
?>
If you have a look at the echoing line, the class of the href is class="clickable". and sandlike.php has changed to delike.
I'am not able to do a AJAX script that will send the and update the "clickable" href to <a href="sendlike.php?delike='.$comment_id_fk.'" class="clickable">' . $row_array['TOTAL_COMMENT_LIKES'] .' Unlike'
This is asfar i have come
<script type="text/javascript">
$('.clickable').on('click', function() {
var data = {
mode: "like",
rating: $(this).data('rating'),
id: $(this).data('id')
};
$.ajax({
type: 'GET',
url: 'sendlike.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
</script>
And is not even close to work.
And how about the class="clickable", i have multipel comments on page. Will all get liked/deliked. Or do i need something like class="item_$number_clickable" ?
Thanks in advance!
Add event.preventDefault() and delegate the event to the static parent:
$(document).on('click', '.clickable', function(e) {
e.preventDefault(); // to stop the page navigation
I want to send geographic data (latitude & longitude) to a mySQL database with Ajax call and PHP script. Both Ajax and PHP scripts look ok for me but nothing goes to the database. I've try different syntax and option (like PDO with array) to manage MySQL but still nothing... Do you have an idea of what is going wrong ?
Thank you very much for your help,
Flo.
The Jquery code of my Html page is simple :
function getCoordPosition(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajaxSetup({
url: "insert-in-bdd.php",
type: "POST",
});
$.ajax({
data: 'latitude='+latitude+'&longitude='+longitude,
success: function (msg) {
alert (msg);},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('Error submitting request.');
}
});
});
}
}
The first PHP script I try (insert-in-bdd.php) is:
<?php
header('Content-type: text/html; charset=ISO-8859-1');
try
{
if(isset($_POST['latitude']) && isset($_POST['longitude'])){
$latitude = ($_POST['latitude']);
$longitude = ($_POST['longitude']);
$db = mysql_connect(localhost, root, "");
$select = mysql_select_db(madb, $db);
mysql_query('INSERT INTO location (lat,lng)
VALUES (:longitude, :longitude)');
}}
catch(Exception $e)
{
echo 'Erreur : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
}
?>
The second PHP script I try (with PDO and array), same name : insert-in-bdd.php is:
<?php
header('Content-type: text/html; charset=ISO-8859-1');
try
{
if(isset($_POST['latitude']) && isset($_POST['longitude'])){
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host=localhost;dbname=madb', 'root', '');
$req = $bdd->prepare('INSERT INTO location(lat, lng) VALUES(:lat, :lng)');
//$req = $bdd->prepare('UPDATE location SET lat = :lat');
$req->execute(array(
'lat' => $_POST['latitude'],
'lng' => $_POST['longitude']
));
}}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
?>
I would do:
$query="insert into location (lat,long) values('".$_POST['latitude']."','".$_POST['longitude']."');";
mysql_query($query,$connection);
You seem to have forgotten the connection from the mysql_query(), and I'm not sure about using :latitude etc.
For your first code block try the following for the mysql query:
"INSERT INTO location (lat,lng) VALUES ('" . $latitude . "', '" . $longitude . "')"
Also, it's very important to clean up your data before inserting into the database - this kind of code leaves you open to sql injection.
You should use the function mysql_real_escape_string around your variables. You can either put it in when you assign the post variables to the $longitude and $latitude, or in the query itself.
You need to have a mysql connection available when you call the function.