Ajax send data to php to download file? - javascript

First thing:
User submits "Run system", i send to php function systemid what user run using ajax, that function collecting data to an array and than return array with json to jquery. - this works great
Second thing
Returned data i need to send to function what convert an array to xls/csv, also that function returns me System name. - also works
Finnally
I start download using window.location.href = '/index.php?/system/download/'+url; but in downloaded file there is no data.
This is client side code:
$(".systemform").submit(function(e) {
var sysid = $(".sysid:checked").val();
$.ajax({
type: "POST",
url: '/index.php?/system/system_options/export',
data: { system : sysid },
dataType:"json",
success: function(data)
{
$(".exportsys").removeAttr("disabled");
$(".exportsys").removeAttr("title");
//now user can export data
$(".exportsys").click(function(e){
//alert(JSON.stringify(data)); works
$.ajax({
type:"POST",
url: '/index.php?/system/downloadcsv',
data: { exportarr : data }, //send array
dataType:"json",
success: function(response){
var url = response.url; //i get system name
window.location.href = '/index.php?/system/download/'+url; //now download start, but file is empty because data is not sended
},
error: function(xhr, textStatus, error){
alert(error);
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
})
})
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
and server side (NOTICE: i am using codeignitier), this are in same controller:
public function downloadcsv(){
//var_dump($this->export_arr);
if(isset($_POST['exportarr'])){
$exportarr = $_POST['exportarr'];
$filename = $exportarr[0]['System'] . date('Ymd') . ".xls";
//echo $filename;
echo json_encode(array('url'=>$filename));
$data = $exportarr;
$flag = false;
foreach($data as $row) {
if(!$flag) {
// display field/column names as first row
implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
implode("\t", array_values($row)) . "\r\n";
//print_r($data);
}
}
exit;
}
public function download($filename){
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
header("Content-Type: text/plain");
}

Related

PHP not receiving AJAX POST from js File

I have been trying to work this out for hours now and cannot find any answer that helps me.
This is the code in my javascript file
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
url: '../game.php',
data: { 'Name': name },
success: function(response) {
console.log("sent");
}
});
}
This is the code from my PHP file (it is outside the js file)
if($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['Name'];
console_log($data);
}
When debugging I can see that AJAX is sending a POST and it does print in the console "SENT" but it does not print $data
update: the function console_log() exists in my PHP file and it works
Try getting response in JSON format, for that your js should have dataType:'JSON' as shown below
JS Code:-
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
dataType:'JSON', //added this it to expect data response in JSON format
url: '../game.php',
data: { 'Name': name },
success: function(response) {
//logging the name from response
console.log(response.Name);
}
});
}
and in the current server side code you are not echoing or returning anything, so nothing would display in ajax response anyways.
changes in php server code:-
if($_SERVER["REQUEST_METHOD"] == "POST") {
$response = array();
$response['Name'] = $_POST['Name'];
//sending the response in JSON format
echo json_encode($response);
}
I fixed it by doing the following:
To my game.php I added the following HTML code (for debugging purposes)
<p style = "color: white;" id="response"></p>
Also added in my game.php the following
if($_SERVER["REQUEST_METHOD"] == "POST") {
$gameID = $_POST['gameID'];
$coord = $_POST['coord'];
$player = $_POST['player'];
echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;
}
AND in my custom.js I updated
function sendMovement(cel) {
var handle = document.getElementById('response');
var info = [gameID, cel.id, current_player];
$.ajax({
type: 'POST',
url: '../game.php',
data: {
gameID: info[0],
coord: info[1],
player: info[2]
},
success: function(data) {
handle.innerHTML = data;
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}

Ajax post request is appending sent data to the returned JSON

I have an ajax call like so:
$.ajax({
url: '/assets/functions.php',
type: 'POST',
data: {
"functionCall": "get-uploads",
"type": type
},
dataType: 'json',
success: function (data, textStatus) {
console.log("done");
console.log(data);
console.log(textStatus);
},
error: function(textStatus, errorThrown) {
console.log("uh oh");
console.log(textStatus);
console.log(errorThrown);
}
});
Which gets sent to and handled with this:
switch($_POST['functionCall']) {
.
.
.
case "get-uploads":
$type = $_POST['type'];
$getUploads = "SELECT * FROM pp_uploads WHERE type = '$type';";
$docArray = array();
while($row = mysql_fetch_assoc($documents)) {
$docArray[] = $row;
}
echo json_encode($docsArray);
}
When I run this I get a parsing error, which from what I understand means that the returned data isn't being returned as JSON. So I changed the dataType to html, and I see that the returned data in the console is:
[{"id":"35","filename":"fdgsdf","path":"ConfiguratorTreeDiagram.pdf","type":"resources"},{"id":"36","filename":"gsrewg","path":"dhx_advertising.pdf","type":"resources"}]Array
(
[functionCall] => get-uploads
[type] => resources
)
So it looks like the data I passed into the call is being appended to the end of my data. How do I prevent that from happening?
It looks like you might be doing a print_r somewhere on an Array variable?

AJAX call sending JSON data

I am working on a chat system which refreshes automatically using AJAX. First I was using the jQuery $.post function, but since i wanted to return JSON data from my PHP script, i want to use the $.ajax function. My script worked well using the $.post function, but i can not return JSON. This is the relevant code:
Javascript:
$.ajax({
url: "pages/loadmessage.php",
type: "POST",
data: {"c": getUrlParameter("c"), "t": messagetime},
dataType: "json",
success: function(pData){
console.log(pData);
},
error: function(xhr, status, error) {
alert(error + status);
}
});
PHP Code:
<?php
require_once("../init.php");
header('Content-Type: application/json');
if (Input::exists() && Input::get("c") && Input::get("t")) {
$chat = new Chat($user->data()->ID, Input::get("c"));
$messages = $chat->getNewMessages(Input::get("t"), $user->data()->ID);
if ($messages) {
$result = array(
'topic' => $chat->getTopic(),
'messages' => array()
);
foreach($messages as $m) {
array_push($result['messages'], array('source' => 'mine', 'Text' => $m->Text));
}
echo json_encode("string!!!");
}
} else {
echo json_encode("string" . Input::get("c") . Input::get("t") . Input::exists());
}
?>
I already tried to set the contentType of the AJAX call to "application/json" and convert the data to JSON using JSON.stringify, but then no input data gets to the PHP script. The code works if just one parameter (data: {"c": getUrlParameter("c")}) is sent to the PHP script...
I already searched StackOverflow, but i could not find a solution...
Thanks
JSON example:
Index.html
<script type="text/javascript">
$.ajax({
url: "out.php",
type: "POST",
data: {"param1": "test 1", "param2": "test2"},
dataType: "json",
success: function(data){
alert("param1:"+data.param1+" | param2:"+data.param2);
},
error: function(xhr, status, error) {
alert(error + status);
}
});
</script>
out.php
<?php
if(isset($_POST["param1"])){ $param1 = $_POST["param1"];}
if(isset($_POST["param2"])){ $param2 = $_POST["param2"];}
$out = array("param1"=>$param1,"param2"=>$param2);
echo(json_encode($out));
?>

JavaScript ajax post command error for localhost

I am new to Ajax & JavaScript. But i am stuck with this error. I am making post request using Ajax.
var sentdata = {"name":"gourav", "email":"email"};
var sentd = JSON.stringify(sentdata);
this.url = "http://localhost/Working/board.php";
$.ajax({
type: "POST",
url: $(this).url,
data: sentd,
contentType: "application/json",
//dataType : "json",
success: function (response) {
alert(response.message);
console.log( "Done with success: ");
},
error: function (xhr, thrownError) {
alert(thrownError);
}
});
I am calling this request to simple code where i am not even checking the $_POST variable and just trying to write some data in mysql table.
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, true);
// selecting database
mysql_select_db(DB_DATABASE, $con);
if(1)
{
$tb_name = "tb_appuser";
$name = "name1";
$email="email1";
$deviceId="0";
$platform="1";
$query = sprintf("INSERT INTO %s (user_name, email, device_regid, platform_type) VALUES ('%s', '%s', '%s', '%d')" , $tb_name, $name, $email, $deviceId, $platform);
echo "$query\n";
$res = mysql_query($query);
}
I already tested this board.php code and verified it is inserting the data in table.
But when i am doing this via $ajax i am getting "The page at localhost says: undefined" and nothing got written in my database also.
url: this.url, not $(this).url.
$(this) does not have a property called "url" in your context I think.

Jquery AJAX with codeigniter, always returns error

I am trying to write a script that will add the video currently being viewed to a database of favourites. However every time it runs, an error is returned, and nothing is stored in the database.
Here is the JQuery
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"localhost/stumble/site/add_to_fav.php",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
The add_to_fav.php is this...
public function add_to_fav(){
$this->load->model('model_users');
$this->model_users->add_favs();
}
And the add_favs function is below
public function add_favs(){
if($this->session->userdata('username')){
$data = array(
'username' => $this->session->userdata('username'),
'title' => $this->input->post('heading'),
'embed' => $this->input->post('embed')
);
$query = $this->db->insert('fav_videos',$data);
if($query){
$response_array['status'] = 'success';
echo json_encode($response_array);
}}else {
$response_array['status'] = 'error';
echo json_encode($response_array);
}
}
Thank you for the input, this has me stuck but I am aware it may be something relatively simple, my hunch is that it is something to do with returning success or error.
Try
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"http://localhost/stumble/Site/add_to_fav",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
Also to use base_url in javascript. In your template view :-
<script>
window.base_url = "<?php echo base_url(); ?>";
</script>
Now you can use base_url in all your ajax scripts.

Categories