I try to send a variable using jquery and ajax to php script. Then I want to use that variable in creating a file name but it fails. The file name is always "0" and does not locate at the dir "redirect".
Here is the code:
Ajax:
var pageName=$('#movie').val();
$.ajax({
type: "POST",
url: "phpstuff.php",
data: { pageName: 'pageName'},
cache: false,
success: function()
{
alert(pageName);
}
});
the "pageName" variable gets the value from an input box with an id "movie"
The php file
function createPage ($newPage){
$file=fopen("redirect/"+$newPage+".php","w") or exit("Fail to create the page");
$data = "some text I want to be in a file";
fwrite ($file, $data);
fclose($file);
}
$newPage = $_POST["pageName"];
createPage($newPage);
I have searched the net for hours and still can't fix the problem.
Line
data: { pageName: 'pageName'},
should be
data: { pageName: pageName},
A print_r( $_POST["pageName"] ) would show you what is being passed, in the first version $_POST["pageName"] is 'pageName'
You could also use
data: 'pageName='+pageName,
The description on http://api.jquery.com/jQuery.ajax/ for data parameter is'nt very clear as it talks about GET and dosn't mention POST.
String concatenation should be done with .:
"redirect/" . $newPage . ".php"
Try changing this line:
$file=fopen("redirect/"+$newPage+".php","w") or exit("Fail to create the page");
to
$file=fopen("redirect/".$newPage.".php","w") or exit("Fail to create the page");
Notice the changes from + to .. In PHP + is for addition, and . is for string concatenation.
Related
I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:
Javascript:
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "POST",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
Then on my php tag:
<?php
if(isset($_GET['subDir']))
{
$subDir = $_GET['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!
When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
or also:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
Then in the response:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the
Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).
Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:
_POST means that this is an AJAX call
_GET means that this is the normal opening of signage.php
So you would do something like:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
A surer way to check is verifying the XHR status of the request with an ancillary function such as:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* #return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
Now you would have:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
and actually you could offload your AJAX code into another file:
if (isXHR()) {
include('signage-ajax.php');
exit();
}
You are send data using POST method and getting is using GET
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
You have used method POST in ajax so you must change to POST in php as well.
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
Edit your javascript code change POST to GET in ajax type
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "GET",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
when you use $_GET you have to set you data value in your url, I mean
$.ajax({
type: "POST",
url: 'signage.php?subDir=' + val,
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
or change your server side code from $_GET to $_POST
So I have a page where the user will hit the "export" button and I want to run a javascript function and get the data I need for the export and then call a php script to get the data from my database and force a download. Right now the problem is, I can run the javascript and then I call a post to my script, but nothing is downloaded. I am assuming it is because I am not actually moving the window to the php file, I am simply calling the script. can anyone help me out?
javascript: ids is an array that I need to pass to get the information. This is inside the function taht I call when the user hits the "export" button.
$.ajax({
type: "POST",
url: "exportLeads.php",
data: { 'idArray' : ids }
});
php: I used this Export to CSV via PHP quetsion. The function are implemented properly and I get no errors. There is just no file that is prompted for download.
$data = mysql_query($query) or die($query.mysql_error());
$results = array();
while($line = mysql_fetch_array($data, MYSQL_ASSOC)){
$results[] = $line;
}
download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($results);
die();
You cannot download files with ajax. You can use window.location.href to redirect user to the file location, but whatever, i suggest you to read this, someone has a better answer for you :)
Download a file by jQuery.Ajax
or you can also use something like this
in your javascript
$.post( "exportLeads.php", { 'idArray' : ids }, function( response ) {
if ( response.error === 0 ) {
window.location.href = response.location;
}
}, "json" );
and in your php file
<?php
if ( $has_error ) {
echo json_encode( array( "error" => 1 ) );
}
else {
echo json_encode( array(
"error" => 0,
"location" => "link_to_file"
) );
}
?>
Got no time to write code, but in few words, you need:
Execute JS to call server side via ajax.
Generate file, put it to the server drive with some random name. Remember that name to session. Send some response to client.
When client gets response, redirect user with JS to some page where PHP code checks if there is some filename in session, and if there is, reads this file, deletes it and its name from session.
You could go for window.location.href in your success function:
$.ajax({
type: "POST",
dataType: "json",
url: "exportLeads.php",
data: { 'idArray' : ids },
success: function(data) {
if (data.success) window.location.href = "/link-to-your-download-script";
}
});
You would have to change the response to json_encode and split the functionality into two scripts, one for the export and one for the download script (with a unique id or sth.)
I want to send an array from javascript to php via ajax function.
And I don't want show the result as callback, but immediately open the target php file and show the images.
I mean, I want open the php file directly on the server side.
I think this is quite simple, but I just have no idea.
My javascript looks like:
var stringArray = new Array("/images/1.jpg", "/images/2.jpg", "/images/3.jpg");
$.ajax({
url: 'test.php',
data: {stringArray:stringArray},
success: function() {
window.open('test.php'); // It opens test.php in a window but shows nothing!
},
});
the test.php file:
$stringArray = $_GET['stringArray'];
foreach($stringArray as $value) {
echo "<img src=" . $value . "></img>";
}
Thanks for any help!
Likely the window.open command is being called without the POST data needed.
Now, I don't know what you want to do here but, why send an Ajax request when you don't really want to make use of it?.
Edit: just to make it a bit clearer, you seem to be calling the php file with no data trough POST. There is no clean way of opening a window in JS with POST data, just try GET for no critical information. Let is know how it goes.
As I can see, You are sending data by post method and accessing in test.php
but when u open file via window.location it doesn't get POST data hence no data get populated
You can achieve it via $_SESSION.
in test.php
session_start();
if(!empty($_POST['stringArray'])) {
$_SESSION['stringArray'] = $_POST['stringArray'];
}
$stringArray = (isset($_SESSION['stringArray']) && $_SESSION['stringArray'] != '') ? $_SESSION['stringArray'] : $_POST['stringArray'];
foreach($stringArray as $value) {
echo "<h3>" . $value . "</h3>";
}
Hope this will work for you...
you should write
var stringArray = new Array("apple", "banana", "orange");
$.ajax({
type: 'post',
url: 'test.php',
data: {stringArray:stringArray},
success: function(message) {
window.open(message); // It will open a window with contents.
},
});
I doesn't show the output because when you open the page on the callback you are not sending anything through to the test page through the post variable. Why you would want to do this I don't know. Send the information through the url, get.
I am making a http://c9.io like service to edit .php files on my server right on browser.
I have implemented CodeMirror editor there.
Editor looks following: http://codemirror.net/mode/php/index.html
My problem is that I can't send data with php code in it via jQuery.ajax POST.
Lets imagine that I would like to save following lines to hello.php:
<?php
require_once("lukujA.php");
?>
I am using following js / jquery code to save the file:
$(".save-file").click(function (){
var content = editor.getValue(); //textarea text
var path = "hello.php";
//following line shows content-data as it shows on CodeMirror editor
//confirm box without any quotes / slashes / and with every linebreak
var response = confirm("Do you want to save? DATA: " + content);
if(response)
{
$.ajax({
type: "GET",
url: "saveFile.php",
data: "content="+content+"&path="+path+"",
success: function(){
alert("File saved!");
}
});
}
else{
alert("File not saved!");
}
});
saveFile.php:
$path = $_GET['path'];
$content = $_GET['content'];
if($path !== "" and is_writable($path))
file_put_contents($path, $content);
above code outputs hello.php as something like following (on one line and with slashes)(using POST seems to remove any line breaks I made on the editor):
<?php require_once(\"lukujA.php\"); ?>
I can't use stripslashes($content); on saveFile.php cause if I have php code like:
<?php echo "<input type=\"text\" name=\"foo\">"; ?>
strip_slashes would remove those slashes and code would become invalid when executed.
How should I come across this and how should I save the new code to a file?
How would you make this kind of editor?
Thanks
Got the whole thing working with following:
$(".save-file").click(function (){
editor.save();
var content = editor.getValue(); //textarea text
var path = $("#hiddenFilePath").text(); //path of the file to save
var response = confirm("Do you want to save?");
if(response)
{
$.ajax({
type: "POST",
url: "saveFile.php",
data: {c:content,p:path},
dataType: 'text',
success: function(){
alert("File saved!");
}
});
}
else{
alert("File not saved!");
}
});
See the code data: {c:content,p:path}, dataType: 'text',
and in saveFile.php I use stripslashes($content) cause it seems I have magicquotes on on php settings.
When I need to send data like echo "<br>Edellinen Tämä viikko Seuraava<br><br>"; stripslashes still preserves those slashes before my data's quotes cause when I send data through POST like that seen above urlEncoding adds slashes before my datas slashes too.
Hard to explain. Hope someone will in future get something out of this :) Sorry for not so good english either.
jQuery(document).ready(function(){
// Set the data text
var dataText = "
{
name: 'John',
time: '2pm'
}";
alert(dataText);
// Create the AJAX request
$.ajax({
type: "POST", // Using the POST method
url: "/ajax/analytics/push", // The file to call
data: dataText, // Our data to pass
success: function() { // What to do on success
alert("Data Loaded: " + dataText);
}
});
});
</script>
hello im still learning ajax. how can we push a array of $_POST?
1.im trying to do something like
var dataText['name'] = 'Jhon';
var dataText['time] = '2pm';
then somehow turns it into
$_POST['name'] = 'Jhon';
$_POST['time'] = '2pm';
then send it to the url..
2.is there a way to debug this ? what im doing now is im writing
# somehow doesnt work becouse its not auto refresh when the ajax sends a post
var_dump($_POST);
# ok heres how i debug it right now.
ob_start();
// write content
$content = $_POST;
ob_end_clean();
file_put_contents('CACHE',$content);
in to a file, i hope there is a better solution for this..
Thankyou for looking in.
Adam Ramadhan
I'm not entirely sure what you're doing. You seem to be building JSON manually (and not doing it correctly) and then passing that (in the JSON-serialised string form) to your file. You then seem to expect it to be parsed by PHP automatically.
It would be better to send it as key-value pairs. You can let jQuery do this for you if you pass in an object. This won't look much different to your existing code:
var dataText =
{
name: 'John',
time: '2pm'
};
Note that I have removed the double quotes. This is primarily because it is illegal to have a JS string covering more than one line without escaping the line breaks. It is also because you want the object to pass into your $.ajax call.
These should be available as $_POST['name'] and $_POST['time'] now.
file_put_contents('CACHE',serialize($content));
or
foreach($_POST as $k => $v) $content .= $k .'='.$v;
jQuery(document).ready(function(){
// Set the data text
var dataText =
{
name: 'John',
time: '2pm'
};
alert(dataText);
// Create the AJAX request
$.ajax({
type: "POST", // Using the POST method
url: "/ajax/analytics/push", // The file to call
data: dataText, // Our data to pass
success: function() { // What to do on success
alert("Data Loaded: " + dataText);
}
});
});
# ok heres how i debug it right now.
ob_start();
# somehow doesnt work becouse its not auto refresh when the ajax sends a post
var_dump($_POST);
$content = ob_get_contents();
ob_end_clean();
file_put_contents('CACHE',$content);