using jquery to loads result into pages - javascript

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"
)

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);
}
});
}
});

Send 2 variables through url

I send 2 variables by url:
var http = false;
http = new XMLHttpRequest();
function carrega(){
var nome = document.getElementById('CodigoUtente').value;
var nomes = document.getElementById('Nome').value;
var url_="conexao4?CodigoUtente="+nome+"&Nome="+nomes;
http.open("GET",url_,true);
http.onreadystatechange=function(){
if(http.readyState==4){
var retorno = JSON.parse(http.responseText);
document.getElementById('CodigoUtente').value = retorno.CodigoUtente;
document.getElementById('Nome').value = retorno.Nome;
document.getElementById('DataNasc').value = retorno.DataNasc;
document.getElementById('Sexo').value = retorno.Sexo;
document.getElementById('Estadocivil').value = retorno.Estadocivil;
document.getElementById('Nacionalidade').value = retorno.Nacionalidade;
document.getElementById('Responsavel').value = retorno.Responsavel;
document.getElementById('Parentesco').value = retorno.Parentesco;
document.getElementById('Contato').value = retorno.Contato;
}
}
http.send(null);
}
in the connection page4 I have the php that receives the variables:
$CodigoUtente = $_GET['CodigoUtente'];
$Nome = $_GET['Nome'];
if((isset($CodigoUtente)) && (isset($Nome))){
$query= "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes WHERE (CodigoUtente = '$CodigoUtente') OR (Nome LIKE '%$Nome%')";
$resultados = $conn->query($query);
$json = array();
while ($rowResultados = $resultados->fetch_assoc()) {
$dados = array(
'CodigoUtente' => $rowResultados['CodigoUtente'],
'Nome' => $rowResultados['Nome'],
'DataNasc' => $rowResultados['DataNasc'],
'Sexo' => $rowResultados['Sexo'],
'Estadocivil' => $rowResultados['Estadocivil'],
'Nacionalidade' => $rowResultados['Nacionalidade'],
'Responsavel' => $rowResultados['Responsavel'],
'Parentesco' => $rowResultados['Parentesco'],
'Contato' => $rowResultados['Contato']
);
$json = $dados;
}
echo json_encode($json);
}
The problem is that they only work if you fill in the two inputs and intended that they return the data from the database only when filling one of them.
Curious_Mind was saying this way?
$where_caluse = array();
if(isset($_GET['CodigoUtente'])){
$where_caluse[] = "CodigoUtente = '".$_GET['CodigoUtente']."'";
}
if(isset($_GET['Nome'])){
$where_caluse[] = "Nome = '".$_GET['Nome']."'";
}
$where = array_filter($where_caluse);
$query = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes";
$resultados = $conn->query($query);
if(!empty($where)){
$final_where = count($where) > 1 ? implode(' OR ', $where) : end($where);
$query = "$query WHERE ". $final_where;
$json = array();
while ($rowResultados = $resultados->fetch_assoc()) {
$dados = array(
'CodigoUtente' => $rowResultados['CodigoUtente'],
'Nome' => $rowResultados['Nome'],
'DataNasc' => $rowResultados['DataNasc'],
'Sexo' => $rowResultados['Sexo'],
'Estadocivil' => $rowResultados['Estadocivil'],
'Nacionalidade' => $rowResultados['Nacionalidade'],
'Responsavel' => $rowResultados['Responsavel'],
'Parentesco' => $rowResultados['Parentesco'],
'Contato' => $rowResultados['Contato']
);
$json = $dados;
}
echo json_encode($json);
}
I tried to apply the form it said, but it is not working, it gives 500 error when I send the values ​​of the variables.
Can you help fix the problem? I have a form to be populated with these values
$where = " where ";
$CodigoUtente = 'a';
$Nome = '';
if($CodigoUtente != '' && $Nome != '')
{
$where .= "CodigoUtente = '$CodigoUtente' OR Nome = '$Nome';";
}else if ($CodigoUtente != ''){
$where .= "CodigoUtente = '$CodigoUtente';";
}else{
$where .= " Nome = '$Nome';";
}
$query = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes".$where;
echo $query;
You can try like this way before making you sql query. This will help you to handle WHERE with OR condition, without OR condition and without any condition at all.
$where = array();
$_GET['CodigoUtente'] = 'Sany';
$_GET['Nome'] = 'Bruno';
if(isset($_GET['CodigoUtente'])){
$where[] = "CodigoUtente = '".$_GET['CodigoUtente']."'";
}
if(isset($_GET['Nome'])){
$where[] = "Nome = '".$_GET['Nome']."'";
}
$sql = "SELECT CodigoUtente, Nome, DataNasc, Sexo, Estadocivil, Nacionalidade, Responsavel, Parentesco, Contato FROM centrodb.PsicUtentes";
if(!empty($where)){
$final_where = count($where) > 1 ? implode(' OR ', $where) : end($where);
$sql = "$sql WHERE ". $final_where;
}
echo $sql;
DEMO: https://3v4l.org/phZGW

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);
}

Issue with downloadable CSV using AJAX with PHP

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

Ajax it does nothing when sending parameters to a php page

I am a beginner using ajax and am trying to change the status of reading a book by clicking an image.
I had the code working but without ajax. Now I have no php error but not a change in mysql.
The code:
<script type="text/javascript">
function sendState(state_id){
var hd_haveread = $("#hd_haveread").val();
var hd_toread = $("#hd_toread").val();
var hd_reading = $("#hd_reading").val();
var val = 0;
var baseurl = "img/";
switch(state_id){
case 1:
if (hd_haveread == "0"){
document.getElementById('hd_haveread').value = "1";
document.getElementById('hd_toread').value = "0";
document.getElementById('hd_reading').value = "0";
val = 1;
}
else{
document.getElementById('hd_haveread').value = "0";
val = 0;
}
break;
case 3:
if (hd_toread == "0"){
document.getElementById('hd_toread').value = "1";
document.getElementById('hd_haveread').value = "0";
document.getElementById('hd_reading').value = "0";
val = 1;
}
else{
document.getElementById('hd_toread').value = "0";
val = 0;
}
break;
case 2:
if (hd_reading == "0"){
document.getElementById('hd_reading').value = "1";
document.getElementById('hd_haveread').value = "0";
document.getElementById('hd_toread').value = "0";
val = 1;
}
else{
document.getElementById('hd_reading').value = "0";
val = 0;
}
break;
}
var parameters = {
"book" : <?php echo $id_book; ?>,
"state" : state_id,
"val" : val
};
$.ajax({
cache: false,
data: parameters,
url: 'change_state_ajax.php',
type: 'post',
dataType: "html",
beforeSend: function (){
},
success: function (response){
switch(state_id){
case 1:
if (hd_haveread == "0"){
$("#img_haveread1").css("display","none");
$("#img_haveread2").css("display","inline-block");
$("#img_toread1").css("display","inline-block");
$("#img_toread2").css("display","none");
$("#img_reading1").css("display","inline-block");
$("#img_reading2").css("display","none");
}
else{
$("#img_haveread1").css("display","inline-block");
$("#img_haveread2").css("display","none");
}
break;
case 3:
if (hd_toread == "0"){
$("#img_haveread1").css("display","inline-block");
$("#img_haveread2").css("display","none");
$("#img_toread1").css("display","none");
$("#img_toread2").css("display","inline-block");
$("#img_reading1").css("display","inline-block");
$("#img_reading2").css("display","none");
}
else{
$("#img_toread1").css("display","inline-block");
$("#img_toread2").css("display","none");
}
break;
case 2:
if (hd_reading == "0"){
$("#img_haveread1").css("display","inline-block");
$("#img_haveread2").css("display","none");
$("#img_toread1").css("display","inline-block");
$("#img_toread2").css("display","none");
$("#img_reading1").css("display","none");
$("#img_reading2").css("display","inline-block");
}
else{
$("#img_reading1").css("display","inline-block");
$("#img_reading2").css("display","none");
}
break;
}
}
});
}
</script>
And the change_state_ajax.php code:
<?php
if(isset($_POST['book']) && isset($_POST['state']) && isset($_POST['val'])){
include 'connection.php';
include('php_lib/config.ini.php');
include_once('php_lib/login.lib.php');
$lib_id = $_POST['book'];
$state = $_POST['state'];
$val = $_POST['val'];
$result=changeState($lib_id, $state, $val);
echo $result;
}
function changeState($lib_id, $state, $val){
session_start();
$usu_id = $_SESSION['USSER']['id'];
$mark = 0;
$pos = 0;
$query = $pdo->prepare('SELECT uliusu_id, ulilib_id, uliedl_id FROM '.TABLE_USSERS_BOOKS.' WHERE ulilib_id = :fil_lib_id AND uliusu_id = :fil_usu_id');
$query->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$query->execute();
while($row = $query->fetch(PDO::FETCH_OBJ)){
$mark = 1;
$state_actual = $row->uliedl_id;
}
if($mark == 0){
$query = $pdo->prepare('INSERT INTO '.TABLE_USSERS_BOOKS.' (uliusu_id, ulilib_id, uliedl_id, uli_posicion, uli_fecha) VALUES (:fil_usu_id, :fil_lib_id, :fil_edl_id, :fil_pos, NOW())');
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$query->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->bindParam(':fil_edl_id', $state, PDO::PARAM_INT);
$query->bindParam(':fil_pos', $pos, PDO::PARAM_INT);
$query->execute();
}else{
if($state == $state_actual){
$query = $pdo->prepare('DELETE FROM '.TABLE_USSERS_BOOKS.' WHERE ulilib_id = :fil_lib_id AND uliusu_id = :fil_usu_id');
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$queryquery->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->execute();
}else{
$query = $pdo->prepare('UPDATE '.TABLE_USSERS_BOOKS.' SET uliedl_id = :fil_edl_id WHERE ulilib_id = :fil_lib_id AND uliusu_id = :fil_usu_id');
$query->bindParam(':fil_edl_id', $state, PDO::PARAM_INT);
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$query->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->execute();
}
}
if($state == 1){
$result = 0;
}else{
$result = 1;
}
return $result;
}
?>
Can anyone help me solve this?
Thanks.
You are not checking for the proper variables. Your JavaScript passes a var called estado but you check in PHP for a var called state.
And because you require all three variables to be set your condition fails.
Also like Hank said in his comment your jQuery.Ajax call uses POST (type: 'post',) but then in your PHP script you check GET variables which of course are not set.
Either change you jQuery call type to GET or change the checking in your PHP script to POST
if(isset($_POST['book']) && isset($_POST['state']) && isset($_POST['val'])){
include 'connection.php';
include('php_lib/config.ini.php');
include_once('php_lib/login.lib.php');
$lib_id = $_POST['book'];
$state = $_POST['state'];
$val = $_POST['val'];
$result=changeState($lib_id, $state, $val);
echo $result;
}
Things I noticed:
1) First you are POSTing but in PHP, you are using $_GET.
2) you are passing "book", "estado", "val" but are trying to get "book", "state", "val", so it never enters into if condition

Categories

Resources