What is the best way to handle two separate ajaxes in laravel? - javascript

So i have a page with two separate ajax call ( with laravel ) , when first one is executed then the second one has to run but second ajax's options is in selectbox. here is my solution ( with bad heart ofcourse) :
public function getCategoryAjax(Request $request)
{
$product = Product::where('category_id',$request->get('category_id'))->get();
return $product;
}
public function getPriceAjax(Request $request)
{
$withPrice = Product::where('category_id',$request->get('category_id'));
if ($request->get('price') == 1){
$withPrice=$withPrice->where('min_price','<', 1000000)->get();
}elseif ($request->get('price') == 2){
$withPrice=$withPrice->where('min_price','>', 1000000)->andWhere('max_price','<',2000000)->get();
}
return $withPrice;
}
first method is for first ajax , in the second one i'm doing if elseif for handling options in selectbox
So here is my question , is there a better way to do this?
(the select box in the left is for second ajax

I think you are asking about better way to handling multiple if conditions in getPriceAjax(Request $request) function...
If this is your problem you can write your code like this...
// Set all your min-max price rules in array, by this you can easily modilfy every price option rule..
protected $priceRules = array(
1 => ["0", "1000000"],
2 => ["1000000", "2000000"],
3 => ["2000000", "3000000"],
4 => ["3000000", "4000000"],
// ... so on
);
public function getPriceAjax(Request $request) {
$price = $request->get('price');
// check given option is in array or not... some validation..
if (isset($this->priceRules[$price])) {
// It will dynamically handle all your price option query...
$withPrice = Product::where('category_id', $request->get('category_id'))->whereBetween('price', $this->priceRules[$price])->get();
return $withPrice;
}
return 'error';
}
Hope it helps you...

Related

passing a variable with get request to PHP

Goal: I am trying to populate a dropdown from a database table column... I need to pass a variable from the front-end to the PHP indicating which table to ping from, as it may change depending on user selection beforehand...
This is where I'm trying to pass my which variable in to use as
this indicator — but I am having a hard time, because I am trying to
do so within a $.get request? If I could get $which = $_GET['id']; to report/gather what I have in my jQuery with let which = $(frm).attr("id"); I should be good to go.
How else could I do this, I don't think I could nor think it would be
any good practice to try and wrap a post around my get or vica
versa? Or chain a post then a get - I just need the PHP to access
my jQuery which variable so it knows which table to query.
Below is my most recent attempt: jquery
$('#agent').click(function(){
let which = $(frm).attr("id");
console.log(which);
$.get('dlteopt', 'id='+which, function (response) { // attempt at id
console.log(response);
$.each(response,function(i,obj){
let dd_data="<option value="+obj+">"+obj+"</option>";
$(dd_data).appendTo('#agent');
console.log(obj);
});
});
});
And the PHP side:
$app->get('/dlteopt', function ($request, $response, $args) {
$which = $_GET['id'];
var_dump($which);
if ($which) {
var_dump($which);
$db = $this->db;
$repo = new coolDBclass($db);
$selectIt = $repo->byCol($which);
}
});
here is function byCol btw: (all should be fine if I can just pass the correct table variable)
public function byCol($which) {
var_dump($which);
if ($which == 'table_1'){
$sql = "SELECT table_1 FROM tab.cool";
} else if ($which == 'table_2'){
$sql = "SELECT table_2 FROM tab.awesome";
} else if ($which == 'table_3'){
$sql = "SELECT table_3 FROM tab.rad";
}
// ............/
the relevant markup:
<select name='agent' id='agent'><option>Placeholder</option></select>
If you're trying to use the second parameter of the $.get method to pass the data, it needs to be an object.
See the examples in the docs.
.get('dlteopt', {id: which }, function (response) {

PHP and javascript (EXTJS) - validate form fields in server side OOP way

In my app the form fields are validated on the client side with javascript (EXTJS).
Although I'not experienced in PHP OOP, I also want to validate them server side with PHP OOP way.
For this - after studying the various possibilities of validation - I am using the following code:
I'm following this example: https://www.youtube.com/watch?v=MlJJyva75t8#t=38.9063742
class Validator
<?php
class Validator {
private $fields = array();
private $field_errors = array();
private $form_is_valid = true;
private $allErrors = array(); //added » edited
public function addField($field_name){
$this->fields[] = $field_name;
$this->field_errors[$field_name] = array();
}
public function addValidationRule($field_name, $field_rule, $value){
$rule_name = $field_rule[0];
switch($rule_name){
case 'empty':
if(strlen($value) == 0){
$this->addValidationError($field_name, ucwords($field_name). " error msg empty");
}
break;
case 'min_lenght':
if(strlen($value) < $field_rule[1]){
$this->addValidationError($field_name, ucwords($field_name). " error msg min_lenght");
}
break;
}
}
private function addValidationError($field_name, $error_message){
$this->form_is_valid = false;
$this->field_errors[$field_name][] = $error_message;
}
public function formValid(){
return $this->form_is_valid;
}
public function outValidationError($field_name){
if(isset($this->field_errors[$field_name])){
foreach($this->field_errors[$field_name] as $field_error){
//$allErrors[] = $field_error;
$this->allErrors[] = $field_error;//added » edited
}
}
}
public function outAllValidationError(){
foreach($this->fields as $field){
$this->outValidationError($field);
}
return $this->allErrors; //added » edited » works ok
}
}
?>
Query with prepared statements
<?php
require('conect.php');
$action = $_REQUEST['action'];
switch($action){
case "create":{
$records = $_POST['records'];
$data = json_decode(stripslashes($records));
$cars = $data->{'cars'};
if ($_SERVER["REQUEST_METHOD"] == "POST") {
require_once('validator.php');
$validator = new Validator();
$validator->addField('cars');
$validator->addValidationRule('cars', array('min_lenght', 4), $cars);
$validator->addValidationRule('cars', array('empty'), $cars);
if($validator->formValid()){
$sqlQuery = "INSERT INTO the_cars (cars)
VALUES (?)";
if($statement = $con->prepare($sqlQuery)){
$statement->bind_param("s", $cars);
$statement->execute();
$success= true;
}else{
$erro = $con->error;
$success = false;
}
}else{
$allErrors = $validator->outAllValidationError();
$success = false;
}
echo json_encode(array(
"success" => $sucess,
'errors'=> $erro,
'errorsValidation'=> $allErrors
));
$statement->close();
$conexao->close();
break;
}
?>
y problem is to export the array of validation errors to the client side with json encode.
If in the outValidacionError() function I uncomment print_r ($ allErrors) and make a form submit with the cars field empty it prints the error on console.
However, I am not able to send these errors to the client side. What is missing?
I appreciate suggestions for improving the code or other solution.
EDITED:
As my json_decode is done for objects and not for an associative array, I have changed the code to make it compatible with the decode that was made, adding $value to addValidationRule()
EDITED
code edited with correct solution
If you use functions to encapsulate behaviour, you should not try to use global variables to store their output. Their side-effects should be minimal and they should only manipulate their own object's properties, if required.
Your $allErrors variable is declared nowhere, especially not as a global variable. So when you fill it inside the function, you get a locally scoped variable that will be thrown away once the function finishes.
You may want to return them from your function
return $allErrors;
and then get the values from the function call:
$allErrors = $validator->outAllValidationError()

Laravel Datatables empty collection error

I'm using Laravel Datatables package to show Ajaxified tables.
I'm getting an error when the collection i want to show in my table is empty, the error is:
ErrorException in CollectionEngine.php line 46: array_keys() expects
parameter 1 to be array, null given
My controller contains two simple functions
// get the view
public function getItems() {
return view('someview');
}
// get data for datatables
public function getItemsdata() {
$data = DataModel::all();
return Datatables::of($data)->make(true);
}
When $data is not empty, everything works just fine but if it is empty, I get the error! how can i fix this? any ideas?
I think you can use the isEmpty() function of laravel
public function getItemsdata() {
$data = DataModel::all();
if($data->isEmpty()){ //I think laravel has isEmpty() function
return 'error!'; //throw exception here
}else{
return Datatables::of($data)->make(true);
}
}

Issue trying to preform a delete with php and angular

I am trying to preform a delete with angular and php. I am pretty sure that my php is right.
But i am not able to delete. In my console log it says that my deletion was succesfull but when looking in the table I still see the recored.
Upon further inspection with debugger in chrome I see dat my parameter index is undefined -> http://gyazo.com/88b6dcf9d4c03a1fc9dd235303b20a8f
(part of) My HTML code:
<md-button class="md-primary" ng-click="delete_task(task.id)">Delete</md-button>
(part of) My app.js file:
/** function to delete a task from list referencing php **/
$scope.delete_task = function(index) {
debugger;
$http.post('db.php?action=delete_task',
{
'task_index' : index
}
)
.success(function (data, status, headers, config) {
// here we also replace how to get the user
getTaskFunction(
/* success function */
function(data) {
$scope.taskInfo = data;
console.log("The taks have been reloaded" , $scope.taskInfo);
},
/* error function */
function()
{
alert("Server load failed");
}
);
console.log('Deletion was succesfull');
})
.error(function(data, status, headers, config) {
console.log("You were NOT succesfull in deleting a task");
}
);
(part of) My PHP code:
<?php
include('config.php');
switch($_GET['action']) {
case 'get_ProjectType_Info' :
get_ProjectType_Info();
break;
case 'add_task' :
add_task();
break;
case 'get_Location_Info' :
get_Location_Info();
break;
case 'get_Task_Info' :
get_Task_Info();
break;
case 'delete_task' :
delete_task();
break;
}
/** Function to delete a task **/
function delete_task() {
$data = json_decode(file_get_contents("php://input"));
$index = $data->task_index;
echo ($index);
//print_r($data);
$del = mysql_query("DELETE FROM tblTask WHERE id = ".$index);
if($del)
return true;
return false;
}
I am not sure how to proceed from this point on.
It should be better not use querystring variables together with post variables as you're doing. Create a complete object on javascript statement in order to have something like this:
{
'task_index' : index,
action: 'delete_task'
}
And then you should threat this object data inside you switcher.
It would be great if you adopt some practices that take the code cleaner and easier to understand.
First thing of all, you should test your delete_task method. To make it successfully I suggest you to get the variables calling file_get_contents("php://input")) into the switch and passing them as method parameters. Make it this way:
<?php
// ...
// Receive id you have already collected
function delete_task($task_id){
$del = mysql_query("DELETE FROM tblTask WHERE id = ".$task_id);
if($del) return true;
return false;
}
// test that method
function test_delete(){
$ret = delete_task(4); // test with valid and invalid ids
}
?>
Obviously this is not a beautiful way to test methods and you should consider using any test framework for unit tests. But it's important to build methods in a way that you can change parameters and observe its behavior. Once you are assured that this method (the more critic one in this scenery) is working, you can go down one level on stack and check if your switcher is working well. At this time you can test your endpoint using Postman for Chrome, as an example.

How do I use a php array within an array returned to Javascript?

I've been at this for more than half a day trying to figure out this problem and I swear I've tried every possible thing. So here's the idea behind what I'm trying to do... Every 10 seconds Javascript performs an AJAX call to see if you have any friends online, then returns a list of users, their status etc... Instead of formatting everything from PHP, I'll be formatting it from Javascript for various reasons... So here's what happens:
Javascript
// Let's get the data from the controller
$.post('/pagething', { datastuff }, function(data){
if(data.status == 'ok'){
// Magic nonsense here that can translate the array example:
var keys = Object.keys(data.allfriends);
}
} etc...
PHP
// Let's skip other code in the controller and focus on the important stuff
$friends_information = array(
'userid' => array();
'username' => array();
'avatar' => array();
'status' => array();
);
foreach($result_from_my_friends_model as $row){
// For ease of read, i'll just associate things with $row
$friends_information["userid"][] = $row->user_id;
$friends_information["username"][] = $row->username;
$friends_information["avatar"][] = $row->avatar;
$friends_information["status"][] = $row->status;
}
$result = array('status' => 'ok', 'allfriends' => $friends_information);
return json_encode($result);
exit();
The closest I've gotten is to either get the results by say username, or userid for example through a new object or getting the entire result but unable to distinguish between keys since object[0][1] for instance would return undefined.
Thank you in advanced, this stuff is tough to understand :/
There's no need to put each column into a separate element of $friend_array, things are generally easier if you keep all the data related to a particular friend together in an object. So do:
$result = array('status' => 'ok', 'allfriends' => $result_from_my_friends_model);
echo json_encode($result);
In the Javascript, make sure you specify that the result is JSON:
$.post('/pagething', { datastuff }, function(data) {
if (data.status == 'ok') {
$.each(data.allfriends, function(i, friend) {
// do stuff with friend.userid, friend.username, friend.avator, friend.status
});
}
}, 'json');
You already have your list_of_friend in your keysvariable of js. Just iterate through it then you will get your desired result. Best of luck

Categories