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;`
Related
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....
I have read through many similar questions and had a look at many ajax php tutorials. But I still cannot find for what reason my array is unable to be passed to my PHP.
I post my JS array here:
function passName() {
$.ajax(
{
type: 'POST',
url: 'eDBase.php',
data: 'array=' + arrays,
success: function(){
}
});
}
Where the data is recieved in PHP through:
$arrays = $_POST(['passed'],true);
if ($arrays !== "") {
echo($arrays);
}
$arraypass = "INSERT INTO clientinfo(first_name, last_name, emails)
VALUES($arrays[1],$arrays[2],$arrays[3])";
if($conn->query($arraypass === true)){
echo'Candidate has been added';
}
else{
echo 'Error thrown while adding candidate to database';
}
mysqli_close($conn);
In my PHP preview I get this error thrown:
https://gyazo.com/57f7faa9ee0869f56f031112b33d29b6
Full code is here:
PHP: https://codeshare.io/50NQjL
HTML: https://codeshare.io/ax1POd
Thanks guys I've been stuck on this issue for about a week now just can't seem to see the problem.
(My PHP code is taking this array and the data from it and then placing it into the database)
EDIT: Code causing error while trying to add to database:
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$email = $_POST['email'];
$arraypass = "INSERT INTO clientinfo(first_name, last_name, emails)
VALUES($fname,$lname,$email)";
if($conn->query($arraypass === true)){
echo'Candidate has been added';
}
else{
echo 'Error thrown while adding candidate to database';
}
mysqli_close($conn);
I understand that similar general questions exist, but none of them follow my specific set of circumstances, and none of them really provide a solution.
Inside the same folder on the server, I have two files: "quiz_maker.php"
and "master_data.php."
I send a JSON object to "master_data.php" from "quiz_maker.php" with the following Ajax code:
if(localStorage.getItem("JSON Question Data Object") != null){
//The JSON object was stringified before saving to localStorage.
var dataString = localStorage.getItem("JSON Question Data Object");
$.ajax({
method: "POST",
url: "master_data.php",
data: { jsonDataObject: dataString },
success: function(msg){
console.log(msg + "\n");
}
});
}
Then, in "master_data.php", I receive it as follows:
if(isset($_POST['jsonDataObject'])){
echo "set";
$masterQuestionData = $_POST['jsonDataObject'];
$masterQuestionData = json_decode($masterQuestionData, TRUE);
//Perform MySQL Queries here.
}
else{
echo "not set";
}
When I run the code on "quiz_maker.php", the Ajax success handler fires, and I receive the string "set" in the console as I would expect. However, if I look at the "master_data.php" file, the string "not set" gets echoed out, and the following notice is displayed:
Notice: Undefined index: `jsonDataObject` in
/home/sites/5a/0/03891393e8/public_html/master_data.php on line 35
Furthermore, all the MySQL queries execute perfectly using the allegedly "undefined index" "jsonDataObject".
What would be the reason why Ajax's success handler fires, gives me the string "set" and all of the queries work, but I get an undefined index notice on master_data.php?
Thank you.
As requested, here is the whole master_data.php file:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
$booleanSuccessfulOne = false;
$booleanSuccessfulTwo = false;
$servername = "[REDACTED]";
$username = "[REDACTED]";
$password = "[REDACTED]";
// Create connection
$link = mysqli_connect($servername, $username, $password, $username);
// Check connection
if (mysqli_connect_error()) {
$alert = "Oops! We're having trouble publishing your questions and
answers right now. Please try again later.";
die($alert);
}
if(isset($_POST['jsonDataObject'])){
echo "set";
$masterQuestionData = $_POST['jsonDataObject'];
// Unescape the string values in the JSON array
$masterQuestionData = $_POST['jsonDataObject'];
// Decode the JSON array
$masterQuestionData = json_decode($masterQuestionData, TRUE);
$maxQuestions = $masterQuestionData["statistics"][0]["totalQuestions"];
for($i = 1; $i <= $maxQuestions; $i++){
$question = $masterQuestionData["block"][$i-1]["question"];
$answer = $masterQuestionData["block"][$i-1]["answer"];
$query = "INSERT INTO `master` (`id`, `question`, `solution`)
VALUES('".$i."', '".$question."', '".$answer."') ON DUPLICATE KEY
UPDATE `id` = '".$i."', `question` = '".$question."', `solution` =
'".$answer."'";
mysqli_query($link, $query);
}
$query = "DELETE FROM `master` WHERE `id` > '".$maxQuestions."'";
mysqli_query($link, $query);
}
else{
echo "not set";
}
There shouldn't be spaces in the item key for localstorage. The rest of my suggestions are in the chat comments.
localStorage.getItem("JSON Question Data Object");
Can you try the following below and let us know what happens? Change all of your getItem() and setItem() to have no spaces.
localStorage.getItem("JSON");
I believe it should fix up this issue because the rest of your ajax & php looks fine.
That said, you can use bracket notation if you want
localStorage['JSON Question Data Object']
I am trying to retrieve data from a PHP file the reads a mySQL db. The data comes in fine on a browser:
http://www.primaryaccess.org/REST/geteasyfile.php?id=25
But when I try to access it using jQuery's get() or post() methods, I get no response. The response header in Firebug says there is the right amount of data, but nothing shows up:
$.get("http://www.primaryaccess.org/REST/geteasyfile.php?id=25",function(data) { alert(data); });
Here's the PHP:
<?
$id=$_GET['id'];
$query="SELECT * FROM easyfile WHERE id = '$id'";
$result=mysql_query($query);
mysql_close();
if (($result == false) || (!mysql_numrows($result)))
echo "Can't load file!";
else
echo mysql_result($result,0,"data");
?>
Thanks!
Bill
Try getJSON and replace alert() with console.log(). Additionally, your URL looks strange ('id=25' + id). I hope you also noticed that there is a Same Origin Policy in JS, so you need to upload your testfile to the specified domain.
probably your problem is in the url, you already setted id=25 and then you concatenate the id variable
Hope this help
Try using a json callback
JS
$.ajax({
url: "http://www.primaryaccess.org/REST/geteasyfile.php?id=25&jsoncallback=?",
success: function(data) {
alert(data)
},
error: function(error){
alert(JSON.stringify(error));
}
});
PHP
<?
$id=$_GET['id'];
$query="SELECT * FROM easyfile WHERE id = '$id'";
$result=mysql_query($query);
mysql_close();
if (($result == false) || (!mysql_numrows($result)))
$result = "Can't load file!";
else
$result = mysql_result($result,0,"data");
$result = array('result' => $result);
echo $_GET['jsoncallback'] . '(' . json_encode($result) . ');'
?>
I have seen many other posts like this, but I cannot see anything I have done wrong. I also read it could be a problem with the hosting (Heroku) so I have created a ticket, but no answer after 3 days.
Below is the code which sends the info:
(discuss.php)
<script type="text/javascript">
$(function() {
$('#ideasubmit').click(function() {
console.log();
$('#ideacontainer').append('<img src="images/loading.gif" alt="Please Wait" id="idealoading" />');
var ideatitle = $('#ideatitle').val();
var ideafbid = $('#ideafbid').val();
var idea = $('#idea').val();
$.ajax({
url: 'ajaxsqli.php',
type: 'POST',
data: 'ideatitle=' + ideatitle + '&ideafbid=' + ideafbid + '&idea=' + idea,
success: function(result) {
$('#idearesponse').remove();
$('#ideacontainer').append('<p id="idearesponse">' + result + '</p>');
$('#idealoading').fadeOut(500, function() {
$(this).remove();
});
}
});
return false;
});
});
Below here is the code file which gets the error when it sent the info:
(ajaxsqli.php)
$db = new db;
$query = "INSERT into comments(user_fbid, discuss_type, discuss_post_title, discuss_post, date) VALUES (?, ?, ?, ?, )";
$stmt = $db->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param('iissi', $_POST['ideafbid'], 1, $_POST['ideatitle'], $_POST['idea'], date('Ymd'));
$stmt->execute();
}
if($stmt) {
echo "Thank you. We'll be in touch with you shortly!";
} else {
echo "There was a problem. Please try again later.";
}
?>
Whats odd is I had it working 3 days ago, and I went to improve some of the code and now I am unable to make it work, even if I restore the back up.
This is the full error message:
Failed to load resource: the server responded with a status of 500 (Internal Server Error) and points to ajaxsqli.php
Using Chrome Inspect Elements I can see the POST is posting the information, but no response information.
Is there anything wrong with this code ?
A 500 error usually refers to a problem in the php. Load ajaxsqli.php in the browser with the paramaters (change $_POST to $_REQUEST and then you can use the querystring. EG
$db = new db;
$query = "INSERT into comments(user_fbid, discuss_type, discuss_post_title, discuss_post, date) VALUES (?, ?, ?, ?, )";
$stmt = $db->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param('iissi', $_REQUEST['ideafbid'], 1, $_REQUEST['ideatitle'], $_REQUEST['idea'], date('Ymd'));
$stmt->execute();
}
if($stmt) {
echo "Thank you. We'll be in touch with you shortly!";
} else {
echo "There was a problem. Please try again later.";
}
?>
Then go to http://yourhost/ajaxsqli.php?ideafbid=data&ideatitle=data&idea=data and see what the PHP error is