The problem that I'm facing is that I'm getting an Undefined Index variable while calling Ajax.
I need to post "json" data to the "update.php" page on click of submit button. Basically, I need to capture the values in textbox and send it to the database.
so, I have created a form on the submit button, for which the code is below:
<form action="update.php" method = "post" class="form-inline">
<input type="submit" class="btn btn-info" id = "saveEdits" disabled = "disabled" onclick = "updateVal()" name="saveEdits" value="Update"/>
/form>
This submit button Calls for an UpdateVal function that captures the value on the text-boxes shown on the page and using AJAX send it to the another php page.
updateVal function is as below:
function updateVal() {
var node_list = document.getElementsByTagName('input');
var c = 0;
var fieldName = [];
var fieldText = []
var ID = [];
for (var i = 0; i < node_list.length; i++) {
var node = node_list[i];
if (node.getAttribute('type') == 'text') {
fieldName[c] = node.name;
fieldText[c] = node.value;
ID[c] = node.id;
c++;
}
}
var postData = {
fieldName: fieldName,
fieldText: fieldText,
ID: ID
};
$.ajax({
type: "post",
url: "update.php",
dataType: "json",
data: {'postData' : JSON.stringify(postData)},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
});
The run time data i.e value in textboxes is being captured and can be shown at console, however, when I'm posting this data on update.php, where I would be capturing the json and will update the database, I'm getting the error:
Notice: Undefined index: in update.php on line 11
Below is my update.php
<?php
$json = $_POST["postData"];
$result = json_decode($json);
var_dump($result);?>
Remove your action attribute from your form, since you send your data per Javascript/AJAX you don't need it.
What you do now is: you send the data twice, once per updateVal() and once per default submit handling of the form.
Since the form-submitted data doesn't contain a input named postData, you are getting your undefined index error.
Edit:
You stated you are not comfortable with the whole AJAX topic. Here is a nice simple answer covering the basics.
Edit2:
to listen for the response of your server add a callback to your ajax-request:
$.ajax({
type: "post",
url: "update.php",
dataType: "json",
data: {'postData' : postData},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
}).done(function (response, textStatus, jqXHR){
// Show an alert on response
alert(response);
});
Related
I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);
I need some help. I am trying to send multiply array of width and length to php, straight forward. I don't want to save it to any HTML field, however it's not working. I am getting the width and length from html text are and convert it to a number and then add it to an array in javascript.
Here is the code for that
var widthL = [];
var lengthL = [];
var widths = document.wall.width.value;
var lengths = document.wall.length.value;
var wNumber = Number(widths);
var lNumber = Number(lengths);
widthL.push(JSON.stringify(wNumber));
lengthL.push(JSON.stringify(lNumber));
This is the Ajax code I am using to send it to PHP
$.ajax( {
type: "POST",
url: "./Summary.php",
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
In PHP I am using this code to receive it. But I am not getting things back.
<?php
$lengths = json_decode($_POST['lengths']);
$widths = json_decode($_POST['widths']);
echo 'This is the width: '.$widtsL;
echo 'This is the length: '.$lengths;
?>
I was hopping that someone could help me out here.
First you should specify the content type in the ajax POST:
$.ajax( {
type: "POST",
url: "./Summary.php",
contentType: "application/json; charset=UTF-8", // Add content type
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
then in PHP:
$request_body = file_get_contents('php://input'); //This reads the raw POST data
$json = json_decode($request_body); // Then parse it to JSON
$lengths = $json->lengths;
$widths = $json->widths;
please add a POST parameter name as dataType,type it value JSON,
the Ajax data param value use key=value&key=value format
then in php file enter debug code
I've got this variable $type and I want it to be month or year.
It should be changed by pressing a div.
I've tried creating an onclick event with an ajax call.
The ajax call and the variable are in the same script (index.php)
Inside the onclick function:
var curr_class = $(this).attr('class');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
But the alert returns the whole html page.
When I console.log the data (create a var data = { type:curr_class }) and console.log *that data* it returnstype = month` (which is correct)
while I just want it to return month or year
So on top of the page I can call
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
}
and change the PHP variable so I can use it in the rest of my script.
But how can I accomplish this?
With kind regards,
as you are sending request to the same page so as a result full page is return .You will have to send it to another page and from that page return the type variable
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
echo $type;
keep this code in separate file and make an ajax call to that page
//Try This It's Work
Get Value
Get Value
$(".btn-my").click(function(){
var curr_class = $(this).data('title');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
});
I am having a form which gets value from the user and stores it to the database.
On submitting the form ,it calls the action.php file using ajax call.
e.preventDefault();
$.ajax({
type: "POST",
url: "action.php",
data: senData,
dataType: "JSON",
success: function(data) {
$("#name").val("");
$('.msg').fadeIn(500);
$('.msg').text("" + data.result + "");
}
});
The values are stored in the database without any errors, but I want to display a notification to the user after submitting the form inside the msg div.
In my action.php file I have added a JSON Encode statement to return a message too.
$msg = 'Thanks Yo Yo';
echo json_encode(array("result" => $msg));
But it is not working i.e, when I submit the form, it stores the data to the database and the webpage refreshes itself without displaying any message inside the .msg div.
Am I doing something wrong and is there a better way to do it??
You need to parse the JSON when it is returned to your javascript.
// Parse the response to JSON
var res = JSON.Parse(data);
$('.msg').text(res.result);
Your code should look like this.
e.preventDefault();
$.ajax({
type: "POST",
url: "action.php",
data: senData,
dataType: "JSON",
success: function(data) {
var res = JSON.Parse(data);
$("#name").val("");
$('.msg').fadeIn(500).text(res.result);
}
});
I have some FormData that are going to be sent into another PHP file using Ajax Post.
var formElement = document.getElementById("form-id");
var form_data = new FormData(formElement);
var csrf_arr = csrf.split("=");
form_data.append(csrf_arr[0],csrf_arr[1]);
$.ajax({
type: "POST",
url: "your-url",
data: form_data,
processData: false,
contentType: false,
dataType: "json",
success: function(data) {
alert(data.message);
},
complete: function(data) {
location.reload();
}
})
What I'm trying to do here is to append a new single data inside the form_data
From my assumption, I could make it just by doing this
form_data.append("key","value");
But it is not sent through the ajax post or even not appended to the form_data as part of the FormData.
Am I making any mistake here or even there is certain rule for that?
Please give any help.
Thanks in advance!
Dear all of my friend,
I'm sorry. Actually it is just a mistake from myself.
I have fix this myself and found the mistake right inside my code.
-- The javascript code --
$( '#submitYours' ).on('click', function(){
var formElement = document.getElementById("form-id");
// Value of formElement consist of pair of data like:
// qst_additional_name_for_the_key=value_of_the_key
var form_data = new FormData(formElement);
form_data.append('break','break');
// to prevent confusion, i'm putting the csrf variable value here
// but i'm not using this as printed variable later, just for security check
var csrf = "your_csrf_token_name=bb6ff34c26ff938822dd339c1682bbcc";
var csrf_arr = csrf.split("=");
var x = 0;
for(x = 0; x < elementId.length; x++){
form_data.append(elementId[x], elementVal[x]);
// Appended data above is just an additional data from some array of data
// and the format is the same with formElement
// qst_additional_name_for_the_key=value_of_the_key
}
form_data.append("master_id",master_id);
form_data.append(csrf_arr[0],csrf_arr[1]);
addLoader("overlay-loader");
runInAnimate("overlay-loader", "bounceInUp");
$.ajax({
type: "POST",
url: "url.php",
data: form_data,
processData: false,
contentType: false,
dataType: "json",
success: function(data) {
alert(data.message);
},
complete: function(data) {
runOutAnimate("overlay-loader", "overlay-loader", "bounceOutDown");
location.reload();
}
})
});
-- The url.php code --
$temp = '';
$arr_in = '';
foreach($_POST as $key => $value){
if(!#$value) continue;
if(substr($key, 0, 4) == 'qst_'){ // This is the real problem.
// The only data taken from the form_data
// are the data containing string "qst_" in it
if(is_array(#$value)){
foreach(#$value as $val){
$this->yourmodel->saveAnswer(substr($key, 4), strtolower(trim(#$val)));
$temp = #$_POST[$key];
$arr_in .= #$temp;
}
}else{
$this->yourmodel->saveAnswer(substr($key, 4), strtolower(trim(#$value)));
$temp = #$_POST[$key];
$arr_in .= #$temp;
}
}else if($key == 'break'){ // remember my additional data? The string "break"
// i just have to chek it here and put into my $arr_in variable,
// so that I can use it now, because the previous conditional allow
// only data containing string "qst_"
$temp = #$_POST[$key];
$arr_in .= #$temp;
}
}
print json_encode(array('status' => 'success', 'message' => #$arr_in));
The conclusion is, nothing wrong if we just append the form_data manually
form_data.append('your_key','your_value');
Everything just the matter of how you access the data after it sent to another file.
My Mistake, everyone!
I'm sorry and thanks a lot for your help. :)