I want php file to return data (from the database) on ajax call. Ajax call returns an error alert everytime. I tried everything, but have no idea how to return array from PHP to ajax call
So far, I made this..
ajax call
function dohvatiPrveTriAkcije(id){
var url = 'http://localhost/ljekarna/model/akcija.php';
$.ajax({
type: "POST",
url: url,
cache: false,
data: { "kategorija": id},
dataType: "json",
success: function (data) {
document.getElementById("kat_id").innerHTML += 'aaa';
},
error: function () {
alert('Pojavila se greška pri dohvacanju akcija za odabranu kategoriju');
}
});
return null;
}
php class
<?php
require_once 'baza_model.php';
$akcija = new Akcija();
if (isset($_GET['kategorija'])) {
echo $_GET['kategorija'];
$akcije = $akcija->dohvatiPrveTriAkcijeZaKategoriju($_GET['kategorija']);
echo $akcije;
}
class Akcija{
private $baza;
static function dohvatiPrveTriAkcijeZaKategoriju($kategorija){
$baza = new Baza();
$akcije = array();
$upit = 'SELECT lijek.naziv, akcija.postotak, akcija.datum_zavrsetka FROM akcija join lijek on akcija.lijek = lijek.id
join kategorija on lijek.kategorija = kategorija.id
where akcija.datum_zavrsetka > CURDATE() AND kategorija.id = ' . $kategorija . ' AND akcija.status = 1
ORDER BY akcija.datum_zavrsetka ASC LIMIT 3';
$rez = $baza->selectDB($upit);
while($red = $rez->fetch_assoc()){
echo "id: " . $red["id"];
$akcije[] = $red;
}
return $akcije;
}
}
I also tried this...
You need a json formatted string returned by the server. Use json_encode() instead of trying to echo out your array (which is what's giving you your array to string error).
Related
I'm trying to get result and alert it if the solicitude was successful or not on the PHP file, it worked (because changed the results) but the AJAX didn't show alerts (No error and no "true")
js:
function addentrys() {
var nwentry = {};
el = document.getElementById('addname').value;
eldmn = document.getElementById('adddomain').value;
nwentry.name = el;
nwentry.domain = eldmn;
$.ajax({
type: 'POST',
url: 'api/domain',
dataType: 'json',
data: nwentry
}).done(function(data) {
alert(data);
});
}
php:
$app->post('/domain', function () {
$jsonContents = file_get_contents('data/data.json');
$name = $_POST['name'];
$domain = $_POST['domain'];
$data = json_decode($jsonContents, true);
$last_item = end($data);
$last_item_id = $last_item['id'];
$data[] = array(
'name' => $name,
'domain' => $domain,
'id' => $last_item_id+1
);
$json = json_encode($data);
file_put_contents('data/data.json', $json);
return true;
});
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row.
Im trying to pass data from using Ajax and PHP on server side. the php file is not catching the data sent through Ajax.
the code gets the values with jquery and make a long string called data
the jquery code looks like this:
var data = 'ppemail=' + $('#email').val()
+ '&monto_enviar=' + montoEnviarDisp
+ '&monto_pub=' + montoPubDisp
+ '&tasa=' + tasaDisp
+ '&monto_recibir=' + monto_recibirDisp
+ '&banco=' + $('#banco').val()
+ '&receptor=' + $('#receptor').val()
+ '&cuenta=' + $('#cuenta').val()
+ '&cedula=' + $('#cedula').val();
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: ({data}),
success: function (response) {
alert(response);
}
});
the php file is this:
<?php
session_start();
require_once 'dbconfig3.php';
var_dump($_POST);
try {
$userID = $_SESSION['userSession'];
$ppemail = $_POST['ppemail'];
$monto_e = $_POST['monto_enviar'];
$monto_p = $_POST['monto_pub'];
$tasa = $_POST['tasa'];
$monto_rec = $_POST['monto_recibir'];
$banco = ($_POST['banco']);
$receptor = ($_POST['receptor']);
$cuenta = ($_POST['cuenta']);
$cedula = ($_POST['cedula']);
/// luego de confirmar hacer el try e insertar
//if(isset($_POST['btnferta'])){
//$password = md5($upass);
$bid_date = date('Y-m-d H:i:s');
$stmt = $db_con->prepare("INSERT INTO ofertas(uid,email_pp,nombre_receptor,banco_receptor,cuenta_receptor,cedula_receptor,monto_enviar,monto_publicar,tasa,monto_recibir,fecha)
VALUES(:userid, :emailpp, :nombre, :banco, :cuenta, :cedula, :monto_e, :monto_p, :tasa, :monto_r, :fecha)");
$stmt->bindParam(":userid", $userID);
$stmt->bindParam(":emailpp", $ppemail);
$stmt->bindParam(":nombre", $receptor);
$stmt->bindParam(":banco", $banco);
$stmt->bindParam(":cuenta", $cuenta);
$stmt->bindParam(":cedula", $cedula);
$stmt->bindParam(":monto_e", $monto_e);
$stmt->bindParam(":monto_p", $monto_p);
$stmt->bindParam(":tasa", $tasa);
$stmt->bindParam(":monto_r", $monto_rec);
$stmt->bindParam(":fecha", $bid_date);
$stmt->execute();
echo 'ok';
} catch (PDOException $ex) {
echo $ex->getMessage();
}
?>
why the $_POST is not getting any data? Thanks for the help!
You should set data to an object. This ensures that the URL parameters will be properly encoded; otherwise, you need to call encodeURIComponent on any parameter that could contain special characters.
var data = {
'ppemail': $('#email').val(),
'monto_enviar': montoEnviarDisp,
'monto_pub': montoPubDisp,
'tasa': tasaDisp,
'monto_recibir': monto_recibirDisp,
'banco': $('#banco').val(),
'receptor': $('#receptor').val(),
'cuenta': $('#cuenta').val(),
'cedula': $('#cedula').val()
};
Then you shouldn't wrap it in another object when calling $.ajax:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});
It looks like you're trying to pass a string as an object property. Change your $.ajax options:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});
I have 2 ajax calls one to insert data, one to get data. Together with the functions for select and insert. the console log of the ajax call select is empty. However, when i check phpmyadmin the correct value is there.
If i start the game again, there will be 1 value (from previous game) but the score of the actual game isn't there. Until I start the game again. And so on. Does anyone know why the values are in my sql but the ajax call says it's empty?
What I understand from it. There's a score via ajax and in php it will get into the part "Check json" it sees json isn't empty so it goes to InsertScore().
The second ajax is cast but this time it doesn't have json so it will get to the method "GetScores".
The insert happens always before the select so the last score should be seen, I don't understand why it doesn't do that.
Ajax call insert:
$.ajax({
type: "POST",
url: "Database.php",
dataType: "json",
data: { json: jsonData }
});
ajax call select:
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (obj) {
console.log(obj);
stageRef.$("txtTopscorePunt").html(obj[0].Score);
stageRef.$("txtTopscoreNaam1").html(obj[0].Naam);
stageRef.$("txtTopscorePunt2").html(obj[1].Score);
stageRef.$("txtTopscoreNaam2").html(obj[1].Naam);
stageRef.$("txtTopscorePunt3").html(obj[2].Score);
stageRef.$("txtTopscoreNaam3").html(obj[2].Naam);
}
});
php insert:
function InsertScore($obj) {
$query = "INSERT INTO topscoresNew (Score, Naam) VALUES('" . $obj['score'] . "','" . $obj['naam'] . "')";
$result = mysql_query($query);
}
php select:
function GetScores() {
$query = "SELECT * FROM topscoresNew ORDER BY Score DESC LIMIT 3";
$result = mysql_query($query);
$scoresArray = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$scoresArray[$i]['Score'] = $row['Score'];
$scoresArray[$i]['Naam'] = $row['Naam'];
$i++;
}
echo json_encode($scoresArray);
}
check json:
if (isset($_POST['json'])) {
$score = json_decode($_POST['json'], true);
InsertScore($score);
} else {
GetScores();
}
Make the ajax-calls synchronous:
$.ajax({
type: "POST",
url: "Database.php",
dataType: "json",
data: { json: jsonData },
async: false
});
This way the 'select'-call will wait for the 'insert'-call to finish.
I am trying to update and get the updated row at a time from database in ajax call
JS in ready function
$("button[name='teacher_lock_exam']").on(ace.click_event, function () {
var current_exams_id = $(this).attr('id');
bootbox.confirm("Are you sure you want to lock the exam? <br/><br/>" +
"Locked exam cannot be modified until exam committee unlock it.", function (result) {
if (result) {
lock_exam(current_exams_id);
bootbox.alert("Your Exam has been Locked !<br/><br/> Contact with Exam committee to modify that exam again.");
}
});
});
function lock_exam(current_exams_id) {
$.ajax({
url: "teacher_internal_exam_management/lock_exam/" + current_exams_id,
type: "POST",
dataType: "json",
success: function (row) {
alert('success');
alert(row[0].access_status);
}
});
}
My teacher_internal_exam_management controller
public function lock_exam($current_exams_id)
{
$this->load->model('teacher_internal_exam_management_model');
$this->teacher_internal_exam_management_model->lock_exam($current_exams_id);
echo (json_encode($this->teacher_internal_exam_management_model->get_exam_details($current_exams_id)));
}
My teacher_internal_exam_management_model Model
function lock_exam($current_exam_id, $data)
{
$this->db->query("update current_exams set access_status = 'locked' where current_exams_id='".$current_exam_id."'");
}
function get_exam_details($exam_id)
{
$query = $this->db->query("select * from current_exams
where
current_exams_id = '" . $exam_id . "'
");
return $query->result();
}
Now the ajax call is updating the data but the row is not returned by the echo in the controller.Means the success function of ajax is not running. Why this is not working? Is there any problem in the code?
The very last line of your model:
return $query->result();
http://ellislab.com/codeigniter/user-guide/database/results.html
This function returns the query result as an array of objects, or an empty array on failure.
This is returning an array of objects.
You have to convert it appropriately -
return $query->result_array();
According to the php manual at http://www.php.net/manual/en/class.mysqli-result.php, I do not see a result() method for the type mysqli_result. I think you need to use
return $query->fetch_all();
instead of
return $query->result();
I'm trying to send data from an html data attribute on a span element and receive it with Ajax and then process it with php and mysql and return the new value to my data attribute in html, but I'm getting a error that says "$.parseJSON unexpected character", can someone please look over my code to see if I'm processing the data correctly as I'm new to working with JSON.
HTML / PHP
<span data-object=
'{"art_id":"<?php echo $row['art_id'];?>",
"art_featured":"<?php echo $row['art_featured'];?>"}'
class="icon-small star-color"></span>
<!-- art_id and art_featured are both int and art_featured will be either 1 or 0 -->
jQuery / Ajax
$("span[class*='star']").on('click', function () {
var data = $.parseJSON($(this).data('object'));
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', JSON.stringify( data ));
});
});
PHP / mySQL
if($_POST['art_featured']==1) {
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 0 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 0);
echo json_encode($result);
}
else if($_POST['art_featured']==0){
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 1 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 1);
echo json_encode($result);
}
if(query($sql_articles)) {
}
else {
}
You don't need to use $.parseJSON, jQuery does that for you.
$("span[class*='star']").on('click', function () {
var data = $(this).data('object');
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', data);
});
});
You also don't need to stringify it later.