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

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);
}
});
});
}

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

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.

How to get a row from database using ajax in codeigniter

i am trying to get a row of data from database using ajax in codeigniter.
Here is the javascript function-
$(function(){
$("button[name='program_view_details']").click(function(e){
e.preventDefault();
var program_id=$(this).attr('id');
$.ajax({
url: "<?php echo base_url();?>program_management/get_program_data",
type: "POST",
dataType: "html",
data: "program_id="+program_id,
success: function(row)
{
alert(row.program_name);
}
});
});
I am not sure if the datatype and post is correct or not.
Here is my controller function-
public function get_program_data( ){
$program_id = $this->input->post('program_id');
$this->load->model('program_management_model');
$data['programs']= $this->program_management_model->get_program_specific($program_id);
echo $data;
}
Here is the model-
function get_program_specific($program_id){
$query=$this->db->query("SELECT * FROM programs WHERE program_id='".$program_id."'");
return $query->result();
}
I am searching the way of returning the row from controller to javascript. But the alert() is showing "undefined" in the success. Please anyone tell me the whole way through. Thanks in advance.
$data['programs']= $this->program_management_model->get_program_specific($program_id);
The $data which you are echoing in the controller is basically an array[] and programs is an array which is present in $data. Either echo the $data in controller using the
foreach(){}
or echo the $query array in your model. That will do the trick.And in ajax success call just append the data to the element in which you want to show the result.
Change names as per your page.
in your script:
$.ajax({
url: '<?php echo base_url();?>managealerts_edit/editalerts',
type: "POST",
data: {'id': edit_id},
cache: false,
dataType: "json",
success: function(row){
//alert(row.sub);
$('#edit').show();
$('#sub').val(row.sub);
$('#mess').val(row.mess);
}
});
in your model:
$query = $this->db->query("SELECT fld_id, fld_course_id,fld_sub,fld_mess from tbl_alerts where fld_id='".$det."' ");
if ($query->num_rows() > 0)
{
$row = $query->row_array();
$data=array("sub" => $row['fld_sub'], "mess" => $row['fld_mess']);
echo json_encode($data);
}
in your controller:
$det = $this->input->post('id');
//$alertsres['tbl_alerts'] = $this->managealerts_m->select_editalerts($det);
$this->managealerts_m->select_editalerts($det);`
in model
function get_program_specific($program_id){
$temp=array();
$query=$this->db->query("SELECT * FROM programs WHERE program_id='".$program_id."'");
$temp= $query->row_array();
echo $temp['program_name'];
}
in controller change the line
$data['programs']= $this->program_management_model->get_program_specific($program_id);
with
$this->program_management_model->get_program_specific($program_id);
and finally in javascript
alert(row);
please let me know if you face any problem.

Categories

Resources