I have been struggling with sending a large string to a PHP page via AJAX post method.The AJAX part seems to be working fine and sending the string without any problem,my problem is as soon as i redirect to my destination page the PHP $_POST seems to be empty.
I have made some research and i found out that this is a recurring problem but none of the solutions worked for me.
Ajax page
PHP destination page
AJAX code
$("#save").click(function(event){
var data = $("#mycontent").html();
$.ajax({
type: "POST",
url: "concat.php",
cache:false,
dataType:"html",
data: {
mycontent: data,
},
success: function(msg){
alert( "Data Saved: " + msg );
top.location.href = 'concat.php';
}
});
});
PHP page
session_start();
if(isset($_POST['mycontent'])){
$content = $_POST['mycontent'];
}
var_dump($_POST);
var_dump($_REQUEST);
The $_POST vairable is not perserved between page redirection. You will need some other mechanism to perserve posted data ie. using $_GET, session or database etc.
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'm trying to send an array from a JS file to a PHP file in the server but when I try to use the array in php, I got nothing.
This is my function in JS:
var sortOrder = [];
var request = function() {
var jsonString = JSON.stringify(sortOrder);
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function() {
alert('data sent');
}
})
};
and this is my php file MYPAGE.php:
<?php
$arrayJobs = json_decode(stripslashes($_POST['sort_order']));
echo($arrayJobs);?>
This is the first time that I use ajax and honestly I'm also confused about the url because I'm working on a template in wordpress.
Even if I don't use json it doesn't work!
These are the examples that I'm looking at:
Send array with Ajax to PHP script
Passing JavaScript array to PHP through jQuery $.ajax
First, where is that javascript code? It needs to be in a .php file for the php code (wordpress function) to execute.
Second, how do you know that there is no data received on the back-end. You are sending an AJAX request, and not receiving the result here. If you read the documentation on $.ajax you'll see that the response from the server is passed to the success callback.
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function(responseData) {
// consider using console.log for these kind of things.
alert("Data recived: " + responseData);
}
})
You'll see whatever you echo from the PHP code in this alert. Only then you can say if you received nothing.
Also, json_decode will return a JSON object (or an array if you tell it to). You can not echo it out like you have done here. You should instead use print_r for this.
$request = json_decode($_POST['sort_order']);
print_r($request);
And I believe sort_order in the javascript code is empty just for this example and you are actually sending something in your actual code, right?
the problem is in your url, javascript cannot interprate the php tags, what I suggest to you is to pass the "get_template_directory_uri()" as a variable from the main page like that :
<script>
var get_template_directory_uri = "<?php get_template_directory_uri() ?>";
</script>
and after, use this variable in the url property.
Good luck.
I hope it helps
i have been reading some posts here regarding issues about storing values form JS to a PHP variable and most comments said to use AJAX.
both AJAX and JS codes can be used to store JS variable value to a PHP variable however can someone explain why most people suggest to use AJAX? or what advantages do I have if I used AJAX over JS to store that value
thanks
You cannot store a PHP value from javascript/jQuery without using AJAX.
After the DOM has been rendered, no additional PHP will run. That's it, all done. In order to send additional data to the server, you have two choices: (1) post a form to another PHP file, which will send the data typed into the form elements and will change/refresh the current page. or (2) use AJAX.
AJAX is a way to communicate with a separate PHP page, sending data back/forth, without refreshing/changing the page the user is on. An AJAX code block looks something like this:
$.ajax({
type: 'post',
url: 'ajax.php',
data: 'varName=' +varSomething,
success: function(d){
if (d.length) alert(d);
}
});
or
$.ajax({
type: 'post',
url: 'ajax.php',
data: 'varSomename=' +varValue
}).done(function(){
//success function
});
Data sent back from PHP is received in the AJAX code block's success function (and ONLY there), where it can be manipulated and/or injected back into the DOM, like this:
$.ajax({
type: 'post',
url: 'ajax.php',
data: 'thevar=' +theval,
success: function(d){
$('#someDIV').html(d);
}
});
Here are some additional links re AJAX:
dynamic drop down box?
Prevent Page Load on Jquery Form Submit with None Display Button
When the data arrives at the specified PHP file (ajax.php in above examples), you can get that data via the $_POST[] variable:
<?php
$summat = $_POST['someVarname'];
//To send data back to the AJAX success function, you just echo it:
$out = '<div style="font-size:3rem;color:blue;">';
$out .= $summat;
$out .= '</div>';
echo $out
Now you have the data in a local PHP variable. This variable will cease to exist when the PHP file execution is completed.
To retain the PHP variable, use a $_SESSION super-variable. In order to use the $_SESSION variable, you must add session_start() to the top of the PHP page:
<?php
session_start();
$_SESSION['summat'] = $_POST['someVarname'];
//Now you have a permanent variable on the server, associated with this user's PHP session
I am trying to create a conversation system with php jQuery and ajax.
I am using the following jQuery to handle the ajax post together with php.
function replyToStatus(sid,user,ta,postuser){
var data = $('#'+ta).val();
if(data.trim() == ""){
alert("Please type a reply before you submit.");
return false;
}else{
var dataString = 'action=status_reply&sid='+sid+'&user='+user+'&postuser='+postuser+'&data='+data;
$.ajax({
type: "POST",
url: location.href,
data: dataString,
cache: false,
success: function(response){
$('#'+ta).val("");
$( "#conrep_"+sid ).append( '<li><div class="comment-user-image-container"><div class="user-image" style="background:url(\'imagesrc.jpg\');"></div></div><div class="comment-content"><h5>admin '+data+'</h5><img class="scaledImageFitWidth img" src="userimagesrc.jpg"></div></li>');
}
});
}
}
This code appends and displays the post immediately to the current user(user1) making the post.However to all the other users viewing the same page whom have not refreshed the page after this user(user1) has posted ,this post won't appear until they have refreshed.
My question is how do I make a system that will automatically show this post to all users or how do I deal with this problem otherwise.
Thanks for the reply in advance:)
I have an HTML form that is processed via PHP, and it's a simple login script. This works fine, but I want to catch the error with AJAX. Basically, if the PHP function to check the login returns false, it should write that error onto the DOM via jQuery. However, if I catch the form submission with AJAX, it will stop the PHP file from doing the redirect. I want to stop the form from redirecting only if the PHP file returns false. Any help would be much appreciated. Here's some code to illustrate what I'm talking about:
controller_login.js
$(document).ready(function(){
$('form.loginSubmit').on('submit',function(){
var that = $(this),
url=that.attr('action'),
type=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){
var that=$(this),
name=that.attr('name');
value=that.val();
data[name]=value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
errorHandle(response);
}
});
return false;
});
});
function errorHandle(error)
{
console.log(error);
}
This is the file that will eventually modify the DOM if there is a PHP error. For now, it just logs.
checkLogin.php
if($verifySqlRequest==1){
session_register("loginUsername");
session_register("loginPassword");
header("location:http://localhost/asd/dashboard.html");
echo "login success!";
}
else{
echo "Wrong user name or password...";
}
This is just a snippet of the login authentication, but essentially I want that last echo to be communicated to controller_login.js, but it should continue the redirect if the login is successfully authenticated. Any help would be much appreciated!, thanks!
The browser isn't going to respond to a 302 or 301 (redirect) from an Ajax call. You can still certainly respond with that code, but, you'll have to handle the redirect manually via script:
window.location.replace("http://localhost/asd/dashboard.html");
or you can do it like this
> echo '<script>window.location.replace("http://localhost/asd/dashboard.html")</script>';
and
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
$('#response_element').html(response);
}
The point of using Ajax is to avoid reloading the page. If the user is going to be redirected upon login you may as well just submit the form synchronously and let PHP display the error.
Just for the sake of argument, if you wanted to do an Ajax function and display a message returned from the server you would NOT do:
<?php
echo 'this is the message';
?>
You would do
<?php
$response = array('message' => 'this is my message');
return json_encode($response);
?>
However, you can't redirect AND return data.