Not able to access form element on another page in jsp - javascript

I simply pass data when user click submit button to retrivedata.jsp page.
But when i try to recive that data it will showing null why??
----> Here are my ajax call
$(document).on("click","#submit",function(){
console.log(validproductname,validproductprice,validdescription,validimage);
if(validproductname&&validproductprice&&validdescription&&validimage)
{
var send_data=new FormData();
send_data.append("pagename","index");
send_data.append("action","insert");
send_data.append("productname",productname.value);
send_data.append("productprice",productprice.value);
send_data.append("productdescription",productdescription.value);
send_data.append("productcategory",productcategory.value);
console.log(send_data);
//append all send_data of pagename
send_data.append("file",$("#product_image")[0].files[0]);
$.ajax({
url:"retrivedata.jsp",
type:"POST",
data:send_data,
processData: false,
contentType: false
,success:function(data)
{
load_data();
}
});
}
else
{
console.log("Invalid Details");
}
});
});
This is sample of data which pass through network.
And i am trying to access that data with following code but it will give me null
<%
String Pagename=request.getParameter("pagename");
String Action=request.getParameter("action");
String res="";
System.out.println(Pagename); //output is null
System.out.println(Action); //output is null
%>
I sent data which is not accessbile in jsp page why???
I am expecting that i need to retrive data in retrivedata.jsp page

Related

Send Ajax post request and retrieve the inserted id

I am trying to submit a form which will insert data into a mysql database which is working fine. I then would like to return the id of the new inserted row (id auto increment in mysql table) as I want to open up a modal once the form is submitted so I can provide a link which includes id as a parameter in the url.
To send the data for the form I am using the following code:
$(document).ready(function(){
$("#submitForm").click(function(){
var string = $('#commentForm').serialize();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "SubmitData.php",
data: string,
cache: false,
success: function(result){
//alert(result);
}
});
});
});
The SubmitData.php file then inserts the form data into the database.
In the SubmitData.php I can create a variable to pick up the id of the newly inserted row like
$last_id = mysqli_insert_id($conn);
Is there a way I can return the $last_id from the SubmitData.php file within the same function?
Yes return from SubmitData.php the id using the following echo:
echo json_encode(['id'=>$last_id]);
js:
$(document).ready(function(){
$("#submitForm").click(function(){
var string = $('#commentForm').serialize();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "SubmitData.php",
data: string,
cache: false,
success: function(result){
alert(result.id);//this will alert you the last_id
}
});
});
});
print last id in that php file
echo $last_id;
get that in ajax success function
success: function(result){
alert(result);
}

Ajax form reloading page instead of working in the background

Firstly, based on other suggestions, I've tried moving around the preventDefault() but haven't had success.
My feedback form uses this JavaScript to pass form fields to "process.php" and return with the relevant messages (ie: "sucesss" or "fail")
It's doing its job except that instead of staying on the same page 'feedback.php' it loads 'process.php' page with this ... {"Data":"Data Value"}
Heres the code:
$(document).ready(
function(){
$('form').submit(
function(event){
var formData =
{
'name' : $('input[name=name]').val(),
'page' : $('input[name=page]').val()
};
$('.form-group').removeClass('has-error'); // remove the error class
$('.error').remove(); // remove the error text
event.preventDefault();
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
.done(function(data){
if ( ! data.success)
{
if (data.errors.name)
{
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#nameField').append(data.errors.name); // add the actual error name under our input
}
}
else
{
$('form').append('<div class="buttonError">Message Sent!</div>');
form.myButton.disabled = true;
}
}
);
.fail(function(data){
$('form').append('<div class="buttonError">Failed!</div>');
}
console.log(data);
);
event.preventDefault();
}
);
});
looks like syntax error calling $.ajax, it should be corrected like this:
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
}).done(function(data){
if ( ! data.success)
{
if (data.errors.name)
{
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#nameField').append(data.errors.name); // add the actual error name under our input
}
}
else
{
$('form').append('<div class="buttonError">Message Sent!</div>');
form.myButton.disabled = true;
}
}).fail(function(data){
$('form').append('<div class="buttonError">Failed!</div>');
console.log(data);
});
Remove the method and action in the form tag in your HTML file. This looks fine. Let me know if it doesn't work.

how to pass a json object from html form submit

I have a logging page and I wanted to send the logging details in json format to the checkuser.php file which is a other page in the web site.
checkUser.php file will create a new window.
What is the best way to do this ? if possible please give me some example.
$("#myform").submit(function( e ) {
e.preventDefault();
$.ajax({
url: "blabla.com/api",
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( { key: val } ) // <-------- HERE IS YOUR JSON
}).done(function() {
console.log('hooray!');
});
});
Suppose you have a login form as login.php with html form controls txtLogin and txtPassword and a Submit button. Once the user submits the form it would post data onto checkuser.php
You can write the following code that can push data in JSON format
$login = $_POST['txtLogin'];
$password = $_POST['txtPassword'];
$userArray = array('login'=>$login,'password'=>$password);
$json_array = json_encode($userArray);

Passing array with Ajax to PHP script results in empty post

I want to pass an array from a HTML site to a PHP script using AJAX
JS
function selectPictures() {
//selected Pictures is my JS array
var jsonArray = JSON.stringify(selectedPictures);
var request;
request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {
data: jsonArray
},
cache: false
success: function () {
alert('OK');
}
});
}
HTML
href="selectedPictures.php" onclick="selectPictures();"
PHP
if (isset($_POST['data'])) {
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d) {
echo $d;
}
}
Actually I want to send the data to another HTML page and then include the PHP script, but I don't understand why this example does not even work. The $_POST['data'] is not set.
UPDATE
Ok, the Ajax post is actually working, as I see the HTTP request is successful BUT: I cannot access the variable instantly. I need to access the values of the passed array at once to execute another PHP script. When I want to do this, I get an undefined index error. Also at the time when the isset function is executed, it returns false (despite the successful HTTP request).
HTML
click
JS
$(function(){
$('#selectPictures').click(function(){
var jsonArray = JSON.stringify(selectedPictures);
var request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {data: jsonArray},
cache: false,
success: function(data){alert(data);}
});
});
});
Use f12 in chrome to see errors, you forgot to add a comma after the "cache: false"

Send data fetch from array from page to other page by jquery

i have 2 pages, one that send data from form and send data to second page.
the first page is html, and the second is php.
So, my problem is i send data from form to the second page to enter to SQL statement, and i get data from fetch array, how can i send data from second page to first page and put it in div.
my JS that i will send
// This function to search aqar
function search_aqar(){
var city = $('#city').val();
var aqar_type = $('#aqar_type').val();
var adv_type = $('#adv_type').val();
var search_btn = $('#search_btn').val();
var show_type = $('#show_type').val();
if (city!='' && aqar_type !='' && adv_type !=''){
$.ajax({
url: "request.php?do=search_aqar",
type: "POST",
data: {
city : city,
aqar_type : aqar_type,
adv_type : adv_type,
show_type : show_type,
search_btn : search_btn
},
dataType: "json",
success: function(data){
if(data.process == "ok"){
}
else
{
}
}
});
}
else
{
}
}
and i get data to page name request.php and put variable to sql statement, i need send data to first page on div
Just put a div in your html file like this:
<div id="msg"></div>
And change this:
success: function(data){
if(data.process == "ok"){
}
To this:
success: function(data){
$('#msg').html(data);
}
you may need to return the data as an json_encoded array from your php script and then use
success: function(data){
var variable = jQuery.parseJSON(data);
$("#yourdiv").html(variable['your_array_identifier']);
}
if you are not sending back an array and just a single item then you don't need to return an array and just simply use
success: function(data){
$("#yourdiv").html(data);
}

Categories

Resources