I need to send variables (username+password) from a js function inside a .js file, to a PHP file, and store them inside the file.
I tried to use ajax but it doesn't work for me:
function func(){
var user = ...
var pass = ...
$.ajax({
type:"POST",
url:"myphp.php",
data: user,
success: function(){
alert("success!");
},
error: function(){
alert("error!")
}
});
}
when I open the PHP file I see nothing.
EDIT: my problem is much more basic. My ajax code just doesn't run inside the function. I have a .js file that contains only one function (the function above) and the ajax code doesn't get executed. I get no success nor error messages.
You need to pass the data to jQuery like this:
$.ajax({
type:"POST",
url:"myphp.php",
data: {user: user, password: pass},
success: function(data){
alert(data);
}
});
PHP won't have any problems parsing this, since jQuery automatically sends it in application/x-www-form-urlencoded. If you need to send JSON and have PHP read JSON, then that's a different story.
Related
I have had this error for multiple days now, I have tried searching this error up but whenever I search this error up it gives a different reason for the error and when I try to add what other sites say it doesn't work which is why I am asking here as I don't see what else I can do.
I am trying to pass a variable from JavaScript to PHP but it is not working and I have no idea why.
Here is my JavaScript code:
<head>
<script type="text/javascript" src="jquery.js"> </script>
</head>
<script>
var variable = "hello";
console.log(variable);
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function() {
alert("Success");
}
});
</script>
Here is my PHP code:
$variable = $_POST['pass'];
echo($variable);
Everything seems to work perfectly. It writes the variable to the console, it comes up with the alert saying success. However I get an error message saying: 'Undefined array key "pass"'
What is causing this? Thank you?
Edit: People have told me to use isset, I have added that it removed the error however it still does not echo the PHP variable, meaning it is still not been passed to PHP, I am still trying to find how to fix this.
Your front end code looks OK, but I don't know your target PHP environement, but maybe your environnement doesn't accept formData.
By default, jQuery send ajax POST data as formData.
Try to send data as JSON
$.ajax({
url: "ajax.php",
type: "POST",
data: JSON.stringify({pass : variable}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){alert(data);},
});
And then you will probably have to adapt your php code:
$json = file_get_contents('php://input');
// Converts it into a PHP array
$data = json_decode($json, true);
$variable = $data['pass'];
echo($variable);
Can you please use the developer tools in chrome browser that will help you to find if data is properly sent to php file.
Also you can try $_REQUEST instead of post just to check what data is coming in REQUEST as it works for GET & POST both. If it still does not help you.
Also can you please use
data: {'pass':variable}
instead of
data: {pass:variable}
let me know if it works for you.
If you get this error in your ajax.php file which you Post the data to it, I say it's normal because when you open that file (ajax.php) it's like that there is no $_POST['pass'] because you just opened that file without running JS to send data.
If you want to receive data that you send you can do this:
Your JS code I call this file index:
var variable = "hello";
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(res) {
alert(res);
}
});
The PHP file:
$variable = $_POST['pass'];
echo($variable);
Then if You open up that index file, after running the JS code it'll send that post data to your PHP file and your PHP file will echo that, then the value will store in that res variable which when every thing went fine, you can see the alert of that res in the page (index file).
Notice that as I said you can't open up the PHP file lonely because it doesn't receive a post data on its own, it is normal for undefined to return.
Re: #puckloe your code is working, php echo wouldn't be printed with ajax(correction echo is working but wouldn't show on page if you don't print it with JS too), you have to catch the response in ajax success function ( like success: function(response) ) and print or alert the response --> success: function(response) { alert("hi look this is echo from php"+response) }
you ajax code should look like
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(response) {
alert("hi look this is echo from php" + response);
}
});
I've been working on a web page which can't use PHP so I had to look up a solution without. I now have the following jQuery code:
function writeFile() {
alert("writing file...");
$.ajax({
type: 'POST',
url: "test.txt", // url of receiver file on server
data: "test", // your data
success: alert("sucess writing the file!"), // callback when ajax request finishes
dataType: "text" // text/json
});
};
The file is where it should be and the alert() are showing up (also the success alert) but somehow the file is empty. Why?
AJAX cannot directly write to a file, because JavaScript is a client side only and not server side. What you want is a server that catches your AJAX request; server can be anything, including PHP, JAVA or NodeJS. You can only read static files using AJAX but that is all.
You can't just write to a text file on the server using client-side AJAX scripting. You will have to use Node.JS or a PHP server-side script to write to the file on the server. This example below uses a PHP script. You will want a file called test.php in the same directory as the page the AJAX is on. This will POST the string "hello world" to test.php, as the superglobal $_POST['textcontent']. It is possible, using an anonymous function in the success field, to get the output from the PHP script and show it on the page. Note that you can replace "hello world" in the example below, to a $("#my-input-area").val() variable, if you want to write user input to a file.
function writeFile() {
alert("writing file...");
$.ajax({
type: "post",
url: "test.php",
data: {
textcontent: "hello world",
},
success: function(response) {
$("#ajax-area").html(response);
}
});
};
And then your PHP will look like this.
test.php
<?php
if (!empty($_POST['textcontent'])) {
file_put_contents("test.txt", $_POST['textcontent']);
exit("<p>TXT file written successfully!</p>");
}
// This is where you write to the text file.
// The string in the exit() function will appear in your $("#ajax-area")
else {
exit("<p>No text string submitted.</p>");
}
?>
Using the above example, the PHP script will receive the string "hello world" from the AJAX call. This will write to the test.txt file in the same directory as your PHP script, which would be in the same directory as the page with the AJAX. You can put these in a different folder on the server if you want. Anything the PHP script outputs, either with echo or with exit, will be returned as the response parameter, in your success function in your AJAX call.
I hope any of this helps.
Hi I am using ajax to do a post request. I think what I want to do is call a function within a php file but am a little confused if and how you do this, could anyone shed any light on this? This is what I have in my js file:
function callAjaxAddition2() {
arguments0 = jQuery('#code').val();
$.ajax({
type: "POST",
url: file.php",
data: {code: arguments0},
success: function(data) {
request( $posted )
}
});
return false;
}
'request' is a function within the php file.
Update I think I should be able to trigger what I need to using this: http://docs.woothemes.com/document/wc_api-the-woocommerce-api-callback/ if I put the url into the url field however that doesn't seem to work, how might I use a callback with ajax post?
First fix this line with the missing opening quote file.php".
You cannot call a PHP function through AJAX but can trigger when it needs to be called, the following demonstrates the same:
In your PHP, your code would be:
if(isset($_POST['code'])){
#'code' here is the identifier passed from AJAX
request($_POST['code']);
}
Once your function has been called, does the necessary and returns the output to AJAX, you can use the data parameter you have set to see what output was sent back from PHP:
success: function(data) {
alert(data); //contains the data returned from the
//PHP file after the execution of the function
}
Calling on a php file via ajax call is like running the script that you pass in the url parameter.
You don't get access to the inner functions, all you can do is pass data and get response.
If you want the request() function to be called in the script, you will have to call it in the php script.
This is my first time posting on this site. I have looked over several of the previous postings related to this topic, but did not find anything that works for me. I am trying to use javascript and jquery $.ajax to call a php script on the server and return the contents of the file. Thus far I am not getting any data back. I am able to update the .txt file on the server using the $.ajax, but could use some help in finding out what I am doing wrong to retrieve it. I do not see any errors being generated from the php script and the events.txt file is not blank. vb.net and c# are my native languages so this is a bit foreign to me.
My js is:
function readText() {
var url = "readdata.php";
var result = "";
$.ajax({
url: url,
type: 'get',
dataType: 'text',
success: function (data) {
result = data;
alert(result);
},
async: false
});
}
and my readdata.php script is:
<?
$file=fopen("events.txt","r");
$read=fread($file,filesize("events.txt"));
fclose($file);
echo $read;
?>
Any advise is welcome. Thanks!
The type in $.ajax should be in capitals
type: 'GET'
function readText() {
var url = "readdata.php";
var result = "";
$.ajax({
url: url,
type: 'GET',
dataType: 'text',
success: function (data) {
result = data;
console.info(result);
},
async: false
});
}
After adding the error: function(){} to the ajax call, I was able to work through this issue.
It turned out that part of the issue was permissions on the server (not able to read from file in the file permissions on the server).
Also I was trying to run locally and I did not have php installed on my local machine.
I know questions about loading XML into a JS variable have been posted here many times, but I didn't find a solution that would work. In my script I declare a variable before an ajax request, and then add the result to the variable. This works only if I add alert to the script:
var myDB;
$.ajax({
type: 'GET',
url: 'db.xml',
dataType: 'xml',
success: function (xml){
myDB = xml;
}
});
alert(myDB); //returns: undefined
$(myDB).find('item').each(function (){
var question = $(this).find('question').text();
alert(question);
});
The above code works only with the alert. When I delete the alert, the code doesn't work. How can I make this work without the alert?
You need to add your code to success handler for doing that:
var myDB;
$.ajax({
type: 'GET',
url: 'db.xml',
dataType: 'xml',
success: function (xml){
$(myDB).find('item').each(function (){
var question = $(this).find('question').text();
});
}
});
An ajax request is asynchronous. That means, the function you gave in the success option is excuted somwhen later.
After you've started the request, you're variable is still empty. Only if you wait long enough to confirm the blocking alert, the variable will have been loaded.
You will need to add the iteration to the success function, where the xml data is certainly available.