php file_put_contents take file longer than script executes - javascript

If I don't use sleep(3). Page refresh and take old file. Or I use timer in js before reload it's help. But I think it's wrong way. I don't understand how return $ajax success after file_put_contents finished finally.
class OrderparamController extends FrontEndController
{
public function actionIndex($typeproduct = OrderService::TypePrintBannerCloth) {
$forms = $this->requireFile('order-forms.php');
$tplParams=array(
'id_order' => $typeproduct,
'forms' => $forms
);
$this->render('form',$tplParams);
}
/**
* Require file
*/
protected function requireFile($file_name){
$configFile = YiiBase::getPathOfAlias('application.cache').'/'.$file_name;
$handle = fopen($configFile, "r");
fclose($handle);
require $configFile;
return $forms;
}
/*
* Удалить параметр
*/
public function actionDeleteparamoption() {
$configFile='order-forms.php';
$forms=$this->requireFile($configFile);
$keyfield = $_POST['keyfield'];
$id_order = (int)$_POST['id_order'];
$numoption = $_POST['numoption'];
unset($forms[$id_order]['fields'][$keyfield]['options'][$numoption]);
if ($this->writeFile($forms,$configFile)) {
$answer=array(
'ok' => true,
);
} else {
$answer=array(
'ok' => false,
);
}
**sleep(3);**
echo json_encode($answer);
}
}
I use js for sending ajax
$('.js-btn-delete').on('click',function(){
var request ={
keyfield : $(this).data('keyfield'),
id_order : Var.id_order,
label : $(this).data('label'),
numoption : $(this).data('option'),
}
$.ajax({
url: '/orderparam/deleteparamoption',
type: 'POST',
data: request,
dataType: 'json',
async: true,
success: deleteOrderParamResult
})
});
function deleteOrderParamResult(data){
if (data.ok) {
var num=intVal($('.param-option').index($('.param-option:visible')));
document.cookie = "viewOption="+num;
location.reload();
} else {
alert('ошибка');
}
}

Related

pagination automatically sending multiple requests with laravel

hello guys recently I am developing a new website which have multiple filters so I use the session-based filter with laravel
it is working fine if I use only the Show filter one time but when I switch to another filter, it is sending multiple requests(as much time I repeat the filter)
when someone clicks the filter this code will run
<------- Laravel route where I am sending a request it returns me a HTML file and I am rendering in my div tag where I have all lists ------->
public function filter(Request $request){
$course = Course::query();
if (isset($request->show)) {
Session::put('show',$request->show);
$show = $request->show;
}
if(isset($request->type)){
$course->where('type',$request->type);
}
if (isset($request->ratting)) {
$course->where('ratting','>=',$request->ratting);
Session::put('ratting',$request->ratting);
}
if(isset($request->short_type))
{
$type = $request->short_type;
$course = $this->checkSort($course,$type);
Session::put('short',$type);
}
if (Session::has('search')) {
$search = Session::get('search');
$course->where(function($q) use ($search){
$q->where('title', 'LIKE', '%'.$search.'%')
->orWhere('slug', 'LIKE', '%'.$search.'%')
->orWhere('description', 'LIKE', '%'.$search.'%')
->orWhere('keyword', 'LIKE', '%'.$search.'%');
});
}
if(Session::has('show') && !isset($request->show)){
$show = Session::get('show');
}
if(Session::has('ratting') && !isset($request->ratting)){
$course->where('ratting','>=',Session::get('ratting'));
}
if(Session::has('short') && !isset($request->short)){
$type = Session::get('short');
$course = $this->checkSort($course,$type);
}
$course->select('id', 'title', 'slug', 'description', 'created_at', 'regular_price', 'sell_price', 'thumbnail','ratting','status');
return view('site.courses.ajax-listing',[
'active' => 'courses',
'type' => $request->type,
'courses' => $course->where('status',1)->paginate(isset($show) ? $show : 10),
]);
}
public function checkSort($courses,$type){
if($type == "alphabetically_a_z")
{
$courses->orderBy('title', 'ASC');
}
if($type == "alphabetically_z_a")
{
$courses->orderBy('title', 'DESC');
}
if($type == "date_new_to_old")
{
$courses->orderBy('created_at', 'ASC');
}
if($type == "date_old_to_new")
{
$courses->orderBy('created_at', 'DESC');
}
if($type == "popular")
{
$courses->where('is_popular', 1);
}
return $courses;
}
<------------------------------------------->
In the search input have route where i will send request
<input type="text" hidden id="search-url" value="{{route('ajax-search-course')}}">
<--------- Javascript Code ----->
$(document).ready(function(){
var url = "{{route('ajax-search-course')}}";
var Jobtype = "1";
var value;
$("input[name='RattingRadioDefault']:radio").change(function(){
value = $("[name=RattingRadioDefault]:checked").val();
ajaxFilter(url + "?ratting="+value+ "&type=" + Jobtype);
});
$("input[name='ShowingRadioDefault']:radio").change(function(){
value = $("[name=ShowingRadioDefault]:checked").val();
ajaxFilter(url + "?show=" + value + "&type=" + Jobtype);
});
$("input[name='ShortingRadioDefault']:radio").change(function(){
value = $("[name=ShortingRadioDefault]:checked").val();
console.log("this is value",value,$("[name=ShortingRadioDefault]:checked").val());
ajaxFilter(url + "?short_type=" + value + "&type=" + Jobtype);
});
});
function ajaxFilter(url, data = null) {
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function(data) {
// console.log("this is return data",data);
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function(jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
console.log("this is error", errorMessage);
}
});
}
<------------- Javascript pagination page ----------->
//Ajax Paginatio
$(document).one('click', '#ajaxPagination ul li a', function (e) {
console.log("ajax pagination function is running",$(this).attr("href"),"and",$(e).attr("href"));
e.preventDefault();
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
var url = $(this).attr("href")+"&"+ "type=" + $('#data_sort_filter').attr('job-type'),
data = '';
e.preventDefault();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function (jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
}
});
});
i was trying to add a multiple filters system with the session. now i have this error pagination function running as much i am repeating filters i want to solve this please help me it is a very important to project for me

Calling method in PHP file from separate JavaScript file

I have a javascript file from which I am trying to make a ajax call to execute method of a different php file.
Javascript file - a.js
function update() {
$.ajax({
url:"abcd.php",
type: "POST",
dataType: 'json',
data: {"updateMethod()"}
success:function(result){
console.log(result);
}
});
}
PHP file - abcd.php
<?php
class abcd {
public function updateMethod() {
//execute this part of the code
}
public function insertMethod() {
}
public function deleteMethod() {
}
}
I am not able to make a call to the PHP method. What is wrong with my AJAX query or what do I need to do in PHP file side to call the method.
I don't know what you try to do, but you can do it this way:
function update() {
$.ajax({
url:"abcd.php",
type: "POST",
dataType: 'json',
data: {methodName: "updateMethod"},
success:function(result){
console.log(result);
}
});
}
On server side:
<?php
class abcd {
public function updateMethod() {
//execute this part of the code
}
public function insertMethod() {
}
public function deleteMethod() {
}
}
$abcd = new abcd();
$method = $_POST['methodName'];
$result = $abcd->$method();
Remove this line
dataType: 'json',
and send data without json
If you sending json in php must be:
$data = file_get_contents('php://input');
PHP "php://input" vs $_POST
Or beter jquery:
var methodName = "YourMethodName";
var y = "Cymbal";
$.post( "test.php", { methodName: methodName, lastname: y })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Maybe something like this is more secure and I think you also need function arguments for CRUD actions(Not tested):
backend:
class CRUD
{
public function update($args)
{
$input = $args['exampleInput'];
// sanitize input
// prepared query
// $stmt->execute($input);
}
}
function access($class, $method, $args)
{
if (method_exists($class, $method)) {
return call_user_func_array([$class, $method], [$args]);
}
}
$data = file_get_contents('php://input');
access('CRUD', $data->method, json_decode($data->args));
js:
function handleAction(methodName, arguments) {
$.ajax({
url: "crudFile.php";
type: "POST",
data: { method: methodName, args: arguments },
dataType: 'json',
success: function (result) {
console.log(result);
}
});
}
var inputs = {
exampleInput: function () {
return document.getElementById('your-div-id').textContent();
},
};
// usage
handleAction('update', inputs);

Infinite scroll in Symfony using Ajax

I wanted to show products from db using infinite scroll.
Here is my Controller:
$start=0;
$limit= 6;
$query = $repository->createQueryBuilder('classified')
->join('classified.statusId','status')
->andWhere('status.name=:status')
->setParameter('status','active')
->setFirstResult($start)
->setMaxResults($limit)
->getQuery();
$results = $query->getResult();
if ($request->isXmlHttpRequest()){
$list = $this->renderView('search-result.html.twig', [
'results' => $results
]);
$response = new JsonResponse();
$response->setData(array('classifiedList' => $list));
return $response;
}
Ajax:
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
getmoredata();
}
})
function getmoredata() {
$.ajax({
type: "GET",
url: "{{ path('classified_list', {'type' : 'all'}) }}",
dataType: "json",
cache: false,
success: function (response) {
$('.card-deck').append(response.classifiedList);
$('#spinner').hide();
console.log(response);
},
error: function (response) {
console.log(response);
}
});
}
So now what is happening is the first 6 results is repeatedly showing when the scrolling is triggered. I know this is not correct and I don't expect this to work properly. But what I don't know is what is the next step.
So do I need to add paginator or something?
Any help would be appreciated,Thanks!
You need to track whether your ajax is requesting or not, so it will not do request multiple times when window reach the scroll limit. Also, you need to track the offset and whether you have more data to loads. e.g
window.__isFetching = false;
window.__offset = 0;
window.__hasMoreData = true;
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
if(!window.__isFetching && window.__hasMoreData) {
getmoredata();
}
}
})
function getmoredata() {
window.__isFetching = true;
$.ajax({
type: "GET",
// NOTE, you can pass current offset here in url
url: "{{ path('classified_list', {'type' : 'all', }) }}"+"&offset="+window.__offset,
dataType: "json",
cache: false,
success: function (response) {
$('.card-deck').append(response.classifiedList);
$('#spinner').hide();
console.log(response);
// Note that here, server side response must have next offset and hasMoreData attribut.
window.__isFetching = false;
window.__hasMoreData = response.hasMoreData;
window.__offset = response.offset
},
error: function (response) {
console.log(response);
}
});
}
in server side , which is symfony, you might want to do something like:
// Get offset from request query
$start= $request->query->get('offset');
$limit= 6;
$query = $repository->createQueryBuilder('classified')
->join('classified.statusId','status')
->andWhere('status.name=:status')
->setParameter('status','active')
->setFirstResult($start)
->setMaxResults($limit)
->getQuery();
$results = $query->getResult();
if ($request->isXmlHttpRequest()){
$list = $this->renderView('search-result.html.twig', [
'results' => $results
]);
$response = new JsonResponse();
// And add offset and hasMoreData fields in response
$response->setData(array(
'classifiedList' => $list,
'offset' => $start += 1
'hasMoreData' => count($list) < ($limit * &start)
)
);
return $response;

Passing custom error code to ajax error function

I'm trying to pass custom error code to the client-side to ajax error function.
In the server side:
$response = array();
if ( empty($post['parent_id']) ) {
$response = array('error' => true, 'status_code' => -2);
exit();
}
$is_valid_id = RC()->is_valid_id($post['parent_id']);
$row = RC()->get_row_data($post['parent_id']);
if ( ! $is_valid_id ) {
$response = array('error' => true, 'status_code' => -1);
} else if ( ! $row ) {
$response = array('error' => true, 'status_code' => 0);
} else {
$response = json_encode($row);
}
echo $response;
Then I want to check for this status code in my js script, but couldn't find a way to do this (found ways only without trigger the error event).
$.ajax({
url: ajax_url,
data: {
'action': 'rc_parent_sign_in',
'form_data': $('#parent-sign-in-form').serialize(),
'security': security_nonce
},
type: "post",
dataType: "json",
cache: false,
success: function (response) {
var query_vars = $.param(response);
window.location.replace('http://localhost/renecassin/user-registration/?' + query_vars);
},
error: function (response) {
$('.form-control-feedback').addClass('hide');
/* Looking for something like this */
switch ( response.status_code) {
case -2 :
parent_id_form_group.addClass('has-danger').children('#empty-field').
removeClass('hide');
prent_id_input.addClass('form-control-danger');
break;
case -1 :
parent_id_form_group.addClass('has-danger').children('#not-valid-id-feedback').
removeClass('hide');
prent_id_input.addClass('form-control-danger');
break;
default :
parent_id_form_group.addClass('has-danger').children('#id-not-exists-feedback').
removeClass('hide');
prent_id_input.addClass('form-control-danger');
}
}
});
Any help will be appreciate.
It's because the response will go to your response callback, you are successfully returning an object.
The error callback will only be called if the request itself failed (timeout,404 etc..)
You need to handle your internal error codes in your success callback

Wait for ajax response using a yii2 form

I am implementing a form that request a process with ajax to sync 2 databases and I need to wait until the process finish.
In my form I have the flowing code to send the db credentials:
<div class="col-lg-offset-1 col-lg-11">
<?=
Html::a('Sync Databases', ['runsync'], [
'class' => 'btn btn-primary',
'id' => 'ajax_link_02',
'data-on-done' => 'linkFormDone',
'data-form-id' => 'syncdb_form',]
)
?>
and I also register the js with the ajax
function handleAjaxLink(e) {
e.preventDefault();
var
$link = $(e.target),
callUrl = $link.attr('href'),
formId = $link.data('formId'),
onDone = $link.data('onDone'),
onFail = $link.data('onFail'),
onAlways = $link.data('onAlways'),
ajaxRequest;
$("#show_msg").html("Loading.... please wait...");
ajaxRequest = $.ajax({
type: "post",
dataType: 'json',
url: callUrl,
data: (typeof formId === "string" ? $('#' + formId).serializeArray() : null)
});
// Assign done handler
if (typeof onDone === "string" && ajaxCallbacks.hasOwnProperty(onDone)) {
ajaxRequest.done(ajaxCallbacks[onDone]);
}
// Assign fail handler
if (typeof onFail === "string" && ajaxCallbacks.hasOwnProperty(onFail)) {
ajaxRequest.fail(ajaxCallbacks[onFail]);
}
// Assign always handler
if (typeof onAlways === "string" && ajaxCallbacks.hasOwnProperty(onAlways)) {
ajaxRequest.always(ajaxCallbacks[onAlways]);
}
}
var ajaxCallbacks = {
'linkFormDone': function (response) {
$('#show_msg').html(response.body);
}
}
The ajax call works fine and call the controller:
public function actionRunsync() {
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = new \app\modules\admin\models\syncdb();
$response = $model->runSyncDb($_POST);
$res = array(
'body' => $response,
'success' => true,
);
return $res;
}
}
But is not waiting to the process
$model->runSyncDb($_POST)
to finish. If I comment the process and add a text it works fine but not if the process takes long.
What am I doing wrong?
I just added async false to the ajax request:
async: false,
so now the ajax is like this:
ajaxRequest = $.ajax({
type: "post",
async: false,
dataType: 'json',
url: callUrl,
data: (typeof formId === "string" ? $('#' + formId).serializeArray() : null)
});
Not sure the best way but works perfectly...

Categories