Send variable from Javascript to PHP using AJAX post method - javascript

I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!

From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)

Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.

you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,

Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});

you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

codeigniter or PHP - how to go to a URL after a specific AJAX POST submission

I am successfully inserting data into my database in codeigniter via a an ajax post from javascript:
//JAVASCRIPT:
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
$('body').append(data); //MH - want to avoid this
}
});
//PHP:
public function respond(){
$this->load->model('scenarios_model');
$responseID = $this->scenarios_model->insert_response();
//redirect('/pages/view/name/$responseID') //MH - not working, so I have to do this
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
echo "<script>window.location = '$redirectURL'</script>";
}
But the problem is that I can't get codeigniter's redirect function to work, nor can I get PHP's header location method to work, as mentioned here:
Redirect to specified URL on PHP script completion?
either - I'm guessing this is because the headers are already sent? So as you can see, in order to get this to work, I have to echo out a script tag and dynamically insert it into the DOM, which seems janky. How do I do this properly?
Maybe you can 'return' the url in respond function and use it in js
PHP :
public function respond(){
// code
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
return json_encode(['url' => $redirectURL]);
}
JS :
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
dataType: 'JSON',
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
window.location = data.url
}
});
you have to concatenate the variable. That's all.
redirect('controller_name/function_name/parameter/'.$redirectURL);

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Javascript passing variable issue not returning

Hi All I have the following code to pass a JS variable using AJAX as seen below:
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
data: { 'id': id },
success: function(msg){
window.alert(msg);
}
});
}
if I put an alert box in I can see the object id is successfully getting grabbed. however if in php I want to simply return the variable - I am getting a null has anyone got any ideas:
heres my PHP function (I am using Codeigniter):
public function passid(){
$courseId = $this->input->post('id');
echo $courseId;
}
EDIT: the success alert box appears - but appears blank and that is my issue I am hoping to see the ID
1. Can you make sure id equals something by doing this:
function buttonCallback(obj){
var id = $(obj).attr('id');
alert( id ); // What does it alert?
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
2. Your javascript looks good... Can you try this instead to see if it works:
JS
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
PHP
public function passid(){
$courseId = $this->input->post('id');
$response = array( "id" => $courseId );
header('Content-Type: application/json');
echo json_encode( $response );
}
3. If this does not work, can you try and rename from id to something like poopoo, just to make sure id is not taken and being weird?
4. Can you check what the network response is of your ajax request - Go to developer toolbar and goto network section, make sure you hit the record/play button. then send your request off. When you see your request come up in the network list, check the "details" of it and goto response.

send multidimensional array to php using ajax as json and receive html text to show in a div

First part is completed, The data is successfully sent to php using ajax as json (I did it by following an answer to an already posted question on this site).
Now how to access these values in php, and after using the string in abc[2] as sql query and printing the result in php(second page) using html in a table format (in second page), how to receive that response after ajax call completes in first page to show it in a div in first page.
Actually I am not asking about the procedure of running query and displaying values.
I am facing problem in accessing these array values in php and displaying them back in first page using ajax.
whenever I return some value from first page (using echo or print function), I receive an alert about syntax error: unexpected tocken after the ajax call comes back from second page. The code in first page is
var abc= {};
abc[0] = {};
abc[0]['name'] = 'first col';
abc[0]['width'] = 123;
abc[1] = {};
abc[1]['name'] = 'second col';
abc[1]['width'] = 456;
abc[2]="abcdefghijklmnopqrstuvwxyz";
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(data)
{
alert(data);
}
});
I don't know exactly...
you can try this one..
$param = cleanAll();
You can do it in this way :
Send parameter to your query.php file using ajax.
In query.php file write logic to process on posted data save/edit/fetch data from/to DB
and create html to print in div and echo that html
Inside your ajax call when success put that html to div which is returned from query.php.
Here are few changes on your ajax code:
Array will like this
var abc= {abc :[{name:'first col',width:123},{name:'second col',width:456},{name:"abcdefghijklmnopqrstuvwxyz",width:456}] };
Ajax will like this
$.ajax(
{
type: "POST",
url: "query.php",
data: abc,
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(my_html)
{
$('#my_div').val(my_html);
}
});
Code is not tested but it should work.
As I understand from my recent experiment, array will be placed to object before converting to JSON. Below my code:
JavaScript:
...
var read_numbers = new Array();
...
function read_ajax_done(num, num_in_word){
rec_count_in_cache = rec_count_in_cache + 1;
var number = {"num" : "", "word" : ""}; // Object type
number.num = num;
number.word = num_in_word;
read_numbers[rec_count_in_cache-1] = number; // Array is multidimensional
}
function save_to_db(read_numbers) {
var object_read_numbers = {"read_numbers" : read_numbers}; // Array placed to object
JSON_read_numbers = JSON.stringify(object_read_numbers); // Object converted to JSON
request = $.ajax({
type : "POST",
url : "post.php",
data : {read_numbers : JSON_read_numbers}
});
request.done(function(msg) {
alert("Respond: "+ msg);
});
request.fail(function(jqXHR, textStatus) {
alert("Function inaccessible: " + textStatus)
});
}
PHP:
if (isset($_POST["read_numbers"])) {
$read_numbers = json_decode($_POST["read_numbers"], TRUE);
.....
$response = $read_numbers["read_numbers"][n]["word"];
}
echo $response;
Second Page PHP
<?php
//need for displaying them back to the $.ajax caller
header('Content-type: application/json');
//accessing data
$post = $_POST['abc'];
/*
* how to access multid array
* $post[0]['name'] = 'first col'
* $post[0]['width'] = 123
* $post[1][name] = 'second col'
* $post[2] = 'abcdefghijklmnopqrstuvwxyz'
*/
//now to pass them back to your $.ajax caller
echo json_encode($post);
?>
First Page
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
success: function(data)
{
//prints your response variable
console.log(data);
}
});

Categories

Resources