I am tryinh to get excel form php through ajax call when i load url of specific php gives me the output but when the same php is called via ajax with some ajax value nothing shows up.. am not sure what to do
ajax:
var fromdate= $("#fromdate").val();
var ToDate= $("#ToDate").val();
var Year= $('#Year').val();
var Category=$('#Category_1').val();
$.ajax({
url: "http://localhost/demo.php",
type: "post",
data: {
fromdate:fromdate,ToDate:ToDate,Year:Year,Category:Category
},
success: function(responsecon) {
window.open('http://YOUR_URL','_blank' );
}
});
PHP:
<?php
$conn=mysqli_connect('localhost','root','0000','xxxxx');
$filename = "users_export";
$fromdate = mysqli_real_escape_string($mysqli,trim($_POST["fromdate"]));
$ToDate = mysqli_real_escape_string($mysqli,trim($_POST["ToDate"]));
$Year = mysqli_real_escape_string($mysqli,trim($_POST["Year"]));
$Category = mysqli_real_escape_string($mysqli,trim($_POST["Category"]));
$sql = "Select * from xxxxxxxxxxx where category='$Category'";
$result = mysqli_query($conn,$sql) or die("Couldn't execute query:<br>" . mysqli_error(). "<br>" . mysqli_errno());
$file_ending = "xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
$sep = "\t";
$names = mysqli_fetch_fields($result) ;
foreach($names as $name){
}
print ("dasd" . $sep."dasd1" . $sep);
print("\n");
while($row = mysqli_fetch_row($result)) {
$schema_insert = "";
for($j=0; $j<mysqli_num_fields($result);$j++) {
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>
Basically there are two problems in your jQuery ajax request:
Sice you are specifying a content-type in your PHP script you have to tell jQuery what to expect from your ajax request using dataType: application/xls in your ajax object.
This is why you don't get any response, because it fails and you have not specified an error callback function to handle the error.
Moreover, in case of success you have to print somehow the content returned from the PHP script with something like $("#selector").html(responsecon);
Here is the updated ajax request:
$.ajax({
url: "http://localhost/demo.php",
type: "post",
dataType: "application/xls", // Tell what content-type to expect from server
data: {
fromdate:fromdate,
ToDate:ToDate,
Year:Year,
Category:Category
},
success: function(responsecon) {
window.open('http://YOUR_URL','_blank' );
$(#"some-container").html(responsecon); // Print the content
},
error: function() {
alert("error");
}
});
Related
I wrote the following code snippet for Ajax connections, but unfortunately the return value is not displayed in the output, but it does not give a special warning to understand the meaning. Please help.
js
$("#search").on('keyup', function(){var value = $(this).val();
$.ajax('feed.php',{
type: 'POST',
dataType: 'json',
data: {
keyword: value
},
success: function(data){
$("#pre").html(data);
}
});
});
feed.php
<?php
require_once('main.php');
$db = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $db->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$out['html']= '';
foreach($records as $record){
$out['html'] .= $record['word'] . '<br>';
}
echo json_encode($out);
?>
js:
jQuery('#search').on('keyup', () => {
jQuery.ajax({
url: 'feed.php',
type: 'POST',
data: { keyword: jQuery(this).val() },
success: response => {
jQuery('#pre').html(response);
}
});
});
feed.php
<?php
require_once('main.php');
$database = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $database->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$output = '';
foreach($records as $record){
$output .= $record['word'] . '<br />';
}
echo($output);
?>
PS: You don't need to use json output absolutly. But if there is coercion to using json output, the problem is 2 following items:
You don't set the output "Content-Type" to json: header('Content-Type: application/json');
You shouldn't pass the json object to html method in jQuery and should parsing it at first with JSON.parse(response) class, then with foreach, for or anything else process it
this simple ajax call works fine in Chrome, FF, Safari :
function downloadEntryReport() {
var data_range = document.getElementById("daterange").value;
var ajax_url = "ajaxcalls/download_entry_report/"+data_range;
$.ajax({
cache: false,
type: 'POST',
url: ajax_url,
dataType: 'text',
error: function(){
alert('Error loading document');
return false;
},
success: function(data) {
document.location.href = "ajaxcalls/download_entry_report/"+data_range;
}
});
}
except in IE (tested in 9.0.8). IE opens the URL (ajaxcalls/download_entry_report/given_date_range) which of course returns a 404 error. Is there a hack around this issue in IE or am I missing something?
Appreciate your help!
Here's the called PHP function :
function download_entry_report($data_range) {
$date_range_array = explode("%20::%20", $data_range);
$start_date = $date_range_array[0];
$end_date = $date_range_array[1];
$query = $this->db->query("SELECT * FROM tbl_name WHERE created_by = '".$this->session->userdata('email')."' AND DATE_FORMAT(created_date, '%Y-%m-%d') BETWEEN '".$start_date."' AND '".$end_date."' ");
$results = $query->result_array();
echo $this->download_csv_results($results, 'entry_report.csv');
exit();
}
and the other function to download the csv file :
function download_csv_results($results, $name = NULL)
{
if( ! $name)
{
$name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
}
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='. $name);
header('Pragma: no-cache');
header("Expires: 0");
$outstream = fopen("php://output", "w");
foreach($results as $result)
{
fputcsv($outstream, $result);
}
fclose($outstream);
}
In my project am using ajax for sending message the problem is i can't get the response in the ajax function the function works perfectly before,Can't find exact cause of the issue help me to solve it
ajax
var str = {
message:message, department_id:department, email:email, username:name
};
$.ajax( {
type: "POST",
url:'<?php echo base_url(); ?>home/savemessage',
dataType:"json",
data: str,
success: function(msg) {
$('#sentchat') . hide();
$('#chatmessage') . show();
$('#userchat') . html(msg . dataid);
$('.chat-box-content') . hide();
$('#adminname span').html('waiting for admins reply');
var elem = document . getElementById('userchat');
elem.scrollTop = elem . scrollHeight;
}
});
php controller
function savemessage() {
extract($this->input->post());
$data['message_id'] = $this->session->userdata('msgid');
$data['username'] = $username;
$data['email'] = $email;
$data['department_id'] = $department_id;
$data['message'] = $message;
$data['datetime'] = date('Y-m-d H:i:s');
$data['status'] = 'new';
$data['message_by'] = '1';
$this->db->insert('message', $data);
echo json_encode($username);
exit;
}
I cant get the response in it help me to solve it
You use ajax to communicate with a PHP script, inside the PHP script you could have the content of the function you want to execute. For example in your code:
$.ajax( {
type: "POST",
url:'<?php echo base_url(); ?>home/savemessage.php',
dataType:"json",
data: {myData:str},
success: function(msg) {
$('#sentchat') . hide();
$('#chatmessage') . show();
$('#userchat') . html(msg . dataid);
$('.chat-box-content') . hide();
$('#adminname span').html('waiting for admins reply');
var elem = document . getElementById('userchat');
elem.scrollTop = elem . scrollHeight;
}
});
Then, on the server side the php script "savemessage.php" would receive the POST action, so you could have:
if(isset($_POST['myData']) && !empty($_POST['myData'])) {
$obj = $_POST['myData'];
//rest of your code
echo json_encode($username);
exit;
}
However from your code I cannot see $username defined, so that probably would return an error.
I am searching this and other sites for hours now, so I'm getting pretty desperate. No code from many questions with the same topic here works.
I need to insert data into the database and display a message after it is done. Also, I am using AJAX with jQuery so it would be asynchronous. It works just fine, the data gets inserted, but no response message shows.
I am a beginner at PHP and can't understend why this won't work. Relevant code below.
PHP function call:
if(isset($_POST["function"]) && !empty($_POST["function"]) && $_POST["function"] == "cl-add") {
$dbb->addMember("MyUsername", $_POST["name"]);
//$dbb is a DataBaseBroker instance
}
PHP function from the Broker:
function addMember($username, $ime) {
$query = "INSERT INTO clan";
$query.=" (username, ime) ";
$query.="VALUES ('".$username."','".$ime."');";
$result = $this->mysqli->query($query);
if ($result) {
echo("You added a member: ".$ime);
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: ".mysqli_error($connection);
echo $response;
}
}
JQuery function declarations:
var addMember = function(name, responseFn) {
if (name === "") {
alert("Please enter a name");
return;
}
$.ajax({
type : 'POST',
url: '../includes/layout/cl.php',
dataType : 'json',
data : {
'name' : name,
'function' : 'cl-add'
},
success : function(data) {
responseFn(data); //not working, should alert
}
});
}
var responseCallback = function(data) {
alert(data);
}
And inside $(document).ready():
$(document).on('click', '#cl-add', function(evt) {
var name = $("#cl_frm input").val();
addMember(name, responseCallback);
});
On your code:
dataType : 'json',
The Ajax request is waiting for a JSON response but you are giving a text response.
You should change the dataType: to text or html depending on your needs.
dataType : 'html',
or
dataType : 'text',
PHP changes:
<?php
function addMember($username, $ime)
{
$query = "INSERT INTO clan";
$query .= " (username, ime) ";
$query .= "VALUES ('" . $username . "','" . $ime . "');";
$result = $this->mysqli->query($query);
$response = null;
if ($result) {
$response = "You added a member: " . $ime;
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: " . mysqli_error($connection);
}
echo $response;
exit;
}
Change dataType parameter to 'text'. Also you can alert an object in JavaScript, actually you are not trying to alert an object but i just wanted to mention it.
I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?
Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});
You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.