javascript array in php using Ajax on submit not working - javascript

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.

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

for each ajax post to another file

So i have a for each function that prints the "local" column from this database:
https://i.imgur.com/IzKOzkt.png
It is working all good till here, this is what i get:
https://i.imgur.com/WH7d4uh.png
Now i want to send variables by post, when the user clicks on different menu items, i've tried everything, but i cant get it to work. Here is my code:
<?php
$query = "SELECT * FROM credenciais_sensores where ambiente = '1'";
$results = mysqli_query($conn, $query);
foreach ($results as $result){
$local = $result['local'];
$local = substr($local,0,7);
echo "<li><a class='clsPostData' data-oxiid='".$result['oxi_sensorid']."' data-oxikey='".$result['oxi_apikey']."' data-redoxid='".$result['redox_sensorid']."' data-redoxkey='".$result['redox_apikey']."' href='#'>".$local."</a></li>";
}
?>
This is working fine, the menu is being printed as i want, but now i cant get to post the data i want, like the "oxi_sensorid", etc... Here is my javascript:
<script type="text/javascript">
$(function(){
$('.clsPostData').click(function(e){
e.preventDefault();
var objPost = {};
objPost.oxiid = $(this).data('oxiid');
objPost.oxikey = $(this).data('oxikey');
objPost.redoxid = $(this).data('redoxid');
objPost.redoxkey = $(this).data('redoxkey');
$.ajax({
url: 'getObjects.php',
type: 'post',
data: objPost
}).done(function(responseFromPhp){
//Do something with the response, like
alert(responseFromPhp.message);
});
});
});
</script>
And my getObjects.php file:
<?php
$oxiid = $_POST["oxiid"];
$oxikey = $_POST["oxikey"];
$redoxid = $_POST["redoxid"];
$redoxkey = $_POST["redoxkey"];
$response["message"] = "Grettings from php, we receive your data: ".$oxiid . $oxikey . $redoxid . $redoxkey;
echo json_encode($response);
?>
But i'm always getting the popup saying "undefined" when i click on any menu item... Any help?
I think the problem there is you need to set the dataType to json. Try adding dataType: 'json' after type: 'post' on your ajax code:
$.ajax({
url: 'getObjects.php',
type: 'post',
dataType: 'json', // add this
data: objPost
}).done(function(responseFromPhp){
//Do something with the response, like
alert(responseFromPhp.message);
});

PHP echoing into JavaScript value "0" even when value is not "0" after POSTing with AJAX

I have button that is using AJAX post method to post value into PHP.
When I echo that value back in JavaScript it's always echoing 0, even when I am 100% sure that value in PHP is not 0.
Here is JavaScript:
function slanje(br){
$.ajax({
type: 'POST',
dataType: 'html',
data: {
'broj' : br,
}
});
}
function otvaranje(id, broj){
slanje(broj);
var testNumber = <?php echo $br; ?> + "";
And PHP (I do file write to check if PHP received correct value):
if(isset($_POST['broj'])){
$br = $_POST['broj'];
$file = fopen($br . "broj.txt", "w");
fclose($file);
}
Here is what value I get back in Javascript:
And here is value in PHP:
Edit 2: I want to post variable in PHP, than get value of element of PHP array with index I passed with ajax. And that without reloading page. I didn't include array part because while I was testing around I couldn't even make it echo back variable I'm passing using AJAX.
If you want to do it using AJAX, then let your PHP script return the POSTed value and grab it in the success handler of the AJAX request.
For the success handler to be able to change the value of testNumber, the variable has to be declared outside of function otvaranje.
Here are the necessary modifications (also take note of the comments I added):
PHP
if(isset($_POST['broj'])){
$br = $_POST['broj'];
$file = fopen($br . "broj.txt", "w");
fclose($file);
// Just output the value and exit
// If there is business logic doing something with
// $br, then move this after that code.
// But remember to only do this if the script was
// called with POST, otherwise the initial request
// wouldn't work anymore.
print $br;
exit;
}
JavaScript
var testNumber = "<?php echo $br; ?>";
function slanje(br){
$.ajax({
type: 'POST',
dataType: 'html',
data: {
'broj' : br,
},
success: function(data) {
// called when the request succeeded
testNumber = data;
}
});
}
function otvaranje(id, broj){
slanje(broj);
// move outside: var testNumber = <?php echo $br; ?> + "";
// rest of function content
}

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

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