ebay-api "findItemsByKeywords" pagination in codigniter 3 - codeigniter

Can anyone help me with this issue?
I'm making an API call with 50 entries per page.
I get results, but how can i display the next page ?
How to use pagination ? i don't have a clue where to start.
I really need some help here.
Thanks
This is the controller
if (!empty($_POST['submit'])) {
$aaa = $_POST['kikozasearch'];
}else {
$aaa = $_POST['kikozasearch'];
}
// API request variables
$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1'; // URL to call
$version = '1.0.0'; // API version supported by your application
$appid = ''; // Replace with your own AppID
$globalid = 'EBAY-US'; // Global ID of the eBay site you want to search (e.g., EBAY-DE)
$query = $aaa; // You may want to supply your own query
$safequery = urlencode($query); // Make the query URL-friendly
$i = '0'; // Initialize the item filter index to 0
$apicall = "$endpoint?";
$apicall .= "OPERATION-NAME=findItemsByKeywords";
$apicall .= "&SERVICE-VERSION=$version";
$apicall .= "&SECURITY-APPNAME=$appid";
$apicall .= "&GLOBAL-ID=$globalid";
$apicall .= "&keywords=$safequery";
$apicall .= "&paginationInput.pageNumber=$currentpage";
$apicall .= "&paginationInput.entriesPerPage=50";
//$apicall .= "&paginationOutput.totalPages";
$apicall .= "$urlfilter";
// Load the call and capture the document returned by eBay API
$resp = simplexml_load_file($apicall);
// Check to see if the request was successful, else print an error
if ($resp->ack == "Success") {
$results = '';
// If the response was loaded, parse it and build links
foreach($resp->searchResult->item as $item) {
$pic = $item->galleryURL;
$link = $item->viewItemURL;
$title = $item->title;
// For each SearchResultItem node, build a link and append it to $results
$results .= "<div><img src=\"$pic\"></td><td>$title$pag</div>";
}
}
// If the response does not indicate 'Success,' print an error
else {
$results = "<div class='alert alert-danger'><h4>Oops! The request was not successful. Make sure you are using a valid ";
$results .= "AppID for the Production environment.</h4></div>";
}
echo "We found: ".$resp->paginationOutput->totalEntries . " resaults!";
echo "<div class='alert alert-info'>".$results."</div>";
// echo $resp->paginationOutput->entriesPerPage;
// echo "<br>";
// echo $resp->paginationOutput->totalEntries;
// echo "<br>";
// echo $resp->paginationOutput->totalPages;
echo $currentpage;
echo "/".$resp->paginationOutput->totalPages;
echo "<br />";
$totalpages = $resp->paginationOutput->totalPages;
Here is the post request
<script>
$(document).ready(function(){
$('#form').on('submit', function(info){
info.preventDefault();
$.post('<?php echo base_url();?>index.php/ebayapps/searchitem',
$('#form').serialize(),
function(data){
$('#resaults').html(data);
}
);
}); // keyup
});
</script>

If I understand correctly, you want to load more than one page of results. In this case, you will need to make numerous API requests, depending on the total number of pages you wanted to retrieve in the first place.
So say you want four pages - you need to run your function four times and increment paginationInput.pageNumber in each loop.
I hope this helps.

Related

Show results from live search AJAX

I have a page that shows all results of my database, I have checkboxes and textboxes on the page wich I use to filter the results on the page.
The checkboxes are working, so when you check a textbox the results on the page are getting live filterd. Now I want the same for the textboxes but im stuck how to do it.
this is my code for the textboxes that im using that I also want to use for the textboxes.
<script>
function makeTable(data) {
var tbl_body = "";
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}
function getEmployeeFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.name);
}
});
return opts;
}
function updateEmployees(opts){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
updateEmployees();
</script>
PHP
<?php
$pdo = new PDO('mysql:host=localhost;dbname=records', 'root', '***');
$select = 'SELECT *';
$from = ' FROM overboekingen';
$opts = (isset($_POST['filterOpts']) ? $_POST['filterOpts'] : FALSE);
if (is_array($opts)) {
$where = ' WHERE FALSE';
if (in_array("medewerker", $opts)){
$where .= " OR medewerker = 1 ";
}
if (in_array("medewerker1", $opts)){
$where .= " OR medewerker = 2 ";
}
if (in_array("medewerker2", $opts)){
$where .= " OR medewerker = 3 ";
}
if (in_array("medewerker3", $opts)){
$where .= " OR medewerker = 4 ";
}
if (in_array("medewerker4", $opts)){
$where .= " OR medewerker = 5 ";
}
if (in_array("medewerker5", $opts)){
$where .= " OR medewerker = 6 ";
}
if (in_array("medewerker6", $opts)){
$where .= " OR medewerker = 7 ";
}
if (in_array("medewerker7", $opts)){
$where .= " OR medewerker = 8 ";
}
if (in_array("medewerker8", $opts)){
$where .= " OR medewerker = 9 ";
}
if (in_array("medewerker9", $opts)){
$where .= " OR medewerker = 10 ";
}
if (in_array("medewerker10", $opts)){
$where .= " OR medewerker = 11 ";
}
else {
$where = false;
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
I am not sure how your submit.php works, but I assume you can send keywords as "filterOpts" and the correct JSON is returned? If this is correct, you can make the AJAX call when the user changes the input field and send the value of the input each time:
The first block of code simple calls the updateEmployeesText function whenever the 'input' element is changed (basically whenever the user types). Note that we pass $(this).val as a parameter, which is the text inside the textbox.
$('input').change(function(){
updateEmployeesText($(this).val());
});
This block of code calls submit.php asynchronously. It passes the value of the textbox as a POST parameter. After submit.php has returned, the success function is executed and the table is updated.
function updateEmployeesText(val){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {text: val},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
In your PHP you can now get that value using $val = $_POST['text']. This is the string you want to search for in the DB. I have outlined the steps below:
Establish PDO (already done)
Now use SELECT * FROM your_table WHERE your_field LIKE '% . $val . %' OR ... (you can keep going)
NOTE: the % at the start and end do a partial search, so anything before or after val will also be returned
Now execute the statement and get the array
Encode the array as JSON and return!
Hope this helps!
EDIT for PHP:
This block of code does everything as described above. Note the partial search used in the SQL LIKE statement. The % indicates wildcard characters before or after $val. For example, if the value was 'cat', the script would search for %cat% which would return results for bcat, cat, fcatr, fggcatrr, etc... Essentially anything containing cat. If you wanted a script that ended with cat you would use '%cat' (%$val) and if you wanted something that began with cat you would use 'cat%' (%$val).
$pdo = new PDO('mysql:host=localhost;dbname=records', 'root', '***');
$select = 'SELECT *';
$from = ' FROM overboekingen';
$val = $_POST['val'];
$where = "WHERE medewerker LIKE '%$val%';
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
Don't know if I got your point, you want to have that ajax live feature on inputs as well as checkboxes ?
If so, I'd do something like
$('yourinputselector').keyup(function() {
var user_input = $(this).val();
if (user_input.length > 3) // or any min-chars number
{
// process your ajax request here
}
});

Codeigniter, using set_checkbox in a controller

I've got a loop that generates checkboxes, I have it working within the view, but I would like to move it into the controller and then pass the resulting string to the view. The problem is set_checkbox() doesn't seem to remember the values when it's placed in a controller. It does however seem to set the default value.
Edit: This is only an issue when validation fails and I want checkboxes to retain the users selections. Otherwise code is working as expected. I also have a validation rule set.
$languages_by_name = $this->event_model->get_spoken_languages_by_name();
// Generate array from model data for form_dropdown()
$i = 1;
$list_languages = '';
foreach ($languages_by_name as $row) {
$i == 1 ? $first = TRUE : $first = FALSE; // Check if this is the first radio and precheck it.
$list_languages .= '<label>' . form_checkbox('spokenLanguages[]', $row->event_spoken_id, set_checkbox('spokenLanguages', $row->event_spoken_id, $first)) . ' ' . $row->name . '</label> ';
$i++;
}
// Pass $list_languages to view
$this->data['list_languages'] = $list_languages;
Here's working code for the controller. There might be a more elegant way to do this.
// Generate array from model data for form_dropdown()
$i = 1;
$list_languages = '';
foreach ($languages_by_name as $row) {
// Check if there is post data
if(!$this->input->post('spokenLanguages')) {
// Set first element to checked
$i == 1 ? $selection = TRUE : $selection = FALSE; // Check if this is the first radio and precheck it.
} else {
// Check if this input is checked
if(in_array($row->event_spoken_id, $this->input->post('spokenLanguages'))) {
$selection = TRUE;
} else {
$selection = FALSE;
}
}
$list_languages .= '<label>' . form_checkbox('spokenLanguages[]', $row->event_spoken_id, set_checkbox('spokenLanguages', $row->event_spoken_id, $selection)) . ' ' . $row->name . '</label> ';
$i++;
}
// Pass $list_languages to view
$this->data['list_languages'] = $list_languages;

Google Places API : next_page_token error

I'm gathering information on the location of stores.
The search is:
<?php
...
$url='https://maps.googleapis.com/maps/api/place/search/json?key=[my_key]&location=40.420989,-3.706812&radius=1000030&=&sensor=false';
$body=file_get_contents($url);
...
?>
I return a Json without problems, and indicates that there is another page of results.
I'll be back to make another call as follows
<?php
...
$url2='https://maps.googleapis.com/maps/api/place/search/json?key=[my_key]&pagetoken=ClREAAAAQXKNHPVGCkTC_MdjSqi2T0KBDMWjEu4KF1Ylw1761Po-67AnNSp4zw0wXD4oocGpx4olSl4k2LyklJBl3mBF4VPmxp3IoOCHDRlXVmivaDsSEBuG_V1GvCH1gS5s0LCuy3EaFNXxUzzHhZ5ZRYNfeGHuqewR6Zk7&sensor=false';
$body=file_get_contents($url2);
...
?>
If I run it with the second call I get an error
'status' -> INVALID_REQUEST
But when I paste the ulr2 browser in the result is correct.
How I can fix it?
Thanks
It has something to do with the timing between the requests, if you run them immediately one after the other, the pagetoken isn't valid yet, you have to wait a few seconds between consecutive requests.
This is because google's license terms don't allow you to fetch all the results at once and return them all at once to the user. You should have a user action asking for more results, which adds a delay of a couple of seconds.
sleep(2) between requests will solve the problem
Sleep(1.3) is the shortest amount of time that seemed to work. In other words the next page token becomes active about 1.3 seconds after it is returned in the previous API request.
Please try below code, I have used sleep(2) function for delay between requests, because next pagetoken needs to be validated on google server.
You can even use looping to remove code repetation.
// your query here
$query = "";
// api key here
$api_key = "";
// api call code
try {
echo $url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" . $query . "&location=40.420989,-3.706812&radius=1000030&=&sensor=false&key=" . $api_key;
echo "<br>";
$result = file_get_contents($url);
$query_results = json_decode($result, true);
echo "First set" . "<br>";
print_r($query_results);
$next_page_token = $query_results['next_page_token'];
unset($query_results);
$query_results = array();
sleep(2);
echo $url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" . $query . "&location=40.420989,-3.706812&radius=1000030&=&sensor=false&key=" . $api_key . "&pagetoken=" . $next_page_token;
echo "<br>";
$result = file_get_contents($url);
$query_results = json_decode($result, true);
echo "Second set" . "<br>";
print_r($query_results);
$next_page_token = $query_results['next_page_token'];
unset($query_results);
$query_results = array();
sleep(2);
echo $url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" . $query . "&location=40.420989,-3.706812&radius=1000030&=&sensor=false&key=" . $api_key . "&pagetoken=" . $next_page_token;
echo "<br>";
$result = file_get_contents($url);
$query_results = json_decode($result, true);
echo "Third set" . "<br>";
print_r($query_results);
unset($query_results);
$query_results = array();
} catch (Exception $e) {
$e->getCode();
$e->getLine();
}
The first query will generate 2nd page token.
You just add "&pagetoken=tokenvalue" in your uri.
Sure it work. No alternative option.

repopulating the select list generated from database in codeigniter

Hi. I have the form in which I use form_validation If the user make any mistake (leave some required fields empty), user is redirected back to the form, and the form has been re-populated. All works, except my select , which is generated from the database.
Here is my code from the view:
echo "<select name='parentid'" . set_value("parentid"). ">";
echo '<option value = "0">None</option>';
foreach ($faq_categories as $row => $option) {
echo "<option value=" . $option['catid'] . ">" . $option['categoryname']. "</option>";
}
echo '</select>';
Here is my controller code:
public function displayAddFaqCategoryForm($error = null)
{
$data['title'] = "Add new FAQ Category";
$data['main_content'] = 'addFaqCategory';
$selectWhat = array('tname' => 'faq_categories',
'sortby'=> 'catid',
'how' => 'asc'
);
$this->load->model('selectRecords');
$data['faq_categories'] = $this->selectRecords->selectAllRecords($selectWhat);
$this->load->vars($data);
$this->load->view('backOffice/template');
} // end of function displayAddFaqCategoryForm
And here is the model code:
public function selectAllRecords($selectWhat = array())
{
$data = array();
$tname = $selectWhat['tname'];
$sortby = $selectWhat['sortby'];
$how = $selectWhat['how'];
$this->db->order_by($sortby,$how);
$query = $this->db->get($tname);
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
} // end of function selectAllRecords
I am not getting any error messages, just the select is not repopulated with last used. Any help will be deeply appreciated.
You're using set_value() incorrectly
echo "<select name='parentid'" . set_value("parentid"). ">";
It's meant to output the actual value (for text inputs). This would produce something like:
<select name='parentid'ActualValue>
Which is not how a <select> element is populated, and is invalid HTML. See the correct usage in the Form Helper docs.
You can use set_select(), and it goes on your <option>:
foreach ($faq_categories as $row => $option) {
echo "<option value=".form_prep($option['catid']).'"';
echo set_select('parentid', $option['catid']); // outputs selected="selected"
echo ">".html_escape($option['categoryname'])."</option>";
}
I've taken a few other liberties with your code here as you can see, to be on the safe side (always).
If this is too much of a mess, you might be interested in the form_dropdown() function.

CodeIgniter - Checking to see if a radio button is checked in the database

Im having a bit of trouble putting some code together ... What im trying to do is add some code to the code i have at the moment to check radiobuttons that are checked in the database.
The code i have at the moment takes all roles from the database, outputs them using a foreach statement, but also splits the results into 2 columns, this is what i have at the moment.
<?php
$i = 0;
$output = "";
foreach($roles as $row){
if($i > 0){
$i = 0;
}
if($i == 0) {
$output .= "<div class='box'>";
}
$output .= '<div class="row">';
$output .= ' <input name="_'.$row->key.'" type="radio" id="'.$row->key.'" class="radio" />';
$output .= ' <label for="'.$row->key.'" style="text-transform: lowercase;">'.$row->name.'</label>';
$output .= '</div>';
if($i ==0) {
$output .= "</div>";
}
$i++;
}
if($i != 1) {
$output .= "</div>";
}
echo $output;
?>
Ok, so what i want to do is check the radio button in the code that i posted, only when there is a match in the database, So to get the values that were checked by the user, i use the following.
Model
function get_roles_by_id($freelancerid)
{
$query = $this->db->query('SELECT * FROM '.$this->table_name.' WHERE user_id = "'.$freelancerid.'"');
return $query->result();
}
Then my controller looks like this
$data['positions'] = $this->freelancer_roles->get_roles_by_id($freelancer_id);
As that is bring back an array i cant use a foreach statement to check the radio button id's that are returned in the positions array.
Could someone help me to figure this out.
Cheers,
I think I understand your question and it seems a fairly simple thing you are trying to do. If
You should have your model only return an array of the names of the checkboxes saved by the user in the following format: array("checkbox1", "checkbox2", "checkbox3") then in your output
you can simply use the native php function in_array()
for example:
$output .= '<div class="row">';
$output .= ' <input name="_'.$row->key.'" type="radio" id="'.$row->key.'" class="radio"';
if(in_array($row->name, $data['positions']) { $output .= ' checked '; }
$output . = '/>';
$output .= ' <label for="'.$row->key.'" style="text-transform: lowercase;">'.$row->name.'</label>';
$output .= '</div>';
As a side note, you have the following code:
if($i > 0){
$i = 0;
}
if($i == 0) {
$output .= "<div class='box'>";
}
If you follow the logic in that code you will see that $i will always equal 0 for the second if statement, making both if statements redundant.

Resources