Issue with downloadable CSV using AJAX with PHP - javascript

I am trying to create a panel, where I can select input from 5 dropdowns (4 are multiselect dropdowns) and send them through an ajax call.
In the ajax function I am trying to create a csv downloadable file.
But the issue is, I can get the alert to display the content that should be in the file, but the file isn't downloading neither its getting saved in some folder.
Here's my JavaScript function triggering the ajax call:
function create_csv()
{
var v = $('#drp_v').val();
var cnt = $('#drp_cnt').val();
var ctg = $('#drp_ctg').val();
var api = $('#drp_api').val();
var nt = $('#drp_nt').val();
alert("version :"+v+" category :"+ctg+" country :"+cnt);
$.post("ajax.php",
{
'version':v,'category':ctg,
'country':cnt,'network_id':nt,
'api':api,'func':'create_csv'
},
function(data)
{
alert(data);
});
}
And here's my PHP function
function create_csv($version,$ctg,$cnt,$nt,$api)
{
$cnt_table = "aw_countries_".$version;
$ctg_table = "aw_categories_".$version;
$off_table = "aw_offers_".$version;
$sizeof_ctg = count($ctg);
$cond_ctg = " ( ";
for($c = 0; $c < $sizeof_ctg ; $c++)
{
$cond_ctg = $cond_ctg." $ctg_table.category = '".$ctg[$c]."' ";
if($c < intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." OR ";
else if($c == intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." ) ";
}
$sizeof_cnt = count($cnt);
$cond_cnt = " ( ";
for($cn = 0; $cn < $sizeof_cnt ; $cn++)
{
$cond_cnt = $cond_cnt." $cnt_table.country = '".$cnt[$cn]."' ";
if($cn < intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." OR ";
else if($cn == intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." ) ";
}
$sizeof_nt = count($nt);
$cond_nt = " ( ";
for($n = 0; $n < $sizeof_nt ; $n++)
{
$cond_nt = $cond_nt." $off_table.network_id = '".$nt[$n]."' ";
if($n < intval($sizeof_nt-1))
$cond_nt = $cond_nt." OR ";
else if($n == intval($sizeof_nt-1))
$cond_nt = $cond_nt." ) ";
}
$sizeof_api = count($api);
$cond_api = " ( ";
for($a = 0; $a < $sizeof_api ; $a++)
{
$cond_api = $cond_api." $off_table.api_key = '".$api[$a]."' ";
if($a < intval($sizeof_api-1))
$cond_api = $cond_api." OR ";
else if($a == intval($sizeof_api-1))
$cond_api = $cond_api." ) ";
}
$output = "";
$sql = "SELECT $off_table.id,$off_table.name
FROM $off_table,$cnt_table,$ctg_table
WHERE $off_table.id = $cnt_table.id
AND $off_table.id = $ctg_table.id
AND ".$cond_api."
AND ".$cond_nt."
AND ".$cond_cnt."
AND ".$cond_ctg;
$result = mysql_query($sql);
$columns_total = mysql_num_fields($result);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++)
{
$heading = mysql_field_name($result, $i);
$output .= '"'.$heading.'",';
}
$output = trim($output,",");
$output .="\n";
while ($row = mysql_fetch_array($result))
{
for ($i = 0; $i < $columns_total; $i++)
{
$output .='"'.$row["$i"].'",';
}
$output = trim($output,",");
$output .="\n";
}
// Download the file
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
}
What modifications do I need so that I can download the CSV file?

maybe it will be a little complicated :)
You can not download CSV directly with ajax.
But there are some trick.
Make sure your mysql connection is ready in your ajax.php.
When you get the resource, dinamicly create a hidden form with all data what you need
$( "body" ).append('
<form name="form" target="my_iframe">
<input name ="version" value="'+v+'">
<input name="country" value="'+cnt'+">
<input name="api" value="'+api+'">');
etc..
something like this,
and after just submit this form to a hidden iframe
$('[name="form"]').submit();
and that's it
in the end destroy your hidden form

Related

How do I submit form without page reload taking into consideration the php script?

So basically I have to work on this loan calculator loancalc.000webhostapp.com
I have looked at other pages on this site "how to submit form without page reload?" but this isn't completely relevant to what i'm working on. So far i've added this into the jquery part of the page...
jQuery('qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else{
}
if (email == ""){
$("input#youremail").focus;
return false;
}
});
But i'm told there is also two other scripts that I need to work with, I'm not really too experienced with php so not sure what's going on, the two php scripts I have to work with are called quick-interest-slider.php and register.php,
//qis_verify_application in register.php
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
//qis_process_application in register.php
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
function qis_loop in quick-interest-slider.php
function qis_loop($atts) {
$qppkey = get_option('qpp_key');
if (!$qppkey['authorised']) {
$atts['formheader'] = $atts['loanlabel'] = $atts['termlabel'] = $atts['application'] = $atts['applynow'] = $atts['interestslider'] = $atts['intereselector']= $atts['usecurrencies'] = $atts['usefx'] = $atts['usedownpayment'] = false;
if ($atts['interesttype'] == 'amortization' || $atts['interesttype'] == 'amortisation') $atts['interesttype'] = 'compound';
}
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
Do I have to edit any of the php and I also don't know what I have to write considering the php.
You can use what is called Ajax to submit the data to the server via POST.
Create a button and give it a class of qis-register, then give each of your input fields a class that matches it's name. Then just add that field to the data object that I have following the format within it.
jQuery(document).on('click', '.qis-register', function(){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "your_php_here.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});

passing multiple values using xmlhttp.send

I am trying to pass two different values into an XMLHttpRequestObject.send but cannot seem to get the php script to read them both, it will only read the first value passed. How can I get the PHP to read both the values, here is the sample code:
HTML
<select id="mes" onchange="callCourseYards(this);">
<option>-</option>
</select>
Javascript
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function callCourseYards(selectObject){
if(XMLHttpRequestObject){
XMLHttpRequestObject.open("POST", "php/CourseChoiceTeeOff.php");
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function(){
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
var returnData = XMLHttpRequestObject.responseText;
var messageDiv = document.getElementById('tee');
messageDiv.innerHTML = returnData;
}
}
var data = selectObject.value;
var course = selectObject.value;
XMLHttpRequestObject.send("data=" + data + "course=" + course);
}
return false;
}
PHP
<?php
$pdo_dsn='localhost';
$dbname ='XXX';
$mysql_user='XXX';
$mysql_pass='XXX';
$db = mysqli_connect($pdo_dsn, $mysql_user, $mysql_pass, $dbname);
if(!$db){
print "Unable to connect to MySQL";
}
$myData = $_POST['data'];
$myData1 = $_POST['course'];
$sql_state = "SELECT * FROM ".$myData1." WHERE CourseCode = '".$myData."' ORDER BY CourseCode";
$result = mysqli_query($db, $sql_state);
$out = "";
$myrowcount = 0;
if(!$result){
$out = "Error";
}else{
$out = "<option>Selecciona un campo</option><br/ >";
$numresults = mysqli_num_rows($result);
for ($i = 0; $i < $numresults; $i++){
$row = mysqli_fetch_array($result);
$teeOff = $row['TeeOff'];
$out .= "<option id='".$myData."' value='".$teeOff."'> ".$teeOff."</option>";
}
$out .= "<br/ >";
}
print $out;
?>
I cannot seem to get the values through the XMLHttpRequestObject to go through into the PHP. I am not sure if its the syntax or how they should get past into the PHP.
I have tried using the & and the + symbols to concatenate both values, but I am not sure if this is possible. Does anyone know how I can fix this problem? I need both values to be able to do the mySQL search in the database.
Any help would be greatly appreciated. Thanks

loop executes only last array element using php, ajax and javascript

Hi friends am trying to save the data from the loop here is my code.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body onload="searchVideo();">
<?php
ini_set('max_execution_time', 300);
$query = "SELECT * FROM `playlists`";
$result = mysqli_query($mysql,$query);
while($row=mysqli_fetch_assoc($result)){
$id=$row['id'];
$playlists=$row['playlists'];
$myArray = explode(',', $playlists);
$length = sizeof( $myArray);
$myArray[0]=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-
$myArray[1]=PLFgquLnL59ak1QNHmrUSjNM6WTegpgX__
for ($i=0; $i<$length; $i++){
echo "
<script>
var pageToken = '';
var numOfResult = 0;
var maxResults = 200;
function searchVideo(){
var separator = ',';
$.getJSON('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&pageToken=' + pageToken + '&playlistId=$myArray[$i]&key=APIKEY&callback=?',function(data){
var l = data.items.length;
pageToken = data.nextPageToken;
numOfResult += l;
var itemUrl = '';
var videoids = [];
for(var i = 0; i < l; i++) {
if( i == 0) {
separator = ',';
}
else {
separator = ',';
}
var videoid = data.items[i].snippet.resourceId.videoId;
var title = data.items[i].snippet.title;
$.ajax({
method: 'POST',
url: 'add.php',
data: { title: title, videoid: videoid }
})
.done(function(data) {
});
}
if( numOfResult <= maxResults) {
searchVideo();
}
});
}
</script>
";
}
}
?>
add.php
<?php
$title = mysqli_real_escape_string($mysql,$_POST['title']);
$videoid = mysqli_real_escape_string($mysql,$_POST['videoid']);
$thumbnail_url = 'http://img.youtube.com/vi/'.$videoid.'/hqdefault.jpg';
$sql = "INSERT INTO ytfb(name,video_name,thumbnail_url) VALUES('$title','$videoid','$thumbnail_url')";
$create_post_query=mysqli_query($mysql,$sql);
if(!$create_post_query)
{
die("Connection failed".mysqli_error($mysql));
}
?>
When am trying to save the data using ajax in add.php the elements from the last array element are only saved the elements from the first array element is not saved how can I be able to save the data from all the array elements. Can anyone please help me out with this
Define the function searchVideo outside the cycle and organize to call it with different parameters. In cycle change global vars or input parameters of searchVideo.
Now you get this result because finaly executes the last istance of this function.
for(var i = 0; i < l; i++) {
if( i == 0) {
separator = ',';
}
else {
separator = ',';
}
var videoid = data.items[i].snippet.resourceId.videoId;
var title = data.items[i].snippet.title;
Here i will be the index of last element so only last item is getting stored.
You have to loop the ajax call through the loop to get all elements to be saved.

Creating export and import in codeigniter i need an assistant

I need an assistant with creating export and import file in codeigniter, I am not advanced in coding, I am still learning. I didn't add export button as I also need an assistant on how to add it
Here is my view
<form method="post" action="<?php echo base_url() ?>csv/importcsv" enctype="multipart/form-data">
<input type="file" name="userfile" size="10" style="width:20px;">
<input type="submit" name="submit" value="IMPORT" class="btn btn-primary">
</form>
Here is my controller
/****MANAGE MEMBERS*****/
function member($param1 = '', $param2 = '', $param3 = '') {
if ($this->session->userdata('admin_login') != 1)
redirect(base_url(), 'refresh');
if ($param1 == 'create') {
$data['names'] = $this->input->post('names');
$data['surname'] = $this->input->post('surname');
$data['title'] = $this->input->post('title');
$data['initials'] = $this->input->post('initials');
$data['id_number'] = $this->input->post('id_number');
$data['passport'] = $this->input->post('passport');
$data['birthdate'] = $this->input->post('birthdate');
$data['gender'] = $this->input->post('gender');
$data['email'] = $this->input->post('email');
$data['address_1'] = $this->input->post('address_1');
$data['address_2'] = $this->input->post('address_2');
$data['address_3'] = $this->input->post('address_3');
$data['province'] = $this->input->post('province');
$data['country'] = $this->input->post('country');
$data['postal_code'] = $this->input->post('postal_code');
$data['phone'] = $this->input->post('phone');
$data['tel'] = $this->input->post('tel');
$data['country'] = $this->input->post('country');
$data['region'] = $this->input->post('region');
$data['branch'] = $this->input->post('branch');
$data['creation_timestamp'] = $this->input->post('creation_timestamp');
$data['expiry_timestamp'] = $this->input->post('expiry_timestamp');
$data['beneficiary_name'] = $this->input->post('beneficiary_name');
$data['beneficiary_surname'] = $this->input->post('beneficiary_surname');
$data['beneficiary_id_number'] = $this->input->post('beneficiary_id_number');
$data['beneficiary_phone'] = $this->input->post('beneficiary_phone');
$data['message'] = $this->input->post('message');
$data['chat_status'] = $this->input->post('chat_status');
$this->db->insert('member', $data);
$member_id = mysql_insert_id();
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/member_image/' . $member_id . '.jpg');
$this->email_model->account_opening_email('member', $data['email']); //SEND EMAIL ACCOUNT OPENING EMAIL
redirect(base_url() . 'index.php?admin/member/', 'refresh');
}
if ($param1 == 'do_update') {
$data['names'] = $this->input->post('names');
$data['surname'] = $this->input->post('surname');
$data['title'] = $this->input->post('title');
$data['initials'] = $this->input->post('initials');
$data['id_number'] = $this->input->post('id_number');
$data['passport'] = $this->input->post('passport');
$data['birthdate'] = $this->input->post('birthdate');
$data['gender'] = $this->input->post('gender');
$data['email'] = $this->input->post('email');
$data['address_1'] = $this->input->post('address_1');
$data['address_2'] = $this->input->post('address_2');
$data['address_3'] = $this->input->post('address_3');
$data['province'] = $this->input->post('province');
$data['country'] = $this->input->post('country');
$data['postal_code'] = $this->input->post('postal_code');
$data['phone'] = $this->input->post('phone');
$data['tel'] = $this->input->post('tel');
$data['country'] = $this->input->post('country');
$data['region'] = $this->input->post('region');
$data['branch'] = $this->input->post('branch');
$data['creation_timestamp'] = $this->input->post('creation_timestamp');
$data['expiry_timestamp'] = $this->input->post('expiry_timestamp');
$data['beneficiary_name'] = $this->input->post('beneficiary_name');
$data['beneficiary_surname'] = $this->input->post('beneficiary_surname');
$data['beneficiary_id_number'] = $this->input->post('beneficiary_id_number');
$data['beneficiary_phone'] = $this->input->post('beneficiary_phone');
$data['message'] = $this->input->post('message');
$data['chat_status'] = $this->input->post('chat_status');
$this->db->where('member_id', $param2);
$this->db->update('member', $data);
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/member_image/' . $param2 . '.jpg');
redirect(base_url() . 'index.php?admin/member/', 'refresh');
} else if ($param1 == 'personal_profile') {
$page_data['personal_profile'] = true;
$page_data['current_member_id'] = $param2;
} else if ($param1 == 'edit') {
$page_data['edit_data'] = $this->db->get_where('member', array(
'member_id' => $param2
))->result_array();
}
if ($param1 == 'delete') {
$this->db->where('member_id', $param2);
$this->db->delete('member');
redirect(base_url() . 'index.php?admin/member/', 'refresh');
}
$page_data['teachers'] = $this->db->get('member')->result_array();
$page_data['page_name'] = 'member';
$page_data['page_title'] = get_phrase('manage_member');
$this->load->view('index', $page_data);
if (!this->load->importcsv()); {
$data['memberbook'] = $this->csv_model->get_memberbook();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$this->load->view('index', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'names'=>$row['names'],
'surname'=>$row['surname'],
'initials'=>$row['initials'],
'id_number'=>$row['id_number'],
'passport'=>$row['passport'],
'birthdate'=>$row['birthdate'],
'gender'=>$row['gender'],
'phone'=>$row['phone'],
'email'=>$row['email'],
'address_1'=>$row['address_2'],
'address_2'=>$row['address_2'],
'address_3'=>$row['address_3'],
'province'=>$row['province'],
'country'=>$row['country'],
'postal_code'=>$row['postal_code'],
'tel'=>$row['tel'],
'region'=>$row['region'],
'branch'=>$row['branch'],
'creation_timestamp'=>$row['creation_timestamp'],
'expiry_timestamp'=>$row['expiry_timestamp'],
'beneficiary_name'=>$row['beneficiary_name'],
'beneficiary_surname'=>$row['beneficiary_surname'],
'beneficiary_id_number'=>$row['beneficiary_id_number'],
'beneficiary_phone'=>$row['beneficiary_phone'],
'message'=>$row['message'],
);
$this->csv_model->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'csv');
//echo "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
}
After months with this problem i came up a solution so i thought i should share it for some peeps who are having same difficulties
CONTROLLER
function member_bulk_add($param1 = '')
{
if ($this->session->userdata('admin_login') != 1)
redirect(base_url(), 'refresh');
if ($param1 == 'import_excel')
{
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/import.xlsx');
// Importing excel sheet for bulk student uploads
include 'simplexlsx.php';
$xlsx = new SimpleXLSX('assets/import.xlsx');
list($num_cols, $num_rows) = $xlsx->dimension();
$f = 0;
foreach( $xlsx->rows() as $r )
{
// Ignore the inital name row of excel file
if ($f == 0)
{
$f++;
continue;
}
for( $i=0; $i < $num_cols; $i++ )
{
if ($i == 0) $data['name'] = $r[$i];
else if ($i == 1) $data['birthday'] = $r[$i];
else if ($i == 2) $data['sex'] = $r[$i];
else if ($i == 3) $data['address'] = $r[$i];
else if ($i == 4) $data['phone'] = $r[$i];
else if ($i == 5) $data['email'] = $r[$i];
}
$data['member_id'] = $this->input->post('member_id');
$this->db->insert('member' , $data);
//print_r($data);
}
redirect(base_url() . 'index.php?admin/member/' . $this->input->post('member_id'), 'refresh');
$this->load->view('backend/index', $page_data);
}

using jquery to loads result into pages

I have got a php databse query which I am trying to process with jquery to loads pages, at the moment when i try and test nothing happens so I feel that the problem lies within my HTMLoutput within the jquery script where I am trying to carry out a php explode function could anyone shed some light on this?
here is the php code to parse the data:
if (!$db_server){
die("unable to Connect to MYSQL: " . mysqli_connect_error($db_server));
$db_status = "not connected";
}else{
if(trim($_POST['submit']) =="submit"){
}else{
if (isset($_POST['dropoption']) && ($_POST['dropoption'] != '')){
if (isset($_POST['meal']) && ($_POST['meal'] != '')) {
if(isset($_POST['pn'])){
$rpp = preg_replace('#[^0-9#', '', $_POST['rpp']);
$last = preg_replace('#[^0-9#', '', $_POST['last']);
$pn = preg_replace('#[^0-9#', '', $_POST['pn']);
if ($pn < 1) {
$pn = 1;
} else if ($pn > $last){
$pn = $last;
}
include_once("db_connect.php");
$limit = 'LIMIT ' .($pn - 1) * $rpp .',' .$rpp;
$sql = "SELECT * FROM `recipename` WHERE `cuisine_type` ='$dropoption' AND `b_l_d` ='$meal' $limit";
$query = mysqli_query($db_server, $sql);
$datastring = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$mealname = $row["mealname"];
$mealpic = $row["imagepath"];
$cookingtime = $row["minutes"]."minutes".$row["hours"]."hours";
$ingredients = $row["ingredients"];
$recipe = $row["recipe"];
$datastring .= $mealname.'|'.$mealpic.'|'.$cookingtime.'|'.$ingredients.'|'.$recipe.'||';
}
echo $datastring;
exit();
}
$dropoption = clean_string($db_server, $_POST['dropoption']);
$meal = clean_string($db_server, $_POST['meal']);
$quer = "SELECT COUNT(recipeid) FROM `recipename` WHERE `cuisine_type` ='$dropoption' AND `b_l_d` ='$meal'";
mysqli_select_db($db_server, $db_database);
$querya= mysqli_query($db_server, $quer);
if (!$querya) die("database access failed: " . mysqli_error($db_server));
$row = mysqli_fetch_row($querya);
$total_rows = $row[0];
$rpp = 1;
$last = ceil($total_rows/$rpp);
if(last < 1){
$last = 1;
}
}//if(meal)//
}//if(cuisine)//
} //if(trim)//
}
?>
And here is the jquery script:
<script type="text/javascript">
var rpp=<?php echo $rpp; ?>;
var last=<?php echo $last; ?>;
function request_page(pn) {
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results";
var hr = new XMLHttpRequest();
hr.open("POST", "results.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urleconded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var dataArray = hr.responseText split("||");
var html_output = "";
for(i= 0; i< dataArray.length - 1; i++) {
var itemArray = dataArray[i].split("|");
html_output += "Recipe: "+itemArray[0]+"<img src='http://ml11maj.icsnewmedia.net/Workshops/Week%207/"+itemArray[1]+"'/><h2>Ingredients</h2><?php $ingredientchunks = (explode(",","+itemArray[2]+"));
for($i = 1; $i < count($ingredientchunks); $i++){
echo "$i.$ingredientchunks[$i] <br/>";}?>"+itemArray[3]+"<h2>Recipe</h2>
<?php $recipechunks = (explode(",","+itemArray[4]+"));
for($i = 1; $i < count($recipechunks); $i++){
echo "$i.$recipechunks[$i] </br>";}
?>";
}
results_box.innerHTML = html_output;
}
}
hr.send("rpp="+rpp+"&last="+last+"&pn="+pn);
//change pagination controls//
var paginationCtrls = "";
if(last !=1) {
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn !=last) {
paginationCtrls += '< <button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
Yep, I suspect it's your explode(",","+itemArray[2]+") that's causing the problem.
Explode is used to split strings into arrays, like so:
$string = "Apples,Oranges,Pears";
$array = explode(",",$string);
var_dump($array);
Example Output
array(2)
(
[0] => string(5) "Apples"
[1] => string(6) "Oranges"
[2] => string(4) "Pears"
)

Categories

Resources