Internet Explorer 9 opens ajax URL instead of sending data - javascript

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

Related

How to use AJAX to call php file from javascript file

I want to call php file from javascript, and this php file will update id=1
like this way:
javascript:
if(lastTemp >= document.getElementById("TempSet").value){
var jsonData2 =$.ajax({
url: "setpp.php",
dataType: "json",
async: false
}).responseText;
var obj2 = JSON.parse(jsonData2);
console.log(obj2);
}
else {
}
php file:
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'use';
$DATABASE_PASS = 'pass';
$DATABASE_NAME = 'database';
// Try and connect using the info above.
$db = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (!$db){
die("Connection Failed: ". mysqli_connect_error());
}
$db_update = "UPDATE setpoint_control SET status='ON' WHERE id=1";
$result = mysqli_query($db, $db_update);
?>
<?php
$data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
array_push($data, $row['status']);
}
}
echo json_encode($data);
?>
the code is executed and the status in database table is changed but I got error in console : SyntaxError: JSON.parse: unexpected character at line 4 column 2 of the JSON data
How can I solve this issue which I think I need to rewrite json_encode but I don't know how?
$.ajax({
type: 'post',
dataType: 'json',
cache: false,
url: 'setpp.php',
success: function (response) {
$.each(response, function(i, item) {
alert(item);
});
},
error: function () {
alert("error");
},
});
example php answer setpp.php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row['status']);
}
die(json_encode($data));
} else {
$answer = array(
'No Records'
);
die(json_encode($answer));
}
I think the problem is the value returned by setpp.php.
remember to die(), otherwise the php answer will not be correct

Send an ajax call to a function in YII

I am in need to send an ajax call to a function in following directory structure
Yii::$app->request->absoluteUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile";
my view function
function uploadImage(){
var url = '<?php echo Yii::app()->request->baseUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile"; ?>';
console.log(url);
return false;
$.ajax({
url:'<?php echo Yii::$app->createUrl("Post/UploadMusicFile"); ?>',
method:'post',
data:{file:$('input[type="file"]')},
dataType:'',
contentType:false,
processData:false,
success:function(data){
var parsed_data = $.parseJSON(data);
},
error:function(data){
console.log("Error "+data);
}
});
}
function which i am posting to
public function UploadMusicFile(){
$file = Yii::$app->request->post('file');
echo "<pre>";
print_r($file);
echo "</pre>";
exit();
$target_dir = "/home/jmwglobaladmin/public_html/melmory/uploads/music_memory/";
$target_file = $target_dir . basename($_FILES["files"]["name"][0]);
foreach ($_FILES["files"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["files"]["tmp_name"][$key];
move_uploaded_file($tmp_name, $target_file);
$connection = Yii::$app->getDb();
$command = $connection->createCommand('select id from post order by id desc limit 1');
$result = $command->queryAll();
$new_id = $result[0]['id']+1;
$file_name = "abc.mp3";
$connection = Yii::$app->getDb();
$command_insert = $connection->createCommand('insert into memory_music (post_id,memory_music) values ("'.$new_id.'","'.$file_name.'")');
$result = $command_insert->execute();
}
}
}
I get the error of 404. How to pass proper url in yii to a function which is present in directory structure like mentioned above?
Basics. Your function is not an action.
Change this:
public function UploadMusicFile()
To this:
public function actionUploadMusicFile()

File upload by ajax $.post not working

I am really new to ajax do forgive me if the question is stupid. I have a multi step form and it has the 4 parts , and I am using $.post() ajax request to send this. while all my other details are going fine I am not able to upload my file. this is what I am trying to do
Here I am trying to catch the form values.
var data_img = new FormData();
var hello = $.each(jQuery('#pan_file')[0].files, function (i, file) {
data_img.append('file-' + i, file);
});
Then I am passing these values to the object variable.
obj_params.pan_file = hello;
And then sending it to store with ajax.post()
$.post('<?php echo base_url(); ?>get-ekyc-form', obj_params, function (msg) {
if (msg == "1") {
swal("Success!", "EKYC Form has been Submitted Successfully", "success");
window.location = '<?php echo base_url(); ?>list-active-requirement';
}
}, "json", "processData:false", "contentType:false");
return true;
And this is where I do file transfer.
if ($_FILES['file-0']['name'] != "") {
$image_data = array();
//config initialise for uploading image
$config['upload_path'] = './media/front/img/quote-docs/';
$config['allowed_types'] = 'xlsx|pdf|doc|docx';
$config['max_size'] = '5000';
$config['max_width'] = '12024';
$config['max_height'] = '7268';
$config['file_name'] = time();
//loading upload library
$this->upload->initialize($config);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file-0')) {
$error = array('error' => $this->upload->display_errors());
} else {
$data = array('upload_data' => $this->upload->data());
$image_data = $this->upload->data();
$file_name = $image_data['file-0'];
}
$file_name = $image_data['file_name'];
} else {
$file_name = '';
}
Also I am working on someone elses code so I do understand I must have made loads of mistakes. I'll be grateful if someone could help me around this.
HTML code
<input id="picture" type="file" name="pic" />
<button id="upload">Upload</button>
$('#upload').on('click', function() {
var file_data = $('#picture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
in upload.php
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>

error in getting ajax response in java script

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.

ajax get Excel form php

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

Categories