AJAX throws error 500 only when PHP function is empty - php

I'm completely puzzled to why this happens, I've been messing on this for a few hours and I'm going crazyyyy! I am trying to update my DB when a checkbox is toggled on or off. The success response works if my PHP function I'm calling is empty, but fails whenever I add PHP. Note I'm on Laravel 3, and I've tried enabling or disabling CSRF filtering, no luck.
My JS:
$seenTD = $('td.seen_by_user');
$seenTD.each(function() {
$this = $(this);
var $seenLabel = $this.find('label');
var $seenInput = $this.find(':checkbox');
$seenInput.change(function() {
var _csrf = $('input[name="csrf_token"]').val();
var chkName = $(this).attr('name');
var checkVal = $(':checkbox[name='+chkName+']').prop('checked'); //true or false
var id = $this.find('input[name="reminder_id"]').val();
$.ajax({
url: 'update',
type: 'POST',
data: 'seen='+checkVal+'&reminder_id='+id+'&csrf_token='+_csrf,
success: function(data) {
console.log(data);
if($seenInput.is(':checked')) {
$seenLabel.removeClass('unchecked').addClass('checked');
$seenLabel.find('span').text('Oui');
}
else {
$seenLabel.removeClass('checked').addClass('unchecked');
$seenLabel.find('span').text('Non');
}
}
});
});
});
My PHP
public function post_update() {
$request = Request::instance();
$content = $request->getContent();
$id = $content['id'];
$seen = $content['seen'];
if($seen == 'true') {
$seen = 1;
}
if($seen == 'false') {
$seen = 0;
}
DB::table('reminders')->where('id', '=', $id)->update(
array(
'seen_by_user' => $seen
));
}

For the sake of maybe helping someone, as this is my first working AJAX, I'll explain how I got it to work, as well as supply working code. I'm not claiming this is the best way to do it, so if anyone has their word to say, don't hesitate :)
There were multiple issues, from Javascript insconsistency returning the row ID I needed for the database update, to the PHP function, and the way I was grabbing the POST data.
To get it to work, I played on Fiddler, retrieved the error message that Laravel throws at me. And I could debug from there :)
My working code is :
JS:
$('td.seen_by_user :checkbox').change(function() {
$this = $(this);
var $label = $this.siblings('label');
var id = $this.attr('data-id');
var _csrf = $this.siblings('input[name="csrf_token"]').val();
var value = $this.prop('checked');
$.ajax({
url: 'update',
type: 'POST',
data: {"seen_by_user": value, "id": id, "csrf_token": _csrf},
success: function(data) {
if($this.is(':checked')) {
$label.removeClass('unchecked').addClass('checked');
$label.find('span').text('Oui');
}
else {
$label.removeClass('checked').addClass('unchecked');
$label.find('span').text('Non');
}
}
});
});
PHP
function post_update() {
$id = $_POST['id'];
$seen = $_POST['seen_by_user'];
if($seen == 'true') {
$seen = 1;
}
if($seen == 'false') {
$seen = 0;
}
$update_reminder = DB::table('reminders')->where('id', '=', $id)->update(
array('seen_by_user' => $seen));
}
And my HTML (Blade Template from Laravel, where {{ }} brackets are simply echo's, and #foreach is a )
#foreach ($reminders as $reminder)
...
<td class="seen_by_user">
<form class="ajax" action="update" method="POST">
{{ Form::token() }}
{{ Form::checkbox('seen_'.$reminder->id, 1, $reminder->seen_by_user, array('id' => 'seen_'.$reminder->id, 'data-id' => $reminder->id)) }}
<label class="seen {{ ($reminder->seen_by_user == 1 ? 'checked' : 'unchecked' ) }}"for="{{ 'seen_'.$reminder->id }}"><i class="read"></i><span>{{ ($reminder->seen_by_user == 1 ? 'Oui' : 'Non') }}</span></label>
</form>
</td>
...
#endforeach

data should be an object like this
data: {"seen": checkVal, "reminder_id": id, "csrf_token": _csrf},
The $.ajax method will take care of the presentation and transmission.

Related

Return JSON Data from PHP and Ajax

In my web application just I trying to returning JSON data from MySQL database using PHP and AJAX query. This is where I follow a tutorial on internet. In case in my application it shows and error like;
data = "↵↵↵↵Notice: Undefined index: lymph in
C:\xampp\htdocs\Hospital\hospitalwebsite\test_query\fetch_count.php
on line 29
Here is my AJAX Code :-
<script>
$(document).ready(function () {
$('select').material_select();
$('#search').click(function () {
var id = $('#test_list').val();
if (id != '') {
$.ajax({
url: 'test_query/fetch_count.php', // Url to which the request is send
method: 'POST', // Type of request to be send, called as method
data: { id: id },
//dataType:"JSON",
success: function (data) {
$('#success_mes').fadeIn().html(data);
$('#test_info').css('display', 'block');
$('#1').text(data.WBC);
$('#2').text(data.lymph);
$('#3').text(data.Mid);
}
});
} else {
alert('sdsd');
$('#test_info').css('display', 'none');
}
});
});
</script>
Below is the PHP Code :-
<?php
session_start();
require_once "../phpquery/dbconnection.php";
if (isset($_POST['id'])) {
//$id = $_POST['id'];
$stmt = $con->prepare("SELECT * FROM testing_report WHERE testing_report_id = ? AND test_id='7' ");
$stmt->bind_param("s", $_POST['id']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0);
while ($row = $result->fetch_assoc()) {
$medRecords = json_decode($row['testing_results'], true);
if (is_array($medRecords) || is_object($medRecords)) {
foreach ($medRecords as $key => $object) {
$data["WBC"] = $object['WBC'];
$data["lymph"] = $object['lymph'];
$data["Mid"] = $object['Mid'];
}
}
}
echo json_encode($data);
}
?>
SQL schema
Really I am appreciating if someone can help me. Thank you
The issue is that your data structure is split over several array elements, something like...
[
{
"WBC": "1"
},
{
"lymph": "5"
}
]
so each loop round the array only has 1 piece of information. This code combines all of that data into 1 set of information using array_merge() and then extracts the data from the result.
I've also added ?? 0 to default the values to 0 if not present, there may be a better default value.
$data = [];
$medRecords = json_decode($row['testing_results'], true);
if (is_array($medRecords) || is_object($medRecords)) {
$medRecords = array_merge(...$medRecords);
$data["WBC"] = $medRecords['WBC'] ?? 0;
$data["lymph"] = $medRecords['lymph'] ?? 0;
$data["Mid"] = $medRecords['Mid'] ?? 0;
}
JQuery work file if the result be json:
$(document).ready(function(){
$('#search').click( function () {
$.ajax({
url: "https://reqres.in/api/users?page=2",
method: "GET",
success:function(data)
{
console.log("page:", data.page);
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="search">Search</button>
i think you have to add correct header to your result:
<?php
header('Content-Type: application/json');
add this code into first line of your php page. then jQuery know result is json.

Queing notification in PHP using AJAX with beep sound

I am building now a Queuing system for my helpdesk system. i have problem in detecting the changes of input value. I want to play the play_sound() function sound when the value of input is incremented. the curent value of input is coming from the rowCount in my SQL Query stored in variable.
screenshot picture link
Input
<input disabled type="text" id="needapproval" id="approval" value="0" class="center" />
My Script
<script type="text/javascript">
function play_sound() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'Kalimba.mp3');
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load();
audioElement.play();
}
activateMagic();
function activateMagic() {
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
$("#needapproval").val(res.data_count);
},
error: function(err) {
console.log(err);
}
});
}
}
</script>
PHP
require_once "connection.php";
class NeedApprovalStatus extends Connection{
public function needApproval() {
$count_approval = "SELECT * FROM job_request WHERE approval_status LIKE '%Need Approval%' ";
$stmt_count_approval = $this->db->prepare($count_approval);
$stmt_count_approval->execute();
$count = $stmt_count_approval->rowCount();
$data_count = [];
if ($count == 0) {
$data_count = [
'data_count' => 0
];
} else {
$data_count = [
'data_count' => $count
];
}
echo json_encode($data_count);
}
}
$need_approval = new NeedApprovalStatus;
$need_approval->needApproval();
I tried to use onchange event in jquery but it doesn't work. because i think onchange only trigger when you change value on input manually. Any ideas guys?
It would be easier to check the value inside the success function and call play_sound() from there.
function activateMagic() {
var value = 0;
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
var newValue = res.data_count;
if(newValue != value) {
play_sound()
$("#needapproval").val(value);
value = newValue;
}
}
...

jquery select2: error in getting data from php-mysql

I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.

Server side scripting onkeyup PHP

i am trying to make an search box which search the name from elastic search database, but when i run the it always give me an error that ----
Notice: Undefined index: value in the line --> $query = $_GET['search_keyword'];
but from my script i believe it should get the "search_keyword".
Search box --
<form method="GET" action="/latest/helloTestData">
<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
</form>
Script --
<script>
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
$.ajax({
type: "GET",
url: "/latest/helloTestData", // address to the php function
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});
</script>
PHP ---
public function helloTestDataAction() {
$paramss = array('hosts' => array('localhost:9200'));
$client = new Elasticsearch\Client($paramss);
$query = $_GET['search_keyword'];
if ($query != "") {
$params = array();
$params['size'] = 1000000000;
$params['index'] = 'myindex';
$params['type'] = 'mytype';
$params['body']['query']['bool']['must'] = array(
array('match' => array('name' => $query)), // search data by input data
);
$esresult = $client->search($params);
if ($esresult < 1) {
echo "Your search did not match any documents. Please try different keywords.";
} else {
echo $esresult; //results found here and display them
}
}
return new Response('ok');
}
Can anyone knows how to fix this problem. Thanks a lot in advanced.
Modifiy $_GET['value'] into $_GET['search_keyword']
So
public function helloTestDataAction() {
[...]
$_GET['search_keyword'];
[...]
}
You're searching for a key that will not be into $_GET array, as, into your ajax request, you're passing a key named search_keyword and so this is the error
Simply replace
$_GET['value'] to $_GET['search_keyword']
Quick and simple! The front-end pass the typed text via GET by url.
In this test I put the 2 files in the same folder. Change as you need.
Front-end:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="my_header" style="background-color:lightblue">
</div>
<input type="text" id="foo" value="bar" onkeyup="loadlink(this)" />
<script>
function loadlink(e){
$('#my_header').load('back.php?var='+e.value,function () {
$(this).unwrap();
});
}
</script>
Back-end (back.php):
<?php
echo "received: " . $_GET["var"] . ' <br>at ' . gmdate('Y-m-d h:i:s \G\M\T', time());
?>

Jquery, Codeigniter 2.1 - How to check if update is succesfull

How can I see if the update, after JQuery post, is succesfull?
JQuery code:
var code = $('#code'),
id = $('input[name=id]').val(),
url = '<?php echo base_url() ?>mali_oglasi/mgl_check_paid';
code.on('focusout', function(){
var code_value = $(this).val();
if(code_value.length < 16 ) {
code.after('<p>Code is short</p>');
} else {
$.post(url, {id : id, code : code_value}, function(){
});
}
});
CI controller:
function mgl_check_paid()
{
$code = $this->input->post('code');
$id = $this->input->post('id');
$this->mgl->mgl_check_paid($code, $id);
}
CI model:
function mgl_check_paid($code, $id){
$q = $this->db->select('*')->from('ad')->where('id_ad', $id)->where('code', $code)->get();
$q_r = $q->row();
if ($q->num_rows() != 0 && $q_r->paid == 0) :
$data['paid'] = 1;
$this->db->where('id_ad', $id);
$this->db->update('ad', $data);
return TRUE;
else :
return FALSE;
endif;
}
I need to check if update is successful and show appropriate message.
CI controller:
function mgl_check_paid()
{
$code = $this->input->post('code');
$id = $this->input->post('id');
// could also return a json or whatever info you want to send back to jquery
echo ($this->mgl->mgl_check_paid($code, $id)) ? 'yes' : 'no';
}
Jquery
var code = $('#code'),
id = $('input[name=id]').val(),
url = '<?php echo base_url() ?>mali_oglasi/mgl_check_paid';
code.on('focusout', function(){
var code_value = $(this).val();
if(code_value.length < 16 ) {
code.after('<p>Code is short</p>');
} else {
$.post(url, {id : id, code : code_value}, function(data){
// display the data return here ... simple alert
//$('.result').html(data); // display result in a div with class='result'
alert(data)
});
}
});
You may also want to read more # http://api.jquery.com/jQuery.ajax/ (if you want to do better error checking like failure)
First of all, mad props, I <3 CI and jQuery. Secondly, you need to echo in order to return data to your jQuery post.
Gimmie 5 to fix something at work and i'll edit this answer with more detail.

Categories