Can't receive data, ajax, javascript, jquery, php - javascript

I am trying to send data that i got from a jquery call and now i want to save it to a file on the server with php.
function getSVG(){
svghead = svghead + $('#test').html();
$.ajax({
type:"POST",
data: svghead,
url: "xyz.php",
success:function(data){
.....
}
});
}
and in php my code is:
<?php
header('Content-Type: text/html; charset=utf-8');
$data = $_POST['data'];
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, $data);
fclose($myfile);
?>
but the created file never contains any value. it s just empty. as far as i tested, i guess it is just a syntax mistake but where or what is wrong? thx for any help

You need to specify the parameter name in order to PHP recognize it:
data: {
data: svghead
}
With the object above you're sending a data paramenter with the value equal to your svghead variable.

Related

Download file with ajax and php - readfile not working

I want to save a value to a txt-file and download it to the user.
Right now, the value is being printed into the txt-file correctly, but the readfile function is not triggered, thus no downloading begins.
The php, this code is located on the same page as the ajax call.
<?php
if (isset($_POST['data']))
{
$handle = fopen("file.txt", "w");
fwrite($handle, $_POST['data']);
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
}
?>
The javascript, there is no url because the data is to be sent to the current page.
function exportColors() {
var exportData = this.dataset.id;
$.ajax({
type: "POST",
data: {data: exportData},
success: function (data) {
console.log(data);
}
});
}
You need to separate the functionality, that is, post the data to PHP first, save the content of the text file and then, in a second request, let the user download the file. So one (skeleton) approach would be:
JS File:
function exportColors() {
var exportData = this.dataset.id;
$.ajax({
type: "POST",
data: {data: exportData},
success: function (data) {
// redirect or print out a link
}
});
}
PHP File for the first request (saving the content):
<?php
if (isset($_POST['data'])) {
$handle = fopen("file.txt", "w");
fwrite($handle, $_POST['data']);
fclose($handle);
// give back some unique id or the unique filepath
}
?>
PHP File for the second request (be it through clicking on a link or after having been redirected):
// essentially everything that outputs your file
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
Comments:
Either give back a unique filepath or via a handle through a database (more secure, but more complex as well). Besides, why should the user download the unchanged data he has formerly submitted? Is there more to it than meets the eye?
Ok I'm going out on a limb so take this with a grain of salt.
You said this request is going to the current page? Does that mean you've excluded (for the sake of brevity) HTML content from the PHP file you're showing us? If you have ANY content above your opening <?php tag, then any call to header will fail with an error (because headers must come before the body of a request). This would cause the script to terminate and prevent the readfile line from ever being reached.
Are your headers being sent? Do you see anything in the error log? If the answers to these are yes and no respectively then I'm wrong and you can ignore this.
Due to security reasons, ajax won't be able to download/save the file to the client's system because of java-script constraints.
Instead you can use
jquery.fileDownload.js
Please have a look at http://jqueryfiledownload.apphb.com/
Hope this helps.
you can't
beacuse javascript is not able to write on user file system.
see answer
Download a file by jQuery.Ajax
explain problem very well
The following Ajax generates a new file on the server at runtime AND downloads it to the client machine's /downloads directory with a single click. It uses Javascript to download the file, not PHP readfile().
await $.ajax("generateFile.php", {
type: "POST",
data: {
param_1: param_1,
param_2: param_2
},
success: function(data){
var a = $("<a>")
.attr("href", "path/filename_on_server.txt")
.attr("download", "filename_on_client.txt")
.appendTo("body");
a[0].click();
a.remove();
},
error : function(data) {
alert("ajax error, json: " + data);
}
});

Getting data from database on pageload jquery php

can any one help me please
What Im trying to do is a phone app using HTML5, JQUERY, Json and PHP. I cannot use PHP pages in this as I will be packaging it with Phone Gap Cloud Compliler.
I have tried using many scripts and suggestions that I have researched on the internet but cannot seem to get this to work.
On the page I need to retrieve data from the database there are 6 text boxes or divs I wish to populate using a on page ajax request to a PHP processing page that gets the required data and forms it into a Json string, the following scripts will show where I am at presently.
PHP Page:- this works as far as getting the data from the database and from the research I have done succssefully parces it into a Json format
PHP Script **********************************************
<?php
include_once 'db_connect.php';
header("Content-Type: application/json"); //this will tell the browser to send a json object back to client not text/html (as default)
session_start();
$return_arr = array();
$sql = "SELECT * FROM `autumnTerm`"; //query
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
$row['term1start'] = date('d-m-y', strtotime($row['term1start']));
$row['term1finish'] = date('d-m-y', strtotime($row['term1finish']));
$row['term2start'] = date('d-m-y', strtotime($row['term2start']));
$row['term2finish'] = date('d-m-y', strtotime($row['term2finish']));
$row_array['term1start'] = $row['term1start'];
$row_array['term1finish'] = $row['term1finish'];
$row_array['term2start'] = $row['term2start'];
$row_array['term2finish'] = $row['term2finish'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
this returns the following json :-
[{"term1start":"01-04-15","term1finish":"02-04-15","term2start":"03-04-15","term2finish":"04-04-15"}]
which I believe to be the right format.
The Jquery:-
<script>
I think I am right in believing that document ready should run the jquery script on page load
$(document).ready(function() {
the processing page address which is associated to a variable
var url = "http://www.newberylodge.co.uk/webapp/includes/retrieveAutumn.inc.php";
The ajax request defining the request elements
$.ajax({
type: "POST",
cache: false,
url: url,
dataType: "json",
success: function(data) {
$('#termoneError').text('The page has been successfully loaded');
},
error: function() {
$('#termoneError').text('An error occurred');
}
});//ajax request
});//ready function
</script>
If anyone would be so kind as to helping me figure this out I would be most greatful, I have been trying to resolve this for over a week now
I havent posted the html trying not to swamp the question with code, but if its needed I will put it up on request
try this:
$.ajax({
type: "GET",
cache: false,
url: url,
dataType: "json",
success: function() {
console.log()
$('#termoneError').text('The page has been successfully loaded');
},
error: function() {
$('#termoneError').text('An error occurred');
}
});//ajax request
});//ready function
</script>
and try to see the console is there any error?
you should try for the error Cross-Origin Request Blocked to put proper header
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,POST,OPTIONS');
header('Access-Control-Allow-Credentials: true');
the rest code its ok

PHP request through AJAX fails

This is probably something very simple, and I've seen that there are/have been more people with the same issue. But the solutions provided there did not seem to work.
So, I want to execute a .php file through AJAX. For the sake of testing the php file (consolefunctions) is very small.
<?php
if(isset($_POST['action'])) {
<script>console.log('consolefunctions.php called.');</script>
}
?>
And now for the javascript/ajax part.
$(".startConsole").click(function(){
var consoleID = $(this).attr("value");
$.ajax({ url: 'include/consolefunctions.php',
type: 'post',
data: {action: 'dosomething'},
success: function(output) {
//alert("meeh");
}
});
});
Somewhere, somehow there's an issue because the message from the PHP file never shows. I've tested the location from the php file, which is valid.
First the php code is not correct, you should add an echo
<?php
if(isset($_POST['action'])) {
echo"<script>console.log('consolefunctions.php called.');</script>";
}
?>
but the problem is, when you send this code to js, you'll get it as a string on your variable output, not as a code that will be executed after making the ajax call, so the best way to do this is to echo only the message to display on your console and then once you receive this message you can call console.log function
<?php
if(isset($_POST['action'])) {
echo"consolefunctions.php called";
}
?>
in the success function :
console.log(output);

pass javascript variable to php mysql select query

I am running a mysql select query in php like this
<?php
$getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'";
$result=mysql_query($getvalue) or die(mysql_error());
while($row=mysql_fetch_array($result)){
extract($row);
echo $name;
}
?>
var1 and var2 are javascript variables on the same page. I know client side variable cannot be passed to server side. But is there any workaround as the variables are in the same page.
In order for you to make this happen - I believe - you have to use AJAX.
The code will look like this:
$.ajax({
url: 'your_script.php',
type: 'POST',
data: {var1: javascript_var_1, var2: javascript_var_2},
success: function(data) {
console.log("success");
}
});
Your PHP will look similar to this (without keeping in mind the JSON encode:
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'";
$result=mysql_query($getvalue) or die(mysql_error());
while($row=mysql_fetch_array($result)){
extract($row);
echo $name;
}
?>
Then you can JSON encode the results and pretty much output them on the success. Your php script - however - must live on another php file.
Also, escape your data. Use prepared statements.
In theory, you could pass the vars to php via some sort of ajax call. I think it would go something like...
JavaScript:
var data = {
'var1': $('selector').val(),
'var2': $('selector').val()
};
$.ajax({
type: 'post',
url: 'path-to-your-file.php',
data: data,
timeout: 50000
}).done(function(response) {
console.log(response);
}).fail(function(error) {
// uh-oh.
});
php:
<?php
print_r($_POST['data']);
Otherwise, you could use:
cookie
hidden input
php:
<?php
... column1='$_COOKIE["mycookie1"]' and column2='$_COOKIE["mycookie1"]'";
... column1='$_POST["hidden1"]' and column2='$_POST["hidden2"]'";
NOTE: you will want to sanitize the data. Using raw cookie and/or input values could lead to some less than desirable results.
Use Method Post in AJAX or Form!! To send js variable in Php and receive it in php using $_post[ name_of_obj ];

Returning a json array using AJAX

Here's the javascript:
var data = $('form#registration-form').serialize();
$.post(
'<?php echo $this->url('/register', 'do_register')?>',
function(data) {
alert(data);
},
'json'
);
And here's the ending of the do_register() method:
if( $_REQUEST['format']=='JSON' ){
$jsonHelper=Loader::helper('json');
echo $jsonHelper->encode($registerData);
die;
}
The $registerData variable holds all the data I need. I want the function to return it after the ajax call. However, when I specify dataType: 'json' nothing is returned. Any suggestions?
I think your problem is in url
$.post(
'<?php echo $this->url("/register", "do_register"); ?>?format=JSON',
function(data) {
alert(data);
},
'json'
);
Also you can use following line in php part to get json values
header('Content-Type: application/json');
I suppose problem is somewhere here:
'<?php echo $this->url('/register', 'do_register')?>', in using quotes.
Use double and single quotes:
"<?php echo $this->url('/register', 'do_register')?>",.
It's impossible to receive right suggestion with little description.
Y'd better to paste more php & javascript code, with much more context, thing to be simple.
And another suggestion, mixed coding is bad. separating the javascript and php with php template such as Smarty.
var data = $('form#registration-form').serialize();
$.post(
'<?php echo $this->url('/register', 'do_register')?>',
function(data) {
alert(data);
},
'json'
);
this source file of above code is a php file ?
Debug with firebug to capture weather the ajax request sent or not
Why use JSON helper??
json_decode(string $json);
json_encode(mixed $value); //normally array...
it is built-in in php.

Categories