How to call a specific php function inside a class through ajax? - javascript

I want to know how I can call the function ajax_check_login available in my User class, this class exists in user.php.
This is the basic content:
class User extends {
/**
* Class Constructor
*/
public function __construct() {
}
public function ajax_check_login() {
try {
if (!isset($_POST['username']) || !isset($_POST['password'])) {
throw new Exception('Invalid credentials given!');
}
$this->load->model('user_model');
$user_data = $this->user_model->check_login($_POST['username'], $_POST['password']);
if ($user_data) {
$this->session->set_userdata($user_data); // Save data on user's session.
echo json_encode(AJAX_SUCCESS);
} else {
echo json_encode(AJAX_FAILURE);
}
} catch(Exception $exc) {
echo json_encode(array(
'exceptions' => array(exceptionToJavaScript($exc))
));
}
}
}
and this is my ajax request:
var postUrl = GlobalVariables.baseUrl + 'application/controllers/user.php/ajax_check_login';
var postData =
{
'username': $('#username').val(),
'password': $('#password').val()
};
$.post(postUrl, postData, function(response)
{
// Some stuff..
});
How you can see I want call the function ajax_check_login available in the user.php file. But I can't access directly to this function 'cause is located inside the User class, so I should create another file to bounce the request or I can do it in the same file user.php file?

You have a typo:
class User extends {
Extends what?
Add this to user.php (outside of the class):
$allowed_functions = array('ajax_check_login');
$ru = $_SERVER['REQUEST_URI']
$func = preg_replace('/.*\//', '', $ru);
if (isset($func) && in_array($func, $allowed_functions)) {
$user = new User();
$user->$func();
}

Related

Laravel cannot retrieve data from multiple model with Ajax

Hi I am beginner with Ajax at the Laravel. I wanted to fetch data with Laravel Eagerload function to my blade modal.
This is my Expenses Model
protected $fillable = [
'name',
'surname',
'email',
'password',
'status',
'role',
];
protected $hidden = [
'password',
'remember_token',
];
public function Expense () {
return $this->hasMany(ExpensesModel::class);
}
This is my Expenses Model
`
{
use HasFactory;
protected $table = 'expenses';
protected $fillable = [
'id',
'emp_id',
'expense_input_date',
'expense_type',
'expense_category',
'reason',
'status'
];
public function UserExpense () {
return $this->belongsTo(User::class, 'emp_id' );
}
My controller
This is My controller function
public function edit (Request $request) {
$req_id = array('id' => $request->id);
if($request->ajax()) {
$employee = ExpensesModel::with('UserExpense')->where('id' ,$req_id)->first();
return response()->json($employee);
}
}
This is my blade script
`
function editFunc(id){
$.ajax({
type:"POST",
url: "{{ url('/expenses/advancedtable/edit') }}",
data: { id: id },
dataType: 'json',
success: function(res){
$('#EmployeeModal').html("Edit Employee");
$('#employee-modal').modal('show');
$('#id').val(res.id);
$('#emp_id').val(res.name);
$('#expense_input_date').val(res.expense_input_date);
$('#expense_type').val(res.expense_type);
$('#expense_category').val(res.expense_category);
$('#expense_slip_no').val(res.expense_slip_no);
$('#expense_amount').val(res.expense_amount);
$('#currency').val(res.currency);
$('#description').val(res.description);
}
});
}
I tried everyting but it does not work. I wanted to retrive user name from User Model by using foreign key on the Expenses model emp_id.
is there something I missed somewhere can you help me with this.
Thank you.
Here how its work.
First of all change relationship in your User and Expenses model like this.
// User Model
public function userExpense() {
return $this->hasMany(ExpensesModel::class,'emp_id','id');
}
// ExpensesModel
public function user() {
return $this->hasOne(User::class,'id','emp_id');
}
Then change your controller function.
// controller function
public function edit (Request $request) {
$req_id = $request->id;
$employeeExpense = ExpensesModel::with('user')->where('id' ,$req_id)->first();
return response()->json($employeeExpense);
}
Then change your ajax sucess function.
// ajax sucsess function
success: function(res) {
console.log(res); // to view your response from controller in webbrowser's console
$('#EmployeeModal').html("Edit Employee");
$('#employee-modal').modal('show');
$('#id').val(res.id);
$('#emp_id').val(res.user.name); // it will print user name
$('#expense_input_date').val(res.expense_input_date);
$('#expense_type').val(res.expense_type);
$('#expense_category').val(res.expense_category);
$('#expense_slip_no').val(res.expense_slip_no);
$('#expense_amount').val(res.expense_amount);
$('#currency').val(res.currency);
$('#description').val(res.description);
}
when you use 'with' eloqunt method it will add relationship function name to your query result, so you want to get user details then you should be do like res.user.userfield this is applicable for hasOne only.
For other relationship you will refer to this https://laravel.com/docs/9.x/eloquent-relationships

ajax post to MVC controller failed with 400 Bad Request

I ajax post a complex object to a .Net 5.0 controller (not a WebAPI controller). The declaration of the MVC controller and TypeScript are as below. The [HttpPost] Edit action is invoked if I post with <input type='submit' value='Save' />. However, the controller's action is not invoked at all if I post through jQuery .ajax(). The browser console says "POST https://localhost:44381/Question/Edit 400 (Bad Request)". I read many code samples and nothing indicates anything wrong with the code. Does anyone know why?
namespace theProject.Controllers {
public class BaseController: Controller {
protected BaseController(IConfiguration configuration, ILogger logger) {
.......(elided
for brevity)
}
}
}
namespace theProject.Controllers {
//ToDo: [Authorize]
public class QuestionController: BaseController {
public QuestionController(IConfiguration configuration, ILogger < QuestionController > logger): base(configuration, logger) {}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([FromBody] PostbackModel model) {
if (ModelState.IsValid) {
List < UserAnswer > newAnswers = model.NewAnswers;
List < UserAnswer > oldAnswers = model.OldAnswers;
List < UserAnswer > updatedAnswers = model.UpdatedAnswers;
UserAnswer thisAnswer = new();
if (newAnswers != null)
thisAnswer = newAnswers.Find(x => x.StageName != string.Empty);
else if (oldAnswers != null)
thisAnswer = oldAnswers.Find(x => x.StageName != string.Empty);
else if (updatedAnswers != null)
thisAnswer = updatedAnswers.Find(x => x.StageName != string.Empty);
//ToDo: call webapi Question controller to persist the data to database
return RedirectToAction(nameof(Edit), new {
stage = thisAnswer.StageName, personName = thisAnswer.personName, custID = thisAnswer.custID.ToString(), redirectFrom = "Edit"
});
} else {
return RedirectToAction("Index", "Home");
}
}
let postBackModel: AjaxPostbackModel = < AjaxPostbackModel > {};
postBackModel.NewAnswers = newAnswers
postBackModel.OldAnswers = oldAnswers;
postBackModel.UpdatedAnswers = updatedAnswers;
let thisUrl: string = $('form').prop('action');
$.ajax({
type: "POST",
url: thisUrl,
data: JSON.stringify(postBackModel),
contentType: 'application/json; charset=utf-8',
}).done(function(result) {
$('.spinnerContainer').hide();
console.log('postback result', result.message);
console.log('inserted entities', result.insetedEntities);
dialogOptions.title = 'Success';
$('#dialog')
.text('Data is saved. ' + result.message)
.dialog(dialogOptions);
}).fail(function(error) {
console.log('postback error', error);
$('.spinnerContainer').hide();
dialogOptions.title = error.statusText;
dialogOptions.classes = {
'ui-dialog': 'my-dialog',
'ui-dialog-titlebar': 'my-dialog-header'
}
$('#dialog')
.text('Data is not saved')
.dialog(dialogOptions)
});
Since you use [ValidateAntiForgeryToken] in action,you need to add the following code to your ajax to add antoforgery token to header.
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },

WooCommerce Ajax add to cart with additional custom data

I am having some difficulties with trying to add to cart with custom data from the front end.
My current PHP from the backend is as follows - this is placed in my functions.php for my child-theme (This code is from the following post: Adding a product to cart with custom info and price - considering I am indeed a PHP-noobie):
<?php // This captures additional posted information (all sent in one array)
add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,10);
function wdm_add_item_data($cart_item_data, $product_id) {
global $woocommerce;
$new_value = array();
$new_value['_custom_options'] = $_POST['custom_options'];
if(empty($cart_item_data)) {
return $new_value;
} else {
return array_merge($cart_item_data, $new_value);
}
}
// This captures the information from the previous function and attaches it to the item.
add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
function wdm_get_cart_items_from_session($item,$values,$key) {
if (array_key_exists( '_custom_options', $values ) ) {
$item['_custom_options'] = $values['_custom_options'];
}
return $item;
}
// This displays extra information on basket & checkout from within the added info that was attached to the item.
add_filter('woocommerce_cart_item_name','add_usr_custom_session',1,3);
function add_usr_custom_session($product_name, $values, $cart_item_key ) {
$return_string = $product_name . "<br />" . $values['_custom_options']['description'];// . "<br />" . print_r($values['_custom_options']);
return $return_string;
}
//This adds the information as meta data so that it can be seen as part of the order (to hide any meta data from the customer just start it with an underscore)
add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
function wdm_add_values_to_order_item_meta($item_id, $values) {
global $woocommerce,$wpdb;
wc_add_order_item_meta($item_id,'item_details',$values['_custom_options']['description']);
wc_add_order_item_meta($item_id,'customer_image',$values['_custom_options']['another_example_field']);
wc_add_order_item_meta($item_id,'_hidden_field',$values['_custom_options']['hidden_info']);
}
and then I have a button on the frontend that runs the following script when pressed - this runs on a custom wordpress post where I have scripted have done some scripting in the background that collects information based on the users actions on the post:
function cartData() {
var metaData = {
description: 'My test Description'
another_example_field: 'test'
};
var activeVariationId = 10335;
var data = {
action: 'wdm_add_item_data',
product_id: 10324,
"add-to-cart": 10324,
quantity: 1,
variation_id: activeVariationId,
cart_item_data: metaData
};
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add-to-cart' ),
data: data,
beforeSend: function (response) {
//$thisbutton.removeClass('added').addClass('loading');
},
complete: function (response) {
//$thisbutton.addClass('added').removeClass('loading');
},
success: function (response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
alert('ajax response recieved');
jQuery( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash ] );
}
},
});
}
Unfortunately this only seems to add my current variation of the product to the to cart without any more custom information. Any help with nesting in this issue would be highly appreciated. If you need any more information and/or code examples I'd be happy to supply it :)
I think that I might have solved it, or at least parts of it with this PHP (this is really just a small modification of this code - adding $cart_item_data https://quadmenu.com/add-to-cart-with-woocommerce-and-ajax-step-by-step/):
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
function woocommerce_ajax_add_to_cart() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
$variation_id = absint($_POST['variation_id']);
// This is where you extra meta-data goes in
$cart_item_data = $_POST['meta'];
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
// Remember to add $cart_item_data to WC->cart->add_to_cart
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $cart_item_data) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
WC_AJAX :: get_refreshed_fragments();
} else {
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
echo wp_send_json($data);
}
wp_die();
}
Where this is part of the JS-function:
var data = {
action: 'woocommerce_ajax_add_to_cart',
product_id: 10324,
quantity: 1,
variation_id: activeVariationId,
meta: metaData
};
$.ajax({
type: 'post',
url: wc_add_to_cart_params.ajax_url,
data: data, ...........
I am going to have to test it some more, as it seems now that all the data-fields also gets posted in the cart, email etc - I probably have to rewrite something so that some parts of it is hidden for the "non-admin", but available for me later on + adding custom product thumbnail on add to cart.

Method App\Http\Controllers\ConfigSplitCleansingController::show does not exist

I got this error and I cant seem to find the bug.
This is the function in my controller.
class ConfigSplitCleansingController extends Controller
{
public function storeNewArea(Request $request)
{
$setArea = $request->setNewArea;
$decode = json_decode($setArea, true);
$activity = Activities::where('activityCode', $request->activityId)->first();
$lastrow = PubCleansingScheduleStreet::join('pubcleansingschedule_activity','pubcleansingschedule_street.pubCleansingActivityId', '=', 'pubcleansingschedule_activity.id')
->select('pubcleansingschedule_street.rowOrder')
->where('pubcleansingschedule_activity.pubCleansingScheduleParkId',$request->scheduleparkId)
->where('pubcleansingschedule_activity.activityId',$activity->id)
->orderBy('pubcleansingschedule_street.rowOrder','desc')
->limit(1)->first();
$row = $lastrow->rowOrder;
foreach ($decode as $key => $value) {
$row = $row + 1;
if($value['id'] == 0){
$schedulestreet = PubCleansingScheduleStreet::find($request->schedulestreetId);
$newsplit = new CleansingSplit;
$newsplit->pubCleansingId =$schedulestreet->pubCleansingId;
$newsplit->streetId =$schedulestreet->streetId;
$newsplit->activityCode =$schedulestreet->activityCode;
$newsplit->serviceType =$schedulestreet->serviceType;
$newsplit->value =$value['value'];
$newsplit->frequency =$schedulestreet->frequency;
$newsplit->save();
$newstreet->pubCleansingActivityId =$schedulestreet->pubCleansingActivityId;
$newstreet->pubCleansingId =$schedulestreet->pubCleansingId;
$newstreet->streetId =$schedulestreet->streetId;
$newstreet->streetName =$schedulestreet->streetName;
$newstreet->streetType =$schedulestreet->streetType ;
$newstreet->activityCode =$schedulestreet->activityCode;
$newstreet->serviceType =$schedulestreet->serviceType;
$newstreet->value =$value['value'];
$newstreet->frequency =$schedulestreet->frequency;
$newstreet->frequency_PJ =$schedulestreet->frequency_PJ;
$newstreet->rowOrder =$row;
$newstreet->save();
}
else {
$newstreet = CleansingSplit::find($value['id']);
$newstreet->value = $value['value'];
$newstreet->save();
}
}
return response()->json($newstreet);
}
}
This is my model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CleansingSplit extends Model
{
//
protected $table = 'publiccleansingsplit';
protected $fillable = [
'id',
'pubCleansingId',
'streetId',
'activityCode',
'serviceType',
'value',
'frequency'
];
}
Route
Route::post('splitpembersihan/storeNewArea', ['as' => 'storeNewArea', 'uses' => 'ConfigSplitCleansingController#storeNewArea']);
And this is the ajax
$.ajax(
{
url: '{{url("splitpembersihan/storeNewArea")}}',
type: 'post',
data: {
"setNewArea": setarray,
"scheduleparkId": scheduleparkId,
"schedulestreetId": schedulestreetId,
"splitId": splitId,
"activityId" : #if(isset($schedulestreet->activityCode))"{{ $schedulestreet->activityCode}}"#endif,
"_token": token
},
success: function (data)
{
alert("success");
window.location.replace('/splitpembersihan/splitBin/'+ PubCleansingID +'/splitValueArea');
},
error: function (data)
{
alert("error");
}
});
The error is the opposite. The data is stored successfully. However, it shows the error alert instead of the success alert. And if I just press the submit button without submitting anything, it shows the success alert.

Trying to implement a comments system with laravel

Trying to implement a comments system using pusher on my laravel project. Everything seems to be in order, however every post request which is meant to send the input data to the database returns with error 500.
Used F12 on firefox to monitor what gets sent to /tip/select, it seems that it passes the text of the comment just fine, so it could be the issue with the controller.
Routes
Route::get('/tip/select','TipController#select');
Route::post('/tip/select', 'TipController#addComment');
Comment model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Zttp\Zttp;
use App\model\User;
use App\Tip;
class Comment extends Model
{
protected $guarded = [];
protected $table='comments';
//protected $fillable=['tip_id','user_id','body'];
public static function moderate($comment)
{
$response = Zttp::withoutVerifying()->post("https://commentator.now.sh", [
'comment' => $comment,
'limit' => -3,
])->json();
if ($response['commentate']) {
abort(400, "Comment not allowed");
}
}
public function tip(){
return $this->belongsTo('App\Tip');
}
public function user(){
return $this->belongsTo('App\model\User');
}
}
Controller
use Pusher\Laravel\Facades\Pusher;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Input;
use DB;
use Image;
use App\Tip;
use App\model\User;
use App\Subcategories;
use App\Category;
use App\City;
use App\Comment;
use App\CityAreas;
//use App\Http\Requests\TipFormRequest;
class TipController extends Controller
{
public function select(){
//$db=DB::table('tips')->orderBy('created_at','desc');
$data=Tip::get();
$url = Storage::disk('s3');
//$data=Tip::paginate(10);
//$data=$db->get();
// dd($data);
$comments = Comment::orderBy('id')->get();
return view('tip', compact('data', 'url','comments'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function create(){
$categories=Category::all();
$cities=City::all();
return view('tip.create',compact('categories','cities'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function store(Request $request, City $city, Category $category){
$this->validate($request, [
'image' => 'image|nullable|max:1999']);
$tipsnew = new Tip;
$tipsnew->title = $request->title;
$tipsnew->description = $request->description;
$tipsnew->category_id = $request->category;
$tipsnew->city_id = $request->city;
$tipsnew->user_id = auth()->id();
$tipsnew->url = $request->url;
if ($request->hasFile('image')) {
try{
$file = $request->file('image');
$name = time() . '.' . $file->getClientOriginalExtension();
$img = \Image::make($file->getRealPath());
$img->fit(1080);
$img->stream();
Storage::disk('s3')->put('tip'.'/'.$name, $img->__toString());
$tipsnew->image = 'tip'.'/'.$name;
}
catch (\Exception $e)
{
$response = [
'information' => 'Error. Something went wrong. Please try again',
];
$statusCode = 400;
return response()->json($response, $statusCode);
}
}
$tipsnew->save();
return redirect ('tip/create')->with('status','your tip is created');
}
public function edit($id){
$tip=Tip::whereId($id)->firstOrFail();
$categories=Category::all();
$selectedCategories=$tip->categories->lists('id')->toArray();
return view('tip.edit',compact('tip','categories','selectedCategories'));
}
public function search(Request $request, City $city, Category $category, User $user){
$q = $request->get('q');
if ($q != ""){
$tips = Tip::where('title','LIKE','%'.$q.'%')
->orWhere('description','LIKE','%'.$q.'%')
->orWhereHas('user', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->orWhereHas('city', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->orWhereHas('category', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->get();
if(count($tips) > 0)
return view('tip.search', ['tips' => $tips]);
}
}
public function addComment(Request $request)
{
$data = $request;
Comment::moderate($data['text']);
$comment = Comment::create($data);
Pusher::trigger('comments', 'new-comment', $comment, request()->header('X-Socket-Id'));
//add creation of new comment to DB
$commentnew = new Comment;
$commentnew->user_id = Auth::user()->id();
//$commentnew->tip_id= $request->post(['tip_id']);
$commentnew->body = $request->text;
$commentnew->save();
return $comment;
}
}
Snippet of the blade
<h3>Comments</h3>
<form onsubmit="addComment(event);">
<input type="text" placeholder="Add a comment" name="text" id="text" required>
<input type="hidden" name="tip_id" id="tip_id" value="{{$val->tip_id}}">
<input type="hidden" name="username" id="username" value="{{Auth::user()->name}}">
<button id="addCommentBtn">Comment</button>
</form>
<div class="alert" id="alert" style="display: none;"></div>
<br>
<div id="comments">
#foreach($comments as $comment)
<div>
<small>{{ $comment->username }}</small>
<br>
{{ $comment->text }}
</div>
#endforeach
</div>
<!--jQuery script used to be here -->
<script>
function displayComment(data) {
let $comment = $('<div>').text(data['text']).prepend($('<small>').html(data['username'] + "<br>"));
$('#comments').prepend($comment);
}
function addComment(event) {
function showAlert(message) {
let $alert = $('#alert');
$alert.text(message).show();
setTimeout(() => $alert.hide(), 4000);
}
event.preventDefault();
$('#addCommentBtn').attr('disabled', 'disabled');
var data = {
text: $('#text').val(),
username: $('#username').val(),
tipid: $('#tip_id').val(),
};
fetch('/tip/select', {
body: JSON.stringify(data),
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
'x-socket-id': window.socketId
},
method: 'POST',
mode: 'cors',
}).then(response => {
$('#addCommentBtn').removeAttr('disabled');
displayComment(data);
showAlert('Comment posted!');
})
}
</script>

Categories

Resources