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.)
Related
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.
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¶m2=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
I use Facebook JavaScript SDK.
I want to know how to post the Javascript variables to another page with GET or POST or any other way.
For example i have:
userInfo = document.getElementById('user-info');
How to post it to new page ?
location.href="http://www.walla.com/?info=" + info.id;
Not working
Better use ajax for this ..
here is an example.
<script type="text/javascript">
$(document).ready(function() {
$('#submit-btn').click(function() {
$.ajax({
type:'POST', //POST or GET depending if you want to use _GET or _POST in php
url:'your-page.php', //Effectively the form action, where it goes to.
data:$('#txtName').val(), //The data to send to the page (Also look up form serialise)
success:function(e) {
// On success this fill fire, depends on the return you will use in your page.
}
});
return false;
});
});
</script>
<form>
<input type="text" id="txtName" />
<input type="submit" id="submit-btn" value="Send" />
</form>
Hope it works for u.
That looks okay. You should be able to obtain info.id via $_GET['info'] from PHP.
However, that's assuming userInfo is a simple string.
If it isn't, you may have to convert it to string first. One way to do that is through JSON as JSON is decodable at PHP's side using json_decode().
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/
i am using the following jquery to post comments to user_submit.php
var submit = document.getElementById("submit_js");
var comment = document.getElementById("comment");
$("#submit").bind('click', function(){
$.post("user_submit.php", {
comment: $("#comment").text()
});
});
the user_submit.php listens like:
$comment = htmlspecialchars($_POST["comment"]);
i can see in the Firebug console that there is no POST happening. only a single GET that i use for a different function (can this be the culprit?)
Assuming:
<input type="text" id="comment">
<input type="button" id="submit_js">
you want:
$(function() {
$("#submit_js").click(function() {
$.post("user_submit.php", {
comment: $("#comment").val()
});
});
});
PHP:
<?php
$comment = $_POST['comment'];
//...
echo htmlspecialchars($comment); // nothing catches this currently
?>
You also seem to be confusing "submit" and "submit_js" in your code. I'd advise against mixing Javascript and jQuery code unnecessarily too (the "getElementById()" business). You should familiarize yourself with jQuery selectors. For example:
$("#submit_js")
will create a jQuery object with all the elements (which should only be zero or one elements) with the ID of submit_js.
Remember that you're posting via AJAX, so even if you're echoing back the field value, it won't show on your screen unless you're listening for it in the $.post callback.
To check what the problem may be, submit the form normally without jQuery. If your PHP script is echoing back the field value, then the PHP script is working - check your JavaScript. If the you're getting blank, or empty array when using print_r(), then make sure the field name in your form is the same as what you're using in the PHP script.
Don't want you to have to rewrite your code, but here's what I recommend to do.
<form class="comments" method="post" action="user_submit.php">
<input type="text" name="comment" />
<input type="submit" value="Submit" />
</form>
JavaScript:
$('.comments').submit(function() {
var $form = $(this);
$.post(
$form.attr('action'),
$form.serialize(),
function(data, status) {
console.log(data);
}
);
return false;
}
This will submit your form to the PHP script. In the callback function, "data" is the returned data from the PHP script. So if you echo the field value back, the Firebug console will display the value.
In the event the user's browser has JavaScript disabled, the form will still submit properly. Of course your PHP script would have to check if the form was submitted via AJAX so that it can process properly depending on the request method. An easy way to test is to check for the X-Requested-With header. If it was sent via AJAX, the value would be XMLHttpRequest.