Pass variable to another page using AJAX [closed] - javascript

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

Related

How to fix Passing the JS array to PHP through ajax

I have two files, game.js and gallery.php. So I have been trying to send an array from game.js to gallery.php through ajax. I have attached the code I tried , below:
game.js:
imgarray.push({"img_name":img_name,"x":x_value,"y":y_value,"w":w_value,"h":h_value});
var st = JSON.stringify(imgarray);
$.ajax({
url: "gallery.php",
method: "POST",
data: { data :st},
success: function(data){
console.log(st);
alert("OK");
}
});
gallery.php:
<?php
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}?>
so in the above code , when I run it , in the console log for game.js i am able to print the array. but when I tried to get the array in gallery.php and print it, it throws an error, says st_img is undefined and the for the echo it produces NULL.
Can someone help me fix this.

How to POST ajax and get response? [closed]

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;

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.

.ajax POST image data URL not working [closed]

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 9 years ago.
Improve this question
I have a canvas converted into a data url, and I need to save it locally in my server. For some reason I can't get this (simple) thing to work. It doesn't write any file on "natalisations" folder. The folder as the write permissions, and javascript seems to do it's work fine and with no errors. Php doesn't give me any error, just doesn't write the actual file.
Javascript
function postData(data) {
alert(data);
$.ajax({
type: "POST",
url: "uploadaux.php",
data: {image: data}
}).done(function( respond ) {
alert(respond);
});
the output of alert(data) is "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAg(...)"
This is the uploadaux.php file:
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
$dataURL = $_POST["image"];
$parts = explode(',', $dataURL);
$data = $parts[1];
$data = base64_decode($data);
$fp = fopen('natalisations/image.jpg', 'w');
fwrite($fp, $data);
fclose($fp);
}
I've been debugging this for ages... and no sign of finding a solution. Thanks in advance!
If you mean that your javascript isn't returning anything to you, it's because you have no return data in your PHP, try this, it also has a fair bit of debugging.
if(isset($_POST['image']) && !empty($_POST['image'])) {
$dataURL = $_POST['image'];
$parts = explode(',', $dataURL);
$data = base64_decode($parts[1]);
if(is_writable('natalisations/')) {
$success = file_put_contents('natalisations/image.jpg', $data);
echo ($success ? 'success' : 'unable to save file');
} else {
echo 'directory not writable';
}
} else {
echo 'no image';
}

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