passing a variable with get request to PHP - javascript

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) {

Related

How do I return $wpdb->get_results as json in WordPress?

I created a custom table in wordpress called custom_users and I want to access the records via the API
functions.php
function get_wp_custom_users()
{
global $wpdb;
$custom_users = $wpdb->get_results("SELECT * FROM wp_custom_users");
foreach ($custom_users as $custom_user)
{
echo $custom_user->first_name.' '.$custom_user->last_name;
}
}
add_action('rest_api_init', function()
{
register_rest_route( 'wpcustomusers/v1', '/users/', array(
'methods' => 'GET',
'callback' => 'get_wp_custom_users'
));
});
The API can be accessed via url http://localhost/mywebsite/wp-json/wpcustomusers/v1/users
Do you know how can I return the results inside the for loop as JSON from the API request?
I hope to see all the fields returned.. Thanks for the help.
There is no need of foreach loop, make changes as below.
function get_wp_custom_users(){
global $wpdb;
$custom_users = $wpdb->get_results("SELECT * FROM wp_custom_users");
//change as below.
echo json_encode($custom_users);
}
var_dump $custom_users to make sure $custom_users is not empty. Skip for loop. Replace return with echo.
echo json_encode($custom_users);

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

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...

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.

mySQL not returning an array into angularJS

I am trying to retrieve the data stored in a mySQL table with a PHP script. I want this data to be returned as an array because I then loop through it in my AngularJS app and conduct various transformations etc. I am getting the data out just fine, but it is returned as just one item in an array i.e. each row is not returned as a separate item of the array. My code as it stands is:
PHP Get Request
<?php
require 'config.php';
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT * FROM user_details';
$stmt = $pdo->prepare( $sql );
$stmt->execute();
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
$json = json_encode( $result );
echo $json;
Database::disconnect();
?>
Angular Controller
$scope.userprofiles = [];
$http.get('php/getUserDetails.php')
.success(function(data) {
$scope.userprofiles = data;
});
I also run some tests to see what the issue is. Specifically, I see if the variable is an array with:
$scope.varcheck = $scope.userprofiles.constructor === Array;
This returns true. And then I check the length of the array with:
$scope.numRecords = $scope.userprofiles.length;
This returns 0.
If anyone had any thoughts it would be a great help.
I also have an issue that if a "/" or a "'" is stored in the database it throws the get request. I assume that it is exiting early. If anyone knew about this it would be great too!
Thanks,
Jack
$http methods return a promise, which can't be iterated, so you have to attach the results to the scope variable through the callbacks:
$scope.userprofiles = [];
$http.get('php/getUserDetails.php')
.then(function(response) {
$scope.userprofiles = response.data;
});
Hope it may help you :-)

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