Calling a JSP script and php script from html form action - php

I have a form on a page that needs to call a php script on my website's server (it's below web root), and it also needs to call an external jsp script hosted on another website's server. I know I can't just put two items into the <form action="..." but I can't figure out a way to get this done. Both scripts need to receive the variables submitted by the form.
Edit: I've made a mistake here. I'm sorry, but I thought it was javascript, and it's actually JSP. I've modified my post to fix all the places where I mentioned javascript.

you don't post to a "javascript file". javascript needs to be hosted in html. So I don't know if you need to INCLUDE the js file in your html file, and call a function, or if you actually meant post to another hmtl file on another server.
to specifically answer, you can make 2 forms and submit each one of them.
with jquery you can create a form dynamically and submit it. use post as the method, not get.
$('<form>', {
"id": "getInvoiceImage",
"html": '<input type="text" id="componentInvoicId" name="componentInvoicId" value="' + componentInvoiceId + '" />',
"action": window.siteRoot + 'ComponentInvoice/GetInvoiceImage/'
}).appendTo(document.body).submit();

you can add onclick event handler to the submit button, and include there all the javascript you need to perform before submission.
hope that helps.
UPDATE:
after you modified your question i realise you want to post to 2 server endpoints from the same client / webpage at the same time.
in this case i suggest you to:
not using a <form>
include jQuery
as following:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function(){
$('#btnSubmit').click(function(){
// set urls
var url1 = 'http://php.url.com',
url2 = 'http://jsp.url.com';
// prepare data
var data = {
'field1' : 'val1',
'field2' : 2
}
// prepare callback (one callback for both requests)
var callback = function(data) {
console.log('request ended with data: ' + data);
}
// send post requests to both servers with the same data payload
$.post(url1, data, callback);
$.post(url2, data, callback);
});
});
</script>
<input type="button" id="btnSubmit" value="Submit" />
with this approach, click on button will send 2 async post requests, one to each server endpoint you set.
hope that helps.

Related

Stop form from refreshing on submit

I've got this problem that the form refreshes on submit, i dont want it to refresh but i do want it to submit. any of you know what i could do ?
click this link to an older post about this.
<form method="post" id="radioForm">
<?
foreach($result as $radio):
printf('
<button type="submit"
href="#radio"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
endforeach;
?>
</form>
<script type="text/javascript">
$('#radioForm').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
});
});
</script>
</div>
Use submit() handler and pass the value of your button to your other script
First set the id on the form.
<form method="post" id="formId">
Then bind a listener
$( "#formId" ).submit(function( event ) {
event.preventDefault();
//This is where you put code to take the value of the radio button and pass it to your player.
});
To use this you need jQuery.
You can read more about this handler here: http://api.jquery.com/submit/
This is the default behavior of a HTML <form> on submit, it makes the browser POST data to the target location specified in the action attribute and loads the result of that processing to the user.
If you want to submit the form and POST the values behind the scenes without reloading the page, you have to disable the default behavior (the form submit) and employ the use of AJAX. This kind of functionality is available readily within various JavaScript libraries, such as a common one called jQuery.
Here is the documentation for jQuery's AJAX functionality http://api.jquery.com/jquery.ajax/
There are lots of tutorials on the interwebs that can introduce you to the basic use of jQuery (Including the library into your HTML pages) and also how to submit a form via AJAX.
You will need to create a PHP file that can pick up the values that are posted as a result of the AJAX requests (such as commit the values to a database). The file will need to return values that can be picked up within your code so that you know if the request was un/successful. Often the values returned are in the format JSON.
There are lots of key words in this answer that can lead you on your way to AJAX discovery. I hope this helps!
use ajax like this of jquery
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
}
});
});

Save text file with PHP using Javascript code

This is the code of a simply button.
<input value="Download" type="button" onclick=" inccount();" />
And here this is what inccount(); does:
function inccount() {
var a = parseInt(document.getElementById("num").value);
document.getElementById("num").value = a + 1;
}
As you can see, this function increments by 1 the number I have on the input field num. I'd like to save this number on my server, but if I call a php script with the <form> tag, the page changes.
I want save the content of count on my server without leaving the current page. Who could I do it?
I wrote this simply PHP script for save the content of the input field (that is called num):
<?php
$file = '/dat/count.txt';
$current = $_GET["num"];
file_put_contents($file, $current);
?>
To update a page without leaving it you need to investigate Ajax. From the linked page:
in the AJAX model, web applications are able to make quick,
incremental updates to the user interface without reloading the entire
browser page.
The Ajax call can be to a PHP script that writes to a text file.
You are Posting the Page to the Server. So, the Page will have changes..
You need to use AJAX request from javascript to the Server.
simply with JQuery
$.ajax(
{
url:'/?num=' + $('#num').val(),
type: 'GET',
success: function(response){
alert('Success');
},
error: function(e1,e2,e3){
alert('Error occured, Could not able to make request.');
}
});

Force download with jquery

I need to make a button, and when I click on it I'll do the same if I had such form:
<form action="myscript.php" method="post">
<input type="hidden" name="items[]" value="..." />
<input type="submit">
</form>
and clicked submit. On the PHP side I use proper headers and make the force download.
The reason why I can't use a form here, because I have a lot of parameters, and it's not that easy to use a form tag in my HTML markup. Moreover, these parameters are dynamically made, so...
But if I use just $.ajax of course It won't work, I'll just get php response in this ajax request, but the browser won't start downloading the file
Any suggestions?
Just redirect to the download page, if it has the correct headers on that page, it wont change what page they're on, just download the file with a prompt.
Simple answer: Don't use GET. Use POST instead!
<script>
var info = ""; // Somewhere for the response to go
var obj = $.post(
raw_url,
{ var1:value1, var2:value2 },
function(data) { info = data; } );
</script>
On the PHP side, you'll receive any array based data AS an array (thus if value2 were a javascript array, you'll receive it in PHP as an array as well.)

Button that runs a php script without changing current page

I have a webpage that generates a table from mysql. I have a button at the beginning of each row. I would like it so if the user decides to press on the button, the contents of that individual row are written to a new table in MySQL.
Currently I am thinking of just having the button be an href to another php script that connects to mysql and inserts the row into a table; however, I think that will redirect my current page.
I would like the button to run the script, without redirecting my current page. That way, the user can continue analyzing the table without having the page have to reload every time.
This is what my current table looks like. This is just a snippet, and the table can be very large (hundreds of rows)
In order to do this client side, there are a couple of ways I can think of off hand to do this:
Javascript
You can include a Javascript library (like the ever popular JQuery library), or code it yourself, but you could implement this as an XMLHTTPRequest, issued from a click handler on the button. Using a library is going to be the easiest way.
An iframe
Create a hidden iframe:
<iframe style="display:none;" name="target"></iframe>
Then just set the target of your tag to be the iframe:
...
Whenever someone clicks on the link, the page will be loaded in the hidden iframe. The user won't see a thing change, but your PHP script will be processed.
Of the two options, I'd recommend the Javascript library unless you can't do that for some reason.
You need to insert a record into mysql table upon click of button without reloading the page.
For accomplishing the above task you need to use AJAX which will send http request to server in background using xmlhttprequest object and thereby updating web page without reloading the web page.
So you will have to create a function in javascript which will send http request to server using xmlhttprequest object and also you need to define server side handler for processing http request sent using ajax.
For implementation details of ajax with php ,please refer the example mentioned in below link
http://www.w3schools.com/php/php_ajax_php.asp
It's easy to do using jQuery:
<script>
$(function(){
$('#your_button_dom_id').click(function(){
$.ajax({
url: 'your_php_script_url',
type: 'POST', // GET or POST
data: 'param1=value1&param2=value2', // will be in $_POST on PHP side
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert("Response is: " + data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error!");
}
});
});
});
</script>
You can read more about AJAX in jQuery here: http://api.jquery.com/jQuery.ajax/
You can use another input tag after your submit button with hidden type.
<input class="ButtonSubmit" type="Submit" name="Submit" id="Submit" value="Submit"/>
</p>
<input type="hidden" name="submitted" id="submitted" value="true" />
after that use in top of your code this
if (isset($_POST['submitted'])) {
// your code is here
}
it's work for me. you can use it in wordpress template as well

Form auto submit ajax not working

I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/

Categories