getting undefined index error in php - javascript

I just want receive the array and print it which is sent by jquery.post()
my HTML-JS
<input type="submit" id="myButton" />
<script type="text/javascript">
var arr = new Array();
arr[0] = "Ding";
arr[1] = "Dong";
arr[2] = "Bong";
var json_string= JSON.stringify(arr); // convert it into a json string.
//and sending the data to server. temp.php.
$("#myButton").click(function(){
$.post('temp.php' , {json : json_string },function(data){
location.href = "temp.php";
});
});
</script>
I have checked by alert() that data sending is successful. After button click page is also redirecting to temp.php
My php page temp.php
<?php
$json_string = $_POST['json']; //geting the post request. //this is line 3
$array_items = json_decode($json_string); //converting json string to a php array.
echo $array_items[0]; //just to print 1st element of array
?>
It should print Ding. But I am getting error
Undefined index: json in C:\wamp\www\phpJSarray\temp.php on line 3
What is my mistake in temp.php page ? Please help me out.

call this javascript on your onclick or on form submit however u like.
var arr = new Array();
arr[0] = "Ding";
arr[1] = "Dong";
arr[2] = "Bong";
var json_string = JSON.stringify(arr); // convert it into a json string.
$("#data").val(json_string);
$("#form1").submit(); //and sending the data to server. temp.php.
HTML:
<form action="temp.php" id="form1" method="POST">
<input type="hidden" id="data" name="data">
</form>
temp.php
$dataArray = json_decode($_POST['data']);

The $.post is doing an AJAX call on the current page... which has no apparent effect because once it finishes, the location.href = "temp.php"; is redirecting you to temp.php.
If you'd like to make a POST to temp.php, you could just do it through a normal form. Use jQuery to set the value of a hidden input element to json_string if desired (or better, let jQuery change the form data to JSON).

<script>
$(document).ready(function() {
$("#myButton").on( 'click', function () {
$.ajax({
type: 'post',
url: 'temp.php',
data: {
arr1: "Ding",
arr2: "Dong",
arr3: "Bong",
},
success: function( data ) {
console.log( data );
}
});
});
});
</script>
You'd then call it by doing $_POST['arr1'];. I hope this solves your problem.

After you send your data via AJAX to temp.php and it returns a successful response, redirect to temp.php with an empty POST happens. Thats why you get no data after redirect.
You should also check whether array element exists in temp.php:
<?php
if (isset($_POST['json'])) {
$json_string = $_POST['json'];
$array_items = json_decode($json_string);
echo $array_items[0];
}
?>

Related

Ajax POST request from JS to PHP does not work correctly

The idea of ​​the code I'm trying to run is this: When a $ _GET [] request arrives on the products.php page, I pass it via an ajax POST request to the get_data_products.php page and get data from there.
PHP
if(isset($_GET['cat'])){
$filter_cat = $_GET['cat'];
echo '<input type="hidden" value="'.$filter_cat.'" class="getcat" />';
}
JS
function filter_data2() {
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var filter = [];
var category = $('.getcat').val();
filter.push(category);
$.ajax({
url:"<?php echo $g['url']; ?>get_date_products.php",
method:"POST",
data:{action:action,category:filter},
success:function(data){
$('.filter_data').html(data);
}
});
}
The problem is: When I get for example $_GET['category'] = 2 and ajax sends the data to get_data_products.php and then selects another category and $_GET['category'] = 12 sometimes it is not sent.
When I give var_dump ($_GET['category']) it always contains the correct value, but for some reason ajax does not send it.
I can see a typo here url:"get_date_products.php" doesn't it supposed to be data?

How can get data from html form and javascript array using PHP and AJAX

I'm sending a HTML form and javascript array using AJAX post method. But I can't get my data in the PHP file.
$.post("addOrder.php", {
"form": $("#placeOrderForm").serialize(),
"array": array
}, function(responce) {});
Please read the docs clearly.
The update code:
$.post("addOrder.php",
$("#placeOrderForm").serialize(),
function(response) {
}
);
And in addOrder.php, print the posted array using.
echo '<pre>';print_r($_POST);echo '</pre>';
If you are using firebug, you will get the posted variables' array in response tab.
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$var = isset($_POST['var']) ? $_POST['var'] : null;
Can you try something like below:
var request = $.ajax({
url: "addOrder.php",
type: "POST",
data: {<data1> : <val1>},
dataType: "html"
});
request.done(function(msg) {
$("#log").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Looks like you passing argument is having issue.
In addForm.php try this:
var_dump($_POST)
This will enable you to inspect the form data posted.
Try something like this in your php file:
$params = array();
echo parse_str($_POST, $params);
Thanks everyone. I found my answer. I used "serializeArray" for sending form.
html
<form id="placeOrderForm">
<input name="po">
<input name="desc">
</form>
javascript
var array = [1,2];
$.post("addOrder.php",{
"form":$("#placeOrderForm").serializeArray(),
"array":array
}, function (responce) {});
php
$form_input_data_1 = $_POST['form'][0]['value']; // get po's data
$form_input_data_2 = $_POST['form'][1]['value']; // get desc's data
$array_index_1_data = $_POST['array'][0]; // get 1
$array_index_2_data = $_POST['array'][1]; // get 2

Using Ajax and JSON to display PHP echo message in HTML

Ive been trying to connect my PHP file to my HTML file using Javascript/jQuery and json. When the user inputs a number into the input box in the form and submits it, the PHP file should multiply the number by two and send it back to the user.
However when I press the submit button it takes me to the php page instead of displaying the information (processed in the php file) in HTML.
This is my HTML form:
<div id="formdiv">
<form action="phpfile.php" method="get" name="form1" id="form1" class="js-php">
Mata in ett nummer: <input id="fill1" name="fill1" type="text" />
<input type="submit" id="submit1" name="submit1" value="submit">
</form>
This is my Javascript file
$(".js-php").submit(function(e){
var data = {
"fill1"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
$("#formdiv").append("Your input: "+data)
alert (data);
}
})
e.preventDefault();
});
PHP file:
$kvantitet = $_GET['fill1'];
$y = 2;
$work = $kvantitet * $y;
$bork = $work * $kvantitet;
echo json_encode($work) ."<br>";
echo json_encode($bork);
There are a few things you could do a bit differently here to make this work:
Currently, using both .serialize and $.param your data variable contains something like this:
someurl.php?fill1=1&0=f&1=i&2=l&3=l&4=1&5=%3D&6=1
If you use only .serialize you will get something easier to work with:
?fill1=5
On the PHP side, currently your code outputs something like this:
4<br>8
By adding your values to an array you can get a response back that you can work with:
$result = array();
$kvantitet = $_GET['fill1']; // Lets say this is 5
$y = 2;
$work = $kvantitet * $y;
$bork = $work * $kvantitet;
//add the values to the $result array
$result = array(
"work" => $work,
"bork" => $bork
);
echo json_encode($result);
Which will output:
{"work":4,"bork":8}
Back on the JS side you can then handle the data in your success callback:
$(".js-php").submit(function(e){
data = $(this).serialize();
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
// *data* is an object - {"work":4,"bork":8}
$("#formdiv").append("Your input: "+data)
console(data);
}
});
// Use return false to prevent default form submission
return false;
});
One way to access the properties in your object is by using dot notation:
data.work //Outputs 4
data.bork //Outputs 8
But here is a really great answer on processing / accessing objects and arrays using JavaScript.
Here is a Fiddle containing your (working) jQuery
You are expecting JSON Data but what you send back is not JSON
Try output the following in your PHP File:
$data['work'] = $work;
$data['bork'] = $bork;
echo json_encode( (object)$data );
Use console.log to inspect incoming data on the AJAX call then handle it according to how you want.
I think you need &
data = $(this).serialize()+'&'+$.param(data);
and as #leonardo_palma mentioned in comments maybe you need to use e.preventDefault(); in the beginning of submit function
and I prefer to use
$(document).on('submit','.js-php',function(){/*code here*/});

Display a session var without refresh the page

I set a session var in an ajax file like that :$_SESSION['id_essai']=$ligne[1];. The value of this var should change at each submit of the form.
Without recharge the page, I want to get the value of this var. So I echo it like that : echo $_SESSION['id_essai'];
My problem is, when I try to echo it, I get the previous value until I recharge the page. I want to refresh this var without recharge the page. How can I do that ?
EDIT :
I send a handsontable grid to my ajax file like that :
$(document).ready(function(){
$('#submit_button_essai').click(function(){
$.post("ajax_insert_essai.php",{arr:data_essai}, insert_essai_callback,'json');
return session;
});
});
In this ajax file, I declare my session var with one value of this grid and I can return it like that :
array_unshift($tab_erreur,$_SESSION['id_essai']);
echo json_encode($tab_erreur);
So I send an array of errors AND the session var that I process like that in my callback function:
function insert_essai_callback(responseObject,ioArgs) //ajax renvoie les indices des cases erronnées et les messages correspondants.
{
var jsonobject = eval(responseObject);
console.log(jsonobject);
//alert(jsonobject[0]);
var session = jsonobject[0];
for(var item in jsonobject)
{
if((item % 2 ) == 0) //Si l'indice est pair, on affiche la couleur
{
$("td").eq(jsonobject[item-1]).after("<div class=\"message\">"+jsonobject[item]+"</div>");
}else //Si l'indice est impair, on affiche le message
{
$("td").eq(jsonobject[item]).css("background-color","red");
}
}
}
My session var is in jsonobject[0].
That's my code after trying to return the session var in ajax.
I think the problem is that every reuqest will start a new session on the server.
<?php
session_start();
// Restart the last session if a session-id is given
if (isset($_GET['session-id'])
session_id($_GET['session-id']);
/* ... your code here .. */
$response = array('session-id' => session_id());
/* ... add some more values/results to your response */
header('Content-Type: application/json');
die(json_encode($response));
?>
Set up a new PHP file. Then send the value you need to update to the session variable using ajax on a click event or change event or something. When it receives the value , PHP will update the session value. Then return that variable's value in JSON. Tada You got the updated value. I hope you understood..
example code look like this
in ajax (jquery ajax i am using here)
$.ajax({
url : 'session.php',
method : 'POST',
data : your value to update ,
dataType : json,
success : function(data){
alert(data.value);
}
})
In session.php file
<?php
session_start();
$value = $_POST['value'];
$_SESSION['value'] = $value;
$json = array('value' => $_SESSION['value'] );
print_r(json_encode($json));
?>
If you need to get value without refresh , call the ajax function on an event. Then update the returned data in to div or something. I hope this one helps ! :)
create a process.php file and post/get the form there.
<form method = 'post' action = 'process.php'>
<input type = 'hidden' value = 'some_Hidden_Value_that_You_Want' id = 'hidden_id'>
<!--Some other stuff (Grid may be) -->
<input type = 'button' value = 'Submit' id = 'submit_form'>
</form>
$("#hidden_id").click(function(){
var hidden_id = $('#hidden_id').val()
$.ajax({
url: 'process.php',
type: 'POST',
data:{
want_this: hidden_id
},
success: function(posted){
alert(posted);
}
});
});
This will post your stuff to process page.
and on process.php or in your case ajax_insert_essai.php
do this to view what you're getting
<?php
print_r($_POST);
?>
EDIT
in callback
obj = $.parseJSON(jsonobject[0]);
console.log(obj);
// this was to update the page without refreshing the page
// $this = $('#'+obj.ID).find('td');
// $this.eq(2).html(obj.username);
// $this.eq(3).html(obj.password);
//ignore these lines
/*You can access all your stuff then like that*/
condole.log('some id' + obj.id);
//and so on...
If the data that will become the new session variable is sent from the page just have it also use the data already on the page to update to page using JavaScript.
If the data you want to get returned is being sent from the page there is no need to re-get the data because it is already on the page.

Is it possible to assign a php variable to a jquery var and then refresh that jquery variable

Is it possible to assign a php variable to a jQuery variable and then use a function to refresh the jQuery var every 30 seconds?
Also, could you use that variable in a html input?
<input type="text" value="jquery value that will refresh every 30 seconds with PHP variable">
If this is possible how and where can you learn to do this?
Try something like this. Just change backend url. This backend should only output the value.
<input id="input" type="text" value="" />
<script>
setInterval(function(){
$.get( "/value.php", function( data ) {
$('#input').val( data );
});
},30000);
</script>
Your value.php file will look something like
<?php
$value = 1;
echo $value;
exit;
If you need to return more values then one, you can use JSON, then
<input id="input" type="text" value="" />
<script>
setInterval(function(){
$.get( "/value.php", function( data ) {
$('#input').val( data.first_value );
}, "json");
},30000);
</script>
Your value.php file will look something like
<?php
$first_value = 1;
$second_value = "Some string";
echo json_encode(array(
'first_value' => $first_value,
'second_value' => $second_value
));
exit;
This script only sends data to fiddle servers which in turn send it back. It then update the value of the input.
It's just a little example but it might help you to get the idea:
var data_sent = 1;
setInterval(function () {// Set interval to retrieve info every 1s.
$.ajax({
url: "/echo/json/",// URL provided by jsfiddle to try AJAX. It just echoes back.
type: 'POST',// jsfiddle imposes that you use POST for that url.
data: {
json: JSON.stringify(data_sent)// Send data, it'll be echoed by jsfiddle script, the format is also imposed by jsfiddle.
},
success: function (data) {
$("#myInput").val(data);// Put the data received in the input
data_sent += 1;// change the data so that you send new one to the server next time.
}
})
}, 1000);

Categories

Resources