How to POST ajax and get response? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a problem with a form, the post and the response. In my form I call a function (javascript) with the ajax post:
var vars = "test="+test;
$.ajax({
type: "POST",
url: "index.php",
data: vars
}).done(function(data) {
alert(data);
}).fail(function(data) {
alert(data);
});
In index.php I receive all the data:
<?php
$test = $_POST['test'];
//do something
?>
After I have to give back a value to the previous php.
How can I do?? Thanks

The same way you send data back for any other HTTP request.
header("Content-Type: text/plain"); # Avoid introducing XSS vulnerabilities
echo $test;

If it's a simple value you need to return, you can just echo it, and it will come back as the response.
If you need to return a more complex structure, you store it in a PHP array, say $response, and use echo json_encode($response); to output it back to javascript.

This may help
Javascript
var vars = { test : "test" };
$.ajax({
type: "POST",
url: "index.php",
dataType : 'json',
data: vars,
success : function(data) {
console.log(data);
},
error : function(resp) {
console.log(resp.responseText);
}
});
PHP
<?php
$test = $_POST['test'];
echo json_encode($test);
?>
Try it and check console log

var vars = "test="+test;
$.ajax({
type: "POST",
url: "index.php",
data: vars
success: function(html){
alert(html)
}
});
in index.php, enter follow code and check
<?php
$test = $_POST['test'];
//do something
echo $test
?>

If you have to return data in JSON format then use
echo json_encode($test);
Else you can simply echo the variable which you need in the ajax response. i.e.
echo $test;

Related

transfer data from localstorage to same php file and recall data to variable

I have data in localStorage and POST successfully to the self php file using ajax as code below:
<script type="text/javascript">
var cartID = JSON.parse(sessionStorage.getItem("magiohang"));
console.log("your cart ID is:"+cartID);
$.ajax({
type: "POST",
url: "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>",
data: {cartID: cartID},
success: function(data){alert("data transfered successfully")}
});
</script>
then I want to recall this data to a variable inside this php file so that I can send it to my email. Code as below:
<?php
$name = "";
error_reporting(E_ALL); ini_set('display_errors', 1);
if (isset($_POST["cartID"])) {
$name = $_POST["cartID"];
}
echo $name."\n";
$values = json_decode($name);
echo "your cartID is: ".$values."\n";
?>
I test it in inspect view there is no error message but the variable $name doesnot have recalled data. Please help me to fix it. Thank you.
You are most likely missing the JSON.stringify call on your data:
$.ajax({
type: "POST",
url: "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>",
data: JSON.stringify({cartID: cartID}),
success: function(data){alert("data transfered successfully")}
});

Pass variable to another page using AJAX [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
## This My test.php file ##
//here I am getting the variable value
<?PHP
$name = $_POST('variable');
echo $name;
?>
## This my script ##
//avariable value passing to test .php file
<script type ="text/javascript">
var name = "jani";
$.ajax({
type: 'POST',
url: 'test/test.php',
data: {'variable': name},
});
</script>
###** I am getting this error **###
Fatal error: Function name must be a string in
D:\xampp\htdocs\test\test.php on line 2
Change your test.php code use square bracket not round for super global variable as below,
<?php
if (isset($_POST['variable'])) {
$name = $_POST['variable'];
echo $name;
}
?>
Try this it will definitely work:
My PHP File:
<script>
var name = "name";
var url = "test/test.php";
$.ajax({
url: url,
type: 'POST',
data: {'name': name},
success: function (data) {
console.log(date);
}
});
</script>
Where ajax request recieves:
//here I am getting the variable value
<?PHP
$name = $_POST['name'];
echo $name;
?>
After Your latest comment I have added js fiddle link
before running it open console and POST besides headers section you can see data has been posted.
Js Fiddle Demo Link

PHP gets JSON String as array

I have a form with 17 checkboxes. When one of these changes, JavaScript should submit the values to the server (running PHP).
I want to use JSON, because the checkboxes give two arrays which have to be seperated in PHP
In JS, I create an JSON-String, which I want to submit via POST and read and decode in PHP.
The String looks like this atm: [["2015-06-26","2015-06-27"],["2","3","4","5","6","7","8","9","10","11","12","13","14"]] - This is what I want it to be.
This is, what my AJAX-function looks like:
var fullArray = [dateArray, trackArray];
var jsonFullString = JSON.stringify(fullArray);
//jsonFullString == [["a","b","c"],["d","e","f","g"]]
$.ajax({
type:'POST',
url:'shownitems.php',
data: jsonFullString,
success: function(data){
//More script. This comment is reached, because
alert(data);
// works.
}
});
When I get it to PHP, and search for $_POST[0] the success function in JS doesn't show anything. When I search for $_POST, I get "Array.." back.
This is, what my PHP looks like (This is my test snippet):
<?php
echo $_POST;
echo ".";
echo $_POST[0];
echo ".";
echo $_POST[0][0];
$array = array();
?>
I am also using jQuery.
In your JS:
/* dateArray and trackArray must be variables with values */
$.ajax({
method: "POST",
url: "shownitems.php",
data: { date: dateArray, track: trackArray }
}).done(function(response) {
alert(response);
});
In your PHP:
<?php
var_dump('Date: '.$_POST['date']);
var_dump('Track: '.$_POST['track']);
?>
You should get your request content instead the $_POST variables.
Something like this would
$json = file_get_contents('php://input');
$obj = json_decode($json); //Will contain your array of two arrays
In case you wanted to get your post variables like you are doing, you could change your AJAX request and use:
$.ajax({
type:'POST',
url:'shownitems.php',
data: {
data: jsonFullString
},
success: function(data){
//More script. This comment is reached, because
alert(data);
// works.
}
});
And your PHP would be:
$json = $_POST["data"];
$obj = json_decode($json); //Will contain your array of two arrays

javascript array in php using Ajax on submit not working

I have an array that i pass from javascript to php and in php page i am trying to put it in session to be used in the third page. The code is as below
JavaScript:
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
var jsonString = JSON.stringify(table_row);
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: jsonString},
success: function(data) {
alert("It is Successfull");
}
});
test1.php
<?php
session_start();
$check1 = $_POST['myJSArray'];
$_SESSION['array']= $check1;
echo $check1;
?>
test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
on submit i call the function in javascript and the form takes me to test2.php. It is giving error on test2.php page Notice: Undefined index: array in C:\xampp\htdocs\test\test2.php on line 13
Any suggestions please do let me know.
You don't need to stringify yourself, jquery does it for you, if you stringify it, jQuery will believe you want a string instead
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: table_row},
success: function(data) {
alert("It is Successfull");
}
});
However, on the php side, you still need to decode it as it is always a string when you get it from $_POST. use json_decode to do it.
$check1 = json_decode($_POST['myJSArray']);
look at your test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
if it's only the code in the file then the error you got C:\xampp\htdocs\test\test2.php on line 13 is mindless, because there is not line 13,
but if you have something about the code you show us, may there be something echoed before?
because session has to be started before any output,
otherwise I've tested whole script and works fine...
To check if session really started (otherwise $_SESSION will not work), try this:
if(session_id())
{
echo "Good, started";
}
else
{
echo "Magic! strangeness";
}
if problem not found in test2.php you can check test1.php echo $_SESSION['array'] after saving it, and in your javascript callback function alert data param itself,
I'm sure you can catch the problem by this way.
i got it to work, the code is below
Javascript file: in page index.php
Either you can call this function and pass parameter or use code directly
var table_row = []; //globally declared array
var table_row[0]=["123","123","123"];
var table_row[1]=["124","124","124"];
var table_row[2]=["125","125","125"];
function ajaxCode(){
var jsonArray = JSON.stringify(table_row)
$.ajax
({
url: "test1.php",
type: "POST",
dataType: 'json',
data: {source1 : jsonArray},
cache: false,
success: function (data)
{
alert("it is successfull")
}
});
}
Page: test1.php
session_start();
unset($_SESSION['array']);
$check1 = $_POST['source1'];
$_SESSION['array']= $check1;
echo json_encode(check1);
Page: test2.php //final page where i wanted value from session
if(session_id())
{
echo "Session started<br>";
$test = $_SESSION['array'];
echo "The session is".$test;
}
else
{
echo "Did not get session";
}
?>
In index page i have a form that is submitted and on submission it calls the ajax function.
Thank you for the help, really appreciate it.

Passing Javascript variable to PHP variable using AJAX on the same page [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to convert my javascript variable to php variable. I can get the value of "1" when i click the link but i want to echo it using PHP or i want to store it on a PHP variable.
this is my Javascript and PHP code on the same page.
<?php $userid = 1; ?>
<a href="#" onclick="sendEmail(<?php echo $userid; ?>)" > Send Mail </a>
<script type="text/javascript">
function sendEmail(userid){
var sendID = userid;
$(document).ready(function(){
$.ajax({
type: "POST",
url: "ajax.php",
data: { toID: sendID },
dataType: 'json',
cache: false,
success: function( toID ){
alert( toID ); }
});
});
}
<?php
$userid = $_POST["toID"];
echo $userid;
?></script>
no display when i echo it.
thanks.
You can't do this, because your ajax request go to another request, and your current php file can't get it.
yourFile.php -> Ajax Request -> yourFile.php
| |
| |-- here your $_POST['todID'] has the value, but it's other thread
|-- here your $_POST['toID'] is empty
UPDATE 1: You can use success callback to show results or do any.
success: function( data ) {
alert( data ); //<--- this have the result of your ajax request
javaScriptVar = data;
}
UPDATE 2: If you need send email in the same file that shows the form, you need put at head:
<?php
if(isset($_POST['toID'])) {
sendmail($_POST['toID'], "subject", "body");
}
?>
According to your code you are passing a userid to ajax request and getting another userID, Do one thing to achieve that:
<input type="hidden" name="userid" id="userid" value="<?php echo $userid; ?>">
<a href="#" onclick="sendEmail()" > Send Mail </a>
and in you js code:
function sendEmail(){
var sendID = $('#userid');
$(document).ready(function(){
$.ajax({
type: "POST",
url: "ajax.php",
data: { toID: sendID },
dataType: 'json',
cache: false,
success: function( toID ){
//alert( toID );
// update the userID
sendID(toID);
}
});
});
}

Categories

Resources