reload just a part of a page after ajax request - php

I am trying to add a search module for my data listing .
my function that i post the request to, renders a view.
how can i load the list grid after pushing search button?
should i echo a html code, or render a view and write that view in that position?
I am totally confused ...
public function actionSell() {
$cond="";
if($_POST) {
foreach ($_POST as $key => $value) {
$_POST[$key] = str_replace(',', '', stripslashes(mysql_real_escape_string($value)));
}
$melk_id = $_POST['melk_id'];
$city_id = $_POST['city_id'];
$cost_from = $_POST['cost_from'];
$cost_to = $_POST['cost_to'];
$metraj_from = $_POST['metraj_from'];
$metraj_to = $_POST['metraj_to'];
if($melk_id) $cond .= ' and melk_id='.$melk_id;
if($city_id) $cond .= ' and city_id='.$city_id;
if($cost_from) $cond .= ' and cost >='.$cost_from;
if($cost_to) $cond .= ' and cost <='.$cost_to;
if($metraj_from) $cond .= ' and metraj >='.$metraj_from;
if($metraj_to) $cond .= ' and metraj <='.$metraj_to;
}
$dataProvider = new CActiveDataProvider('Data', array('criteria' => array(
'condition' => 'type = 0 '.$cond,
'order' => 'id DESC',
),
'pagination' => array('pageSize' => 15)
));
$this->render('sell', array(
'dataProvider' => $dataProvider,
));
}

I'm not a php developer but I'll try yo answer in a jQuery manner.
Suppose you hold your list grid in a container: <div id="container"> //the grid </div>
You fill the container from a View that holds the grid
You have Seach TextBox
<input id="searchBox" type="text" name="SeachTxt" Value="Some text"/>
And a Button :
<input id="SearchBtn" type="button" value="Search Now!">
Next you must have a jQuery ajax post function, like this one:
jQuery("#SearchBtn").click(function(e) {
e.preventDefault();
jQuery.ajax({
url: 'index.php?searchString=' + jQuery("#searchBox").val(),
success: function(result) {
jQuery("#container").html(result);
}
});
});

you could use renderPartial, like
$this->renderPartial('_ajaxContent', array(
'dataProvider' => $dataProvider
), false, true
);

Related

How to implement Polylang functions in my theme's php file?

I am translating a site with Polylang that was created by someone else using a custom theme. Some strings couldn't be found by Polylang, so I need to manually register them for Polylang to see. Now, some of the strings were pretty easy to translate using __():
$args = shortcode_atts([
'link' => 'service',
'text' => __('Get the code now!'),
'title' => __('Code'),
'id' => '',
'class' => 'width300',
], $args, '' );
But I don't know how to translate strings in these scenarios:
$popup = do_shortcode('[popup id="110" link="vacancy" class="" title="Code" text="Get the code now!!" ]');
Or here words Details, Close
$script = '
<script>
$(document).ready(function(){
btn = $(\'.add_vakan_info\'),
popup = $(\'.add_popup\');
btn.click(function(){
var block_info = $(this).closest(\'.vacancy\').find(\'.content\');
if(block_info.hasClass(\'active\')){
block_info.removeClass(\'active\');
$(this).html(\'Details <i class="las la-angle-down"></i>\');
}else{
block_info.addClass(\'active\');
$(this).html(\'Close <i class="las la-angle-up"></i>\');
}
})
popup.click(function(){
var text = $(this).closest(\'.vacancy\').find(\'.title\').text(),
form = $(\'.vacancy_name\');
form.val(text);
})
FileInput();
})
</script>';
Or
else:
$html = '<h4>No vacancy </h4>';
Or
<div class="content col">
<div class="sp-20"></div>
<h4>Description</h4>
'.$description.'
<div class="sp-20"></div>
<h4>Requirements</h4>
'.$requirements.'
<div class="sp-20"></div>
<h4>Conditions</h4>
'.$conditions.'
You need to use Polylang's string translations API.
Step 1. Registering your strings.
// functions.php
add_action('init', function () {
$strings = array(
'no-vacancy' => 'No vacancy',
// Add more strings here...
);
foreach ($strings as $key => $string) {
pll_register_string('theme-' . $key, $string, 'Hardcoded Theme Strings');
}
});
Now these strings will appear in Languages > String translations menu, under the dropdown for Hardcoded Theme Strings
Step 2. Translate the Strings
else:
$html = '<h4>' . pll_e( 'No vacancy' ) . '</h4>';
The value you enter on the back-end in the string translations menu will be used when translating this value.

Can I declare a function inside of the parameter of another function in PHP?

I am writing helper functions that allow me to build tables quickly. I have a function called responsive_table that accepts two parameters: headings, and rows. The rows are dynamic and are pulled from a database. I build an array of rows with a foreach loop because some of the db table rows don't match the contents or order of the html table... some of the cells in the html table contain combinations of db columns, etc. and can't be displayed directly from the db. None of the rows in my HTML table array are being displayed. Nothing from inside of the function that's being declared in the function parameter is being displayed. Here's my code:
<?php
$output = responsive_table(array('<input type="checkbox" name="all">', 'Thumbnail', 'Title', 'Location', 'Author', 'Date Submitted', 'Actions'), function(){
foreach($listing_results as $listing){
$listings[] = array(
'<input type="checkbox" name="delete[]" value="'.$listing['listing_id'].'">',
'<img src="http://placehold.it/50x50" alt="Thumbnail">',
$listing['title'],
$listing['location'],
anchor('members/modify/'.$listing['member_id'], $listing['display_name']),
date($setting['date_format'], $listing['date_submitted']),
array(
array(
'title' => 'Modify Listing',
'color' => 'primary',
'href' => 'listings/modify/'.$listing['listing_id'],
'text' => '<i class="fa fa-pencil"></i>'
),
array(
'title' => 'Delete Listing',
'color' => 'danger',
'href' => 'listings/delete/'.$listing['listing_id'],
'text' => '<i class="fa fa-eraser"></i>',
'confirm' => true
)
)
);
}
return $listings;
});
echo $output;
function responsive_table($headings = array(), $rows = array(), $sortable = false){
$output = '
<div class="table-responsive">
<table data-sortable class="table">
<thead>
<tr>
';
if(count($headings) > 0){
foreach($headings as $heading){
$output .= '
<th>'.$heading.'</th>';
}
}
$output .= '
</tr>
</thead>
<tbody>';
if(count($rows) > 0){
foreach($rows as $row){
$output .= '
<tr>
<td>'.$row.'</td>
</tr>';
}
}
$output .= '
</table>
</div>';
return $output;
}
Yes, what you are looking for is a http://php.net/manual/en/class.closure.php
Any valid PHP code may appear inside a function, even other functions and class definitions. What it looks like your trying to do is work with anonymous functions, also known as closures. Here is a link that might help you out with this PHP anonymous functions.

How to make auto complete form in cakephp?

I am trying to make an auto complete function in CakePHP but did not succeed. I tried the following code.
public function find() {
if ($this->request->is('ajax')) {
$this->autoRender = false;
$country_name = $this->request->data['Country']['name'];
$results = $this->Country->find('all', array(
'conditions' => array('Country.name LIKE ' => '%' . $country_name . '%'),
'recursive' => -1
));
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
echo json_encode($results);
}
}
// Form and jquery
<?php
echo $this->Form->create('Country', array('action' => 'find'));
echo $this->Form->input('name',array('id' => 'Autocomplete'));
echo $this->Form->submit();
echo $this->Form->end();
?>
<script type="text/javascript">
$(document).ready(function($){
$('#Autocomplete').autocomplete({
source:'/countries/find',
minLength:2
});
});
</script>
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
Breaks your JSON structure.
Keep in mind that autocomplete by default expects "label" and value keys in your JSON table, so all the script should do after fetching DB records is:
$resultArr = array();
foreach($results as $result) {
$resultArr[] = array('label' =>$result['Country']['name'] , 'value' => $result['Country']['name'] );
}
echo json_encode($resultArr);
exit(); // may not be necessary, just make sure the view is not rendered
Also, I would create the URL to your datasource in the jQuery setup by
source:'<?=$this->Html->url(array("controller" => "countries","action"=> "find")); ?>',
And try to comment-out (just to make sure if the condition is not met by the request when autocomplete makes its call)
if ($this->request->is('ajax')) {
condition

I want to pause a while loop until user submit a form, so how can I do that?

I have a 25 advertiserids from CJ and now I want to create 2 post in different category of wordpress from each advertiserid given. So I have created following script but it is not pausing for user input, so how can I do that ?
If its not possible with while then is there any other method to do this ? in script $ad is array with advertiser's id value and $adcat is also a array with advertiser's catagory
function cjlinks($n)
{
global $ad, $adcat;
$URI = 'https://product-search.api.cj.com/v2/product-search?website-id=12345678'.
'&advertiser-ids='.$ad[$n].
'&records-per-page=2';
$context = stream_context_create(
array(
'http' => array(
'method' => 'GET',
'header' => 'Authorization: ' .
'my api id'
)
));
$res = new SimpleXMLElement(file_get_contents($URI, false, $context));
return $res;
}
$a = 0;
while ($a < 25)
{
echo 'advertiser id is: '.$ad[$a].'<br/>advertiser - catagory is: '.$adcat[$a]->child.
'<br/>';
if (isset($_SESSION['sumit'])){
$data = cjlinks($a);
$attributes = $data->products->attributes();
if ($attributes->{'total-matched'} == 0){
echo 'No products found ...try again with new keyword.';
}else{
foreach ($data->products[0] as $product)
{
// Sanitize data.
$price = number_format((float)$product->price, 2, '.', ' ');
$image = '<img src="'.$product->{'image-url'} .'" style="float: right"/>';
$pd = $image.$product->description .'<a href="'.$product->{'buy-url'}.
'">...For more details and to buy it click here</a>';
$p = array('post_title' => $product->name,
'post_content' => $pd,
'post_status' => 'publish',
'post_author' => 1,
'post_category' =>array($_GET['cat']));
$pr = wp_insert_post( $p, $wp_error );
echo '<br/>posted...post ID is:'.$pr;
wp_reset_query(); // Restore global post data stomped by the_post().
}
}
}else{
echo 'please complete form';
$a = $a+1;
}
}
?>
<html>
<body>
<form action="catag.php" method="get">
<table>
<tr>
<td><label> Select a catagory from list:</label></td></tr>
<tr>
<?php
foreach($cat as $key=>$val){
echo '<tr><td><input type="radio" value="'.$val->cat_ID.'" name="cat" id="'.$val->cat_ID.'">'.$val->cat_name.'</td></tr>';
}
?>
</tr>
</table>
<input type="submit" name="submit" value="submit">
</form><br>
</body>
</html>
You can not literally "pause" a php script, as php is executed on the server before the page even loads.
To execute any kind of a "pause" you would need to write your function in Javascript or other Client Side (Browser Executed) code, or send something like an Ajax request to a php page that would then update the current page on response.

Input custom attribute value : retrieve and loop in PHP

When I click on buttons I generate some inputs field with custom attributes like that :
<input type='text' name='field["+ i++ +"]' value='' data-kind='title' />
<input type='text' name='field["+ i++ +"]' value='' data-kind='video' />
<input type='text' name='field["+ i++ +"]' value='' data-kind='text' />
I retrieve the 'name' value with a foreach loop in PHP :
$result = array_combine($num, $records);
foreach ($result as $rank => $content)
{
$data = array(
'content' => $content,
'post_id' => $post_id,
'rank' => $rank,
'type' => $this->input->post('field_type') // HERE
);
echo '<pre>';print_r($data);echo '</pre>';
}
To get the 'type' I do a $this->input->post('field_type'); which is given by this :
var field_type = $(":input[data-kind]").attr('data-kind');
$("#field_type").val(field_type' ');
and :
echo '<input type="hidden" id="field_type" name="field_type" value="" />';
But it only returns me the last 'data-kind' value not each one :/
Now i just need to loop the 'data-kind' value for each input fields and retrieve them in my foreach loop
Any help would be very very appreciated !!
Many thanks for your answers, it helped me a lot! But now how can I add the result in my current foreach at 'type' data :
$result = array_combine($num, $records);
foreach ($result as $rank => $content)
{
$data = array(
'content' => $content,
'post_id' => $post_id,
'rank' => $rank,
'type' => // HERE I NEED EACH ATTRIBUTE VALUE
);
echo '<pre>';print_r($data);echo '</pre>';
}
If you want to place all of the data-kind values in the #field_type field, you need something like this:
var fieldTypes = [];
$("input[data-kind]").each(function()
{
fieldTypes.push( $(this).attr('data-kind') );
});
$("#field_type").val(fieldTypes.join(','));
Maybe you've missed the plus sign?
$("#field_type").val(field_type' ');
should be $("#field_type").val(field_type+' ');
This code:
http://jsfiddle.net/PKgkU/17/
Does what you want!
$('input').each(function(el) {
switch ($(this).data('kind')) {
case "video":
kind = 'video';
break;
case "image":
kind = 'image';
break;
case "title":
kind = 'title';
break;
default:
break;
}
$(this).after('<input type="hidden" id="field_type" name="field_type" value="' + kind + '" />');
});

Categories