Help needed on running a MYSQL script in the background of a web page and taking different actions dependent on the result - ajax

I have a form on a web page, with one field to enter a code, to search for a property.
On clicking 'submit' I want to be able to run a script in the background without leaving the page.
The script will need to run a MYSQL statement which will have one of these results:
The property code does not exist, so display a Javascript Alert saying it does not exist.
The property is for sale, so call an existing javscript function 'saleSubmit(propertyCode)' to overwrite the exsiting web page with a new page sale.php for that property code
The property is for rent, so call an existing javscript function 'rentSubmit(propertyCode)' to overwrite the exsiting web page with a new page rent.php for that property code
The property is for sale and rent, so display 2 checkboxes within a div on the page to choose either the sales details or the rental details.
Can anybody point me in the right direction here?
Hi Nick - I think I screwed the system up a bit as I initially posted a question, then created an account which would not let me comment on the thread.
The status of the query is as simple as: does not exist, sale, rent, sale & rent
Extra advice would be really appreciated as I am problems googling for examples or a tutorial to point me in the right direction.
I first took this approach when I was looking at this problem to check that the form and Select statement were working correctly. So my form code looked like this:
<form name="idsearch" action="" method="post" onsubmit="xmlhttpPostForm('includes/idsearch-response.php', 'idsearch', 'idSearchResult', '<img src=\'images/loading.gif\'>'); return false;">
<input type="text" id="idRefNo" name="idRefNo" value="Enter Property Code" onfocus="this.value='';" />
GO <input type="image" src="img/template/search2.gif" alt="Click to Search for Properties"/>
and the php code called looked like this:
$idRefNo = $_POST['idRefNo'];
$query = "SELECT DISTINCT * FROM property WHERE property.Title = '".$idRefNo."' AND suspend != 'Yes'"; $result = #mysql_query ($query);
if ($result) { // If the query runs ok
if ($result != "") {
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
if ($row["BaseRental"] > 0 AND $row["Saleprice"] > 0) {
echo 'This property is for RENT and for SALE <br/>';
} else if ($row["BaseRental"] > 0) {
echo 'This property is for RENT only <br/>';
} else if ($row["Saleprice"] > 0) {
echo 'This property is for SALE only <br/>';
} else {
echo 'DOH! What is going on here!!! <br/>';
}
}
As I said above I would appreciate it if you could point me in the right direction to achieve what I want to do at the beginning of this thread.

First of all let's differentiate between the page(client) and your mysql database(server). Your page will have to send some request to your server which triggers a script to query the database. The result of that query is returned as a response to your page.
You could send a request by using javascript and the xmlhttprequest or try jquery which offers very simple methods to make requests ($.ajax(...)).
Your server and the script which queries your db should then return some meaningful status back to your client which has to interprete the result: Doing alerts, showing your div or whatever you'd like to do. I suggest returning the response as json which can be directly used in javascript without any parsing hassle. If the status of your query as simple as: does not exist, sale, rent, sale & rent. You could go as far and encode those as plaintext numbers, no json needed.

Related

Best strategy to avoid Ajax roundtrips when updating databases in Laravel

Let's say I have a table with data in the rows coming from a database. On each row of this table there are helper buttons. These buttons perform instant operations on the database, such as setting a status code (for example sold, blocked, in progress), changing an invoice date for the row (for example from 18/11/2022 to null) and so on..
What I would like is that when a user clicks on one of these buttons, an ajax function will performs a request to the related controller that will show a modal box asking for confirmation (not a JS alert but HTML code that comes from a blade component).
So, giving a basic example in the case of the change of status code for the row, what I would do is first set up a route of this type:
Route::post('/status', [TableController::class, 'status']);
after that i will build my controller(using the related model Table) in a way that if the action value coming from the ajax request is confirm(the one coming from the confirmation modal), I will continue with the data update, if instead the action is something different such as status(the one coming from the helper button), then I will bring up my confirmation modal
class TableController extends Controller {
// Change status
public function status(Request $request){
if( $request['action'] == 'confirm' ) {
// Update DB
Table::where('id', $request->id)->update(['status' => 822]);
} else {
$id = $request->id;
// Show confirmation modal
return \Blade::render('<x-confirm :title="$title" :action="$action" :id="$id" />',
[
"title" => "Vuoi bloccare le seguenti disponibilità? ".$id ?,
"action" => "status",
"id" => $id
]);
}
}
If you notice the return of component part here
// Show confirmation modal
return \Blade::render('<x-confirm :title="$title" :action="$action" :id="$id" />'
I'm passing to the component the id of the row, and the action to perform, those datas will be usefull for the next ajax request coming from the confirmation modal, that will update the row in the database. But basically what is happening here?
Send data from frontend to the controller(id of the row, status action, status code).
Send back the same data from the backend to modal component to fill the ajax confirmation request.
Resend back to the server the same data to catch the confirm statement and update the database.
This kind of approach always worked for me, but when things becomes complex(let's say that I have different kind of helpers like I said before, in example remove a date, change the owner, set some flags etc) this will become a mess, because I have everytime to send back the same data that I just received.
So my question:
Is there a way to avoid this thing to sending back and forward those datas? like something in the middle that stores what am I doing in the current session and can inform the modal box without this round trip? Also i am really thinking that my approach is completely wrong and out of mind, so i have to see things from a different point of view? This is because I am self-taught so I certainly have some gaps that I would like to fill.

In Zoho Creator unable to pass the decision from Zoho Workflow (deluge script) to Zoho Form

I have a calculator whose output i need to display on Submit button. The output comes from a decision tree running in Zoho Workflow module using deluge script.
1) Have tried storing the output in workflow as a string and then passing it back to a form field
2) Tried creating a zoho page for output display but unable to link output of workflow and zoho page
if(input.Price > input.Income)
{
if(input.EMI_Exp < 0.6)
{
info "Take the Personal Loan as you can easily manage the EMI.
If you choose a credit card then you will mess your cashflow";
}
else
{
info "No Personal Loan, No Using Credit Card. You are stretching
yourself by purchasing this";
}
}
else
Need to pass the info information to a decision box ( text) in Zoho form.
On submit of the form, if you are willing to display a message to the user, you can make use of two things page or stateless form.
Page:
Create a page on creator and names it as Message ( You can name it as
you wish )
Add parameters to the page by name recordID ( datatype of
the variable is string & can have any name ).
On page fetch record information from the form and using recordID( convert into
to long as it is string whereas ID is bigint ). i.e
response = FormName[ID == recordID.toLong()]
if(response.EMI_Exp < 0.6)
{
%><p>
Take the Personal Loan as you can easily manage the EMI. <br>
If you choose a credit card then you will mess your cashflow
<p><%
}
else
{
%>
<p>
No Personal Loan, No Using Credit Card. You are stretching
yourself by purchasing this
</p>
<%
}
}else{
%>
<p>
Thank you!!!
</p>
<%
}```
On click of submit button use open url :
openUrl("#page:pageLinkName?zc_LoadIn=dialog&recordID="+input.ID,"same window"), using the script you can open a dialog box
Stateless Form:
Create a stateless form ( Name it as Message or anything you want)
Add two field a single-line text field and name it as recordID and
note field and keep it empty without any value and name it as
Message
On load hide recordID field and using recordID fetch record details
i.e
response = FormName[ID == recordID.toLong()];
if(response.Price > response.Income) {
if(response.EMI_Exp < 0.6)
{
input.Message = "Take the Personal Loan as you can easily manage the EMI.
If you choose a credit card then you will mess your cashflow";
}
else
{
input.Message = "No Personal Loan, No Using Credit Card. You are stretching
yourself by purchasing this";
} }
else{ input.Message= "Thank you !!!" }
On Submit of calculator form using following script :
openUrl("#Form:formLinkName?zc_LoadIn=dialog&recordID="+input.ID,
"same window")```
, using the script you can open a dialog box
Hope this could help you.

Prestashop: how to display messages in the cart

i'm working in a quota module for PrestaShop 1.6 and in one of the features is that a need to display a message in the cart's page and in that modal that opens when you add an item to the cart from the home page.
I'm working with the hookCart the hook function, public function hookCart($params), is in my module's class. From it I can get the instance of the Controller like this $this->context->controller
My question is how to display messages in these two views? I tried adding them to the errors array. I can see the message but not the way I'm supposed to display. I would like to display in those alert classes from bootstrap.
The views:
Can you help me?
To display a message on the checkout page you can use whatever front controller hook you want. I guess the one that makes most sense would be displayTop. We won't be outputting any html to the top but just add a message to the controller's errors array.
public function hookDisplayTop()
{
$controller = $this->context->controller;
if ($controller->php_self != 'order' && $controller->php_self != 'order-opc') {
return false;
}
/*
You can do custom logic here if you want to display message only
on some conditions or only on specific step of the checkout
*/
$controller->errors[] = $this->l('Some message');
return false;
}
For the popup the things get messy because:
Popup doesn't have an error display area
Blockcart AJAX uses weird logic that calls CartController which includes blockcart-ajax.php which loads blockcart module method which loads a JSON template file to output data (???)
One way to do this is to use the hook actionCartSave. This hook gets executed on pretty much all cart operations, so we need to make sure we are adding our message when a product is added to cart, uses ajax etc.
public function hookActionCartSave()
{
// If cart doesn't exist or product is not being added to cart in ajax mode - do nothing
if (!$this->context->cart || !Tools::getValue('id_product) || !Tools::getValue('add') || !Tools::getValue('ajax')) {
return false;
}
/*
You can do custom logic here if you want to display message only
on some conditions
*/
$this->context->smarty->assign('mycartpopupmessage', $this->l('Message');
return false;
}
Then you will have to modify themes/default-bootstrap/modules/blockcart/blockcart-json.tpl file to add your message into JSON template.
...
"wrappingCost": {$wrapping_cost|json_encode},
"nbTotalProducts": {$nb_total_products|intval},
"total": {$total|json_encode},
{if isset($mycartpopupmessage)}
"mycartpopupmessage": {$mycartpopupmessage|json_encode},
{/if}
....
Then you need to modify themes/default-bootstrap/js/modules/blockcart/ajax-cart.js and add the following
if (jsonData.mycartpopupmessage) {
$('#layer_cart .alert-message').html(jsonData.mycartpopupmessage);
$('#layer_cart .alert').removeClass('hidden');
}
else {
$('#layer_cart .alert').addClass('hidden');
}
And at last modify themes/default-bootstrap/modules/blockcart/blockcart.tpl
and add alert div
<div class="alert alert-danger hidden">
<button data-dismiss="alert" type="button" class="close">×</button>
<p>{l s='There is 1 error' mod='mymodule'}</p>
<ol>
<li class="alert-message"></li>
</ol>
</div>
Now you should be getting a bootstrap alert inside a popup.
Quite some native prestashop modules haven't been (I guess) updated in years as a lot of them are good candidates for an extensive rework or at least compliant with the MVC workflow which would make modifications like yours much more simple.

Download raw data in Joomla component

I have written a Joomla component which is working well. I now want to add a button to an admin list view that when clicked automatically starts a CSV download of only the items selected in the list.
I'm OK with the model logic, the problem I've got is passing the selected cids or presenting raw output without the template.
If I use JToolBar's appendButton function to add a 'Link' type button, then I can send the user to a URL with 'format=raw', but I can't send information about which items were checked.
If I use JToolBarHelper::custom to add a custom list button, then I can send the information about which buttons were checked, but I can't send format=raw
As far as I can see there are two solutions, but I don't know how to implement either of them. Option one would be to force templateless raw output without a URL parameter of format=raw. Option two would be to set a hidden variable with format=raw in the admin form.
Any help would be appreciated
I've solved this as follows:
I added this hidden field to the admin form
<input type="hidden" name="format" value="html" />
Then subclassed JToolbarButtonStandard overriding the _getCommand with
protected function _getCommand($name,$task,$list)
{
JHtml::_('behavior.framework');
$message = JText::_('JLIB_HTML_PLEASE_MAKE_A_SELECTION_FROM_THE_LIST');
$message = addslashes($message);
if ($list)
{
$cmd = "if (document.adminForm.boxchecked.value==0){alert('$message');}else{document.getElementById('adminForm').format.value='raw'; Joomla.submitbutton('$task')}";
}
else
{
$cmd = "document.getElementById('adminForm').format.value='raw'; Joomla.submitbutton('$task')";
}
return $cmd;
}
So that when the button was clicked it changed the format parameter from html to raw.
I'm not going to mark this as solved in case anyone has any better ideas

client side validation not working for model window / ajax-loaded-form in yii

I am using Yii-user extension in the main layout i have a sign up link which is common to all the Cmenu
view/main layout
echo CHtml::link('Signup','#',array('id'=>'regi'));
$("#regi").click(function(){
$.ajax({
type:'GET',
url:'<?php echo Yii::app()->request->baseUrl;?>/index.php/user/registration',
success:function(res){
$("#dispdata").show();
$("#dispdata").html(res);
}
});
});
<div id="dispdata"><div>
**yii user extension **renders this perfectly and even submit its correctly if form values a re valid.
but if the values are incorrect and blank it redirect to url .../user/registration
which is not what my need .I need guidance what do i do such that if the values are incorrect or blank it should not redirect and display the errors in model window.
I did tried but hardly could get the satisfied results
if i place the following the model window itself doesnt appear what do i do
module registrationController i placed
....//some code here (**in yiiuser register controller**)
if ($model->save()) {
echo CJSON::encode(array(
'status'=>'success',
));
}
....//some code here...
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderPartial('registration',array('model'=>$model,),false,true);
in module view registration
<?php echo CHtml::ajaxSubmitButton(Yii::t('registration'),CHtml::normalizeUrl(array('user/registration','render'=>false)),array('dataType'=>'json',
'success'=>'function(data) {
if(data != null && data.status == "success") {
$("#registration-form").append(data.data);
}
}')); ?>
can anyone please guide me am working past 10 ten days tried every hook or crook method but could not obtain the results......how can the model window with client side validation be done appear..... Please guide me or let me know something better can be done
rules in registration model
if (!(isset($_POST['ajax']) && $_POST['ajax']==='registration-form')) {
array_push($rules,array('verifyCode', 'captcha', 'allowEmpty'=>!UserModule::doCaptcha('registration')));
as well was not with attributes for reqired field
have changed to
array_push($rules,array('verifyCode', 'captcha','message' => UserModule::t("captcha cannot be blank.")));
and added the verifycode to required field
yet not working,
The simple way is using render method in your Ajax action and creating empty layout for this action. If you do so, validation scripts will be included in the server response. Also you need to exclude jquery.js and other script with Yii::app()->clientScript->scriptMap and include them in main layout always.

Resources