How can I get the results of two SQL-Queries in PHP in one JS function with AJAX? - ajax

I am a complete beginner and I hope that you can help me.
In my php file I make two different database queries and I need their results for calculations in a js function, which in turn should be displayed in the browser.
If I try to display the results from both queries, only "undefined" is returned. However, they are displayed to me in the console, where I also have the numbers output via consol.log (data). I am trying this with the help of ajax. If I remove the part from the second DB query in my function, it works. Unfortunately not all together. What am I doing wrong? Is what I plan to do even possible or do I have to take a detour? If yes, which one?
Here is my previous code:
Javascript:
function clickPHPtoJS(){
$.ajax({
url: "index.php",
type: "POST",
success: function(data) {
console.log(data);
clickPHPtoJSResponse(data);
},
error: function (data) {
console.log("Daten nicht erhalten");
}
});
}
function clickPHPtoJSResponse(data) {
// Antwort des Server ggf. verarbeiten
var response = JSON.parse(data);
var einer = response.einer;
var zwoelfer = response.zwoelfer;
var anzahl = response.nr;
document.getElementById("lab1er").innerHTML = einer + " " + zwoelfer + " " + anzahl;
}
PHP:
<?php
require 'inc/db.php';
$erg = $db->query("SELECT id, sender FROM packaging_log WHERE sender='test' AND packaging='1er'")
or die($db->error);
$gesteigereiner = $db->query("SELECT * FROM geliefert WHERE 1")
or die($db->error);
while ($zeile = $gesteigereiner->fetch_object()) {
$einer = $zeile->test1er;
$dreier = $zeile->test3er;
$sechser = $zeile->test6er;
$zwoelfer = $zeile->test12er;
}
$geliefert = array ( "nr" => $erg->num_rows,
"einer" => $einer,
"zwoelfer" => $zwoelfer);
print_r (json_encode($geliefert));
?>
Unfortunately, that's not how it works. But if I completely remove the result from the first DB query in the JS.
Many thanks in advance. I am grateful for any information, clarification and tips.

The problem was the following: "nr" => $erg->num_rows
To get what I wanted I had to save $erg->num_rows as a variable and to put the variable into the array.
So first step: $nr= $erg->num_rows;
Second step: "nr" => $nr

Related

Datatable info is lost after i do a flitered search

I'm having a problem with a data table, whenever I use the search function in my table all the data is lost the moment I input anything on the search bar, I create this data table dynamically using AJAX, first I do a request to the server to get the data for my table.
function traerBecas() {
var ciclo = document.getElementById("ciclo").value;
$.ajax({
url: '/becas/listaBecas',
type: 'GET',
data: {
"ciclo": ciclo,
},
dataType: 'JSON',
success:function(response){
llenarTabla(response);
}
});
}
Once I get the response as a JSON I pass the info to another function to build each table row and insert it into the table.
function llenarTabla(jsonArray) {
var tabla = document.getElementById('becaBody');
tabla.innerHTML = "";
jsonArray.forEach(element => {
var trElement = document.createElement('tr');
var tdCLVBECA = document.createElement('td');
var tdINSTIT = document.createElement('td');
var tdCICLO= document.createElement('td');
var tdSECCION = document.createElement('td');
var tdFECINI = document.createElement('td');
var tdFECFIN = document.createElement('td');
var tdACCIONES = document.createElement('td');
var linkEditar = document.createElement('a');
var linkEliminar = document.createElement('a');
tdCLVBECA.innerText = element.CLV_BECA;
tdINSTIT.innerText = element.INSTIT.toUpperCase();
tdCICLO.innerText = element.CICLO;
tdSECCION.innerText = element.SECCION;
tdFECINI.innerText = element.FEC_INI;
tdFECFIN.innerText = element.FEC_FIN;
linkEditar.setAttribute("href","/becas/editar/"+element.CLV_BECA);
linkEditar.setAttribute("data-bs-toggle", "tooltip");
linkEditar.setAttribute("data-bs-placement", "top");
linkEditar.setAttribute("title", "Eliminar");
linkEditar.innerHTML = "<i class='fas fa-pen'></i>";
linkEliminar.setAttribute("onclick", "eliminacion("+element.CLV_BECA+")");
linkEliminar.setAttribute("data-bs-toggle", "tooltip");
linkEliminar.setAttribute("data-bs-placement", "top");
linkEliminar.setAttribute("title", "Editar");
linkEliminar.innerHTML = " <i class='fas fa-trash'></i>";
tdACCIONES.appendChild(linkEditar);
tdACCIONES.appendChild(linkEliminar);
trElement.appendChild(tdCLVBECA);
trElement.appendChild(tdINSTIT);
trElement.appendChild(tdCICLO);
trElement.appendChild(tdSECCION);
trElement.appendChild(tdFECINI);
trElement.appendChild(tdFECFIN);
trElement.appendChild(tdACCIONES);
tabla.appendChild(trElement);
});
}
Then I have the function to transform my table to a data table, and up to this moment, everything works alright. EDIT: Forgot to mention that this info is run first when the page is loaded, the table at the beginning is empty and then is filled with the info I requested.
$(document).ready(function() {
$('#myTable').DataTable({
responsive: true,
language: {
url: '//cdn.datatables.net/plug-ins/1.10.25/i18n/Spanish.json'
}
});
});
Then, once I have my table built, I try to use the search function that it generates, but then I run into the problem that the table doesn't find the info, loses the data, and doesn't return to the previous state once I delete the prompt on the search bar.
I'm at a loss of what to do, I have other data tables that don't have this problem, however, those tables aren't built using AJAX, they get their info directly from the controller with the compact() function in the PHP controller, and using Blade directives like #foreach loops.
You should open up your browser's dev tools and inspect the network request to your endpoint:
url: '/becas/listaBecas'
It could be a number of things, the network tab will show you if there is an error with the AJAX request. If the AJAX request has no error, you will want to look at your endpoint and debug the query that is being run to see why it's not returning any results.
Would also be a good idea to add a error catch for the AJAX call:
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error with the request");
}

AJAX to update mySQL in Wordpress Custom Table

I have followed Matt Van Andel's Custom List Table Example to create an admin table which displays enquiries to a website via an external MySql database.
Having implemented the displaying of my data correctly, I have added a select box column which will allow the admin to update the 'status' of the enquiry (Awaiting Response, Responded etc.) and I need this to update my database via AJAX.
I need a change in these select boxes to trigger an AJAX call which will update the database with the new value but I seem to be struggling to link my external AJAX file to my plugins .php file correctly.
I have reached a point where (in the Network tab) I can see I am loading the .js file like so:
Code in list-table.php:
function ajax_test_enqueue_scripts() {
wp_enqueue_script( 'list-table', plugins_url( 'js/list-table.js', __FILE__ ), array('jquery'));
}
add_action( 'admin_enqueue_scripts', 'ajax_test_enqueue_scripts' );
And my AJAX:
jQuery('.status-select').on( 'change', function ajaxSubmit() {
alert("IT WORKED!");
$.ajax({
url: ajaxurl,
type: "POST",
cache: false,
data: this.val()
})
});
At the moment the file is showing but the 'on change' part doesn't seem to be firing (hence the 'alert' in the .js).
Apologies if this question is worded or organised poorly, it is my first time posting!
Hope someone can explain what/ where I am going wrong.
This is quite a specific requirement but for anyone else using custom tables in WordPress and wanting to update an external myqsl database via AJAX - here's how I did it.
The AJAX side of things -
<script>
jQuery('select.status').on('change', function() {
var $statusSelect = jQuery( this );
var $statusSelectCell = $statusSelect.parent();
var enquiryStatusValue = $statusSelect.val();
var currentBackgroundColor = $statusSelectCell.parent().css("backgroundColor");
var ajaxData = {
'action': 'update_status_db',
'currentId': $statusSelect.attr('id'),
'data': enquiryStatusValue
}
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: ajaxData,
success: function( response ) {
console.log("Data returned: " + response );
$statusSelectCell.parent().css({"background-color": "#b3e6b3"});
$statusSelectCell.parent().animate({backgroundColor: currentBackgroundColor}, 1200);
},
error: function() {
alert("FAILED TO POST DATA!!");
}
});
})
</script>
Note, the users success confirmation in this case is for the specific row to flash green. This is optional.
Next, the PHP to process the AJAX request. This is to be written outside the tables class.
wp_enqueue_script('jquery');
add_action( 'wp_ajax_update_status_db', 'update_status_db_callback' );
function update_status_db_callback(){
global $wpdb;
$newStatus = $_POST['data'];
$currentId = $_POST['currentId'];
$table = 'wp_enquiryinfo';
$result = $wpdb->update( $table, array( 'status' => $newStatus ), array( 'id' => $currentId ));
echo $_POST['data'];
if (!$result) {
echo "FAILED TO UPDATE";
} else {
$result;
echo "WILL UPDATE SUCCESSFULLY - CALL RESULT FUNCTION";
};
wp_die();
}
Here are a couple of the things I was getting wrong originally:
Firstly, the callback function HAS to end with _callback. Secondly, I didn't call the wp_die function at the end of this - this again is required.
Hopefully this may be of use to someone in the future.

Simple ajax in laravel 4

i have following code
ajax
//ajax edit button
$('.edit_button').on('click', function(e) {
e.preventDefault();
var id_produk = $(this).attr('id');
$.ajax({
type : "POST",
url : "editproduk",
data : id_produk,
dataType: 'JSON',
success : function(data) {
alert('Success');
console.log(data);
},
error: alert('Errors')
});
});
i always get messagebox error
and don't know where i'm missing,
because in chrome - inspect element - console not give any clue
my route
Route::post('/account/editproduk', array(
'as' => 'edit-produk-post',
'uses' => 'AccountController#postEditProduk'
));
my controller
public function postEditProduk() {
if (Request::ajax()) {
return "test test";
}
}
extended question
i running my script well after using return Response::json() like this
$id_produk = Input::get('id_produk');
$produk = Produk::findOrFail($id_produk);
return Response::json($produk);
and access it in view by this script
success : function(data) {
alert('Success');
console.log(data["name-produk"]);
}
but if i want to return array json like
$id_produk = Input::get('id_produk');
$produk = Produk::findOrFail($id_produk);
$spesifikasi = SpesifikasiProduk::where('id_produk', '=', $id_produk);
return Response::json(array($produk, $spesifikasi));
i can't access it in view like this...
success : function(data1, data2) {
alert('Success');
console.log(data1["name-produk"] - data2["title-spek"]);
}
how to access json array
extended question update
if i'm wrong please correct my script
because i get a litle confused with explenation
is this correct way to return it?
Response::json(array('myproduk' => 'Sproduk', 'data2' => 'testData2'));
result
console.log(produk["myproduk"]);
--------------------------------
Object {id_produk: 1, nama_produk: "produk1", deskripsi: "desc_produk"
console.log(produk["data2"]);
--------------------------------
testData2
and i still don't have idea how to print nama_produk in my_produkarray
Question 1:
Why is this code not sending JSON data back.
public function postEditProduk() {
if (Request::ajax()) {
return "test test";
}
}
Answer: Because this is not the right way to send the JSON data back.
From the Laravel 4 docs, the right way to send JSON data back is linked. Hence the correct code becomes:
public function postEditProduk() {
if (Request::ajax()) {
return Response::json("test test");
}
}
Question 2:
Why am I not able to access the data in data1 and data2
success : function(data1, data2) {
alert('Success');
console.log(data1["name-produk"] - data2["title-spek"]);
}
Answer: Because this is not the right way to catch the JSON data. The right way to send is given in the Laravel 4 API reference docs.
static JsonResponse json(string|array $data = array(), int $status = 200, array $headers = array(), int $options)
As you can see the method json takes string or array as the first parameter. So you need to send all your data in the first parameter itself (which you are doing). Since you passed only one parameter, you have to catch only 1 parameter in your javascript. You are catching 2 parameters.
Depending on what $produk and $spesifikasi is, your data will be present in one single array. Lets say that $produk is a string and $spesifikasi is an array. Then your data on the javascript side will be this:
[
[0] => 'value of $produk',
[1] => array [
[0] => 'value1',
[1] => 'value2'
]
]
It would be best if you print the log your entire data and know the structure. Change your code to this:
success : function(data) {
console.log(data.toString());
}
This will print your entire data and then you can see the structure of your data and access it accordingly. If you need help with printing the data on your console, google it, or just let me know.
I sincerely hope that I have explained your doubts clearly. Have a nice day.
Edit
extended question answer:
Replace this line:
$spesifikasi = SpesifikasiProduk::where('id_produk', '=', $id_produk);
With this:
$spesifikasi = SpesifikasiProduk::where('id_produk', '=', $id_produk)->get();
Without calling the get() method, laravel will not return any value.
Then access your data in javascript like this:
console.log(JSON.stringify(data));
This way you will get to know the structure of your data and you can access it like:
data[0]["some_key"]["some_other_key"];
In your controller you're returning text while your ajax request awaits json data, look at these lines of codes, I think you should get your answer:
if(Request::ajax()) {
$province = Input::get('selectedProvince');
//Get all cites for a province
if ($cityList = City::where('province_id','=', $province)) {
return Response::make($cityList->get(['id', 'name']));
}
return Response::json(array('success' => false), 400);
}

Ajax.request not working

I am sorting a list using scriptaculous, i can't get the ajax request part to work.
This is my code:
<script type="text/javascript">
Sortable.create("images_list", {
onUpdate: function() {
var list = Sortable.serialize("images_list");
alert(list);
new Ajax.Request('processor.php', {
method: 'post',
parameters: { data: list }
});
}
});
I Have alerted out the serialize string, this part is working fine:
images_list[]=18&images_list[]=19&images_list[]=21&images_list[]=22&images_list[]=20
So the sorting is working fine, however the data string doesn't seem to be available in the processor.php
<?php
//Connect to DB
require_once('connect.php');
parse_str($_POST['data']);
for ($i = 0; $i < count($images_list); $i++) {
$id = $images_list[$i];
mysql_query("UPDATE images SET ranking = '$i' WHERE id = '$id'");
}
?>
Any ideas why the data is not getting posted? I have tested to see if the processor.php page is actualy being invoked, and it is.
Thank you
When method = 'post', you need to use "postBody" instead of "parameters" for having parameters posted to your server side script

jqGrid display default "loading" message when updating a table / on custom update

I have a case where I need to update a jqgrid based on some search criteria which the user selects. I can get the data to update , but I would want the loading message to show while the new data is being fetched. Can someone please let me know how to get that working ?
Current code follows
var ob_gridContents = $.ajax( {
url : '/DisplayObAnalysisResults.action?getCustomAnalysisResults',
data : "portfolioCategory="+ $('#portfolioCategory').val()
+"&subPortfolioCategory="+ $('#subPortfolioCategory').val()
+ "&subportfolio=" + $('#subportfolio').val(),
async : false
}).responseText;
var ob_Grid = jQuery('#OBGrid')[0];
var ob_GridJsonContents = eval('(' + ob_gridContents + ')');
$('#ob_Grid').trigger("reloadGrid");
ob_Grid.addJSONData(ob_GridJsonContents);
ob_Grid = null;
ob_GridJsonContents = null;
}
If I correct understand what you will, I can recommend you to use jQuery blockUI plugin (http://malsup.com/jquery/block/). Then you don’t need more to use "async : false" parameter of $.ajax function and do something like following:
var WaitMsg = function () {
jQuery('#main').block({ message: '<h1>Die Daten werden vom Server geladen...</h1>' });
};
var StopWaiting = function () {
jQuery('#main').unblock();
};
WaitMsg();
$.ajax({url : '/DisplayObAnalysisResults.action?getCustomAnalysisResults',
data: jQuery.param({portfolioCategory: $('#portfolioCategory').val(),
subPortfolioCategory: $('#subPortfolioCategory').val(),
subportfolio: $('#subportfolio').val()}),
complete: function (data, status) {
if (status === "success" || status === "notmodified") {
var ob_GridJsonContents = jQuery.parseJSON(data.responseText);
...
}
StopWaiting();
},
error: function (xhr, st, err) {
// display error information
StopWaiting();
}
});
I recommend you don’t build parameters with the way like
"portfolioCategory="+ $('#portfolioCategory').val()
+"&subPortfolioCategory="+ $('#subPortfolioCategory').val()
+ "&subportfolio=" + $('#subportfolio').val()
because you can receive encoding problems, if data returned by .val() have some special characters. You could use JavaScript function encodeURIComponent in such cases (like encodeURIComponent($('#portfolioCategory').val()))
or jQuery.param function if you construct a string like p1=val1&p2=val2&...pN=valN.
Best regards
Oleg

Resources