This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to get GET and POST variables with JQuery?
I have the following HTML:
<form action='.' method='post'>{% csrf_token %}
<div class="parameters">
Show
<select name="earnings_filter">
<option value="all">Total earnings</option>
<option value="hd">HD earnings</option>
<option value="sd">SD earnings</option>
</select>
<input type="submit" name="submit" class="submit float-right" value="submit" id="submit_financials"/>
</div>
</form>
I need to do an ajax call with this, which I'm triggering on:
$("#submit_financials").live('click', function(){
...
});
Is there a way to get the variables that are submitted in POST, for example which option was selected (and there are about 10 other variables I need to get). Or do I need to use the jQuery selectors to get the value of each?
$("#submit_financials").live('click', function(){
$.ajax({
url: '', // script url to send
method: 'POST', // method of sending
data: $('form').has(this).serialize(), // .serialize() make query string with form inputs name and value
dataType:'json', // expected data format returned from server, you may have something else
success: function(response) {
// response contains data returned from server
}
});
});
It would be better replace live() with .on() if you're using jQuery > 1.7 and it'd be better if possible. So you can write it
$("#container").on('click', '#submit_financials', function(){
$.ajax({
url: '', // script url to send
method: 'POST', // method of sending
data: $('form').has(this).serialize(), // .serialize() make query string with form inputs name and value
dataType:'json', // expected data format returned from server, you may have something else
success: function(response) {
// response contains data returned from server
}
});
});
Here #container point to holder of #submit_financials that belong to DOM at page load.
If all the values are in input elements on the form...
$("#formId").serialize()
You could serialize the form and send to the server page
$.post("yourServerPage.php", $("form").serialize(),function(data){
//Do whatever with the result from ajax server page.
});
How about creating several input values of type hidden
<input type="hidden" id="sample_id" value="SOMETHING" />
give them ids and acces the data inside using:
$('#sample_id').val()
Unfortunately, POST variables are communicated in the request from the client to the server, but they are not automatically included in the response from the server back to the client. This is one of the things that sets them apart from GET variables.
If your data isn't excessively long, you may want to switch to the GET method instead. You can then retrieve the variables using a function like one listed in this question: How can I get query string values in JavaScript?
Alternatively, if you have access to the server-side code, you could include these variables in HTML returned; however this is another question entirely :)
Related
I am trying to pass a string stored in a variable to a mysql table via php.
Currently I am using an <input> with type hidden, I assign the variable that I want as its value and post it through a form submit.
it is working but it's ugly.
I know there is $.post and $.ajax but I don't seem to figure out how to use them in the js side and php side. I have looked for them online and there are a lot of questions of this sort but none of them work for me (probably because I am missing knowledge)
How can I do it?
Here is a very basic example. We start out with a form on an HTML page. When this button is clicked, we are going to activate a javascript function.
<html>
<form>
<input type="email" id="email-field" />
<input id="submitButton" type="submit" value="Submit" />
</form>
</html>
Now, here is the javascript function being activated due to the button click. Inside, we extract any information that might have been filled out in the input field with id of "email-field", then send that off via ajax to a php file that sits on the server.
$('#submitButton').click(function() {
var email = $('#email-field').val();
$.ajax({
type: 'POST',
url: './yourphpfilename.php',
data: {
email: email
}
}).done(function(data) {
console.log(data) // Will send you the result that is echoed in the PHP file
})
})
As long as you put the correct url in your ajax request to your PHP file, you can easily receive the data being sent like so,
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email'];
echo 'I have received your request.';
}
To send the data back, I use the echo command to do so here.
Try to read some documentation on the $_POST variable in PHP. Notice how I call for ['email']. The identifier inside the brackets directly correlates to the key inside the data object in the js file. For example, say we decided to name our email key something different in the js file.
data: {
useremail: email
}
You would then just change the PHP code like so,
$email = $_POST['useremail'];
This was very confusing for me starting out, and sometimes it's hard to even pose a quality question on it if you have no idea how it works. In the future though, I would atleast try to post some code showing that you attempted the problem.
There are several things you need to do:
You have a form tag and you need to prevent it from submitting, like this:
$("#myformid").submit(function(event) {
//Do something
event.preventDefault();
});
If your form is no longer submitted, then you are on the right track.
You need to use $.ajax to send the request, like this:
$("#myformid").submit(function(event) {
//Here I assume that all variables have been properly initialized
$.ajax({
url: "yoururl",
method: "POST",
data: yourdata, //yourdata should contain the things you intend to send to the server
}).done(function(response) {
//callback
});
event.preventDefault();
});
You will need a PHP code which will properly handle the POST request you send at yoururl. This is how you can check in PHP whether the request method was POST:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//It is a POST request
} else {
//It is not a POST request
}
I'm fairly new to the jQuery execute on the same page stuff. So far I have been passing only single values trough ajax which is working fine. Now, I need to pass an array which is created by checkboxes through ajax.
My form html, dynamically created by php:
<input type=checkbox class=box name=box[] value=".$row['DoosID']." />
My jQuery:
var BackorderDate = $("#BackorderDate").val();
var Box = $(".box").val();
if( (TerugleverDatum == "") ){
$("#backorderresult").html(" * Some Error .").fadeIn("Slow").fadeOut(3000);
} else {
$("#backorderresult").fadeOut();
$.ajax({
type :'POST',
url :'./backorder.php',
data : box : Box,
backorderdate: BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
}
My PHP:
$boxlist = json_encode($box);
foreach($boxlist as $boxvalue){
// Do something with every value
}
this gives me a javascript error on submit saying box is not defined.
change this:
data : box : Box, backorderdate: BackorderDate, // invalid way of sending
to this:
data : {box : Box, backorderdate: BackorderDate}, // valid way
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs.
More Info
Why don't you try enclosing all the data values in a open and close curly braze( { and } ) .
Else it will conflict with the syntax of $.ajax method.
I think it is causing the problem.
You are sending data value in wrongly manner -
The data property should always be a JavaScript object. It's properties are serialized into a regular query string (for GET requests), or a normal post body parameter string (for POST requests). This serialized string is then sent to the server, along with the AJAX request.
On the server you can read the properties of the data object as if they were sent as simple request parameters, via either GET or POST. Just like if the properties had been fields in a form.
Try this :
$.ajax({
type :'POST',
url :'./backorder.php',
data : 'box='+Box+'&backorderdate='+BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
For more information see jQuery Ajax
You might want to refer to the php file like this: url :'../backorder.php' (double dots). At least, that's how I do it always.
So, i'm making a subscribe form.
Jquery
$("<div id='dialog' title='Subscribe!'> <form id='subscribe_form' method='POST' action='/user/subscribe'>" +
"<input type='text' name='subscribe_email' id='email' placeholder='Email Address'> <br/>" +
"<button id='submit_subscribe_form'>Submit</button></p><p id='ruby_bool'></p></form>" +
"</div>").appendTo($("#subscribe"));
When this form is submitted, it sends an ajax call to a Ruby Sinatra listener (sorry if I'm not using the right terminology, haven't really been taught Sinatra, just shown how to use it)
$('form').submit(function(){
$.ajax({
type: "POST",
url: "/user/subscribe",
data: $('form').serialize(),
success: function()
{
Ruby Code
post "/user/subscribe" do
user_Information = EmailList.new
if params[:subscribe_email] =~ /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/
user_Information.email = params[:subscribe_email]
puts user_Information.save
#email_validation_result = "True"
else
#email_validation_result = "False"
end
puts #email_validation_result
(Yes i know i shouldn't use regex, but the engines i could find were for PHP)
I want to use the #email validation result so i can know what to put in my success: call in my ajax. Problem is, JavaScript doesn't allow Ruby Injection (according to my god knows how many hours of research) and i cant update a div on the web page that contains that variable async. I want to do this all async, so there is no refreshing of the entire page whatsoever. (If it's not possible otherwise i will concede, but i highly doubt that). I tried to put the div on another page and use the JQuery .load() function, but .erb files aren't recognizable.
Out of ideas and nearly out of sanity.
Thanks!
JavaScript:
$.post( '/user/subscribe', $('form').serialize(), function(data){
// Do whatever you want with the response from the server here
// data is a JavaScript object.
}, 'json');
Ruby/Sinatra:
require 'json' # just for a convenient way to serialize
post '/user/subscribe' do
# process the params however you want
content_type 'application/json'
{ :ok => #is_ok }.to_json
end
Without the JSON library you could end your method with just some valid JSON markup, like:
%Q[ { "ok":#{#is_ok} } ]
JavaScript/AJAX will post to the server, the matching Sinatra route will process the request, and the string result of that method (not done via puts) will be sent as the response to the method. The jQuery AJAX handler will receive it, parse it as JSON and invoke your callback function, passing the JavaScript object it created as the parameter. And then you can modify your HTML DOM as desired, client side.
using the checkTL() function, i need to send to the server (for example) only the input value into div with class "sideon". So, in the example, i need to get (server side) only the value of inputside0 and inputside3. How is possible this?
cheers
How about using AJAX?
<form method="POST" action="./index.php?general=example3" name="addtl">
...
</form>
and then:
$(function() {
$('form[name=addtl]').submit(function() {
var dataToPost = $(this).find('.sideon :input').serialize();
$.post(this.action, dataToPost, function(result) {
alert('success');
});
return false;
});
});
Of course putting input fields whose values shouldn't be submitted to the server into a form is doubtful. Maybe you should rethink the way you organize the forms.
two ways:
make them into lots of seperate forms.
do return false on the form submit in jquery and use $(".sideon").find('input').val(); to post an ajax query
I have a getJSON call which is inexplicably failing. The idea is, you click to submit a comment, a URL gets hit which determines if the comment is OK or has naughty words in it. The response is given in JSON form.
Here's the paired down JS that generates the call. The comment and the URL are already on the page, it grabs them and hits the URL:
FORM HTML:
<fieldset id="mg_comment_fieldset" class="inlineLabels">
<div class="ctrlHolder">
<textarea id="id_comment" rows="10" cols="40" name="comment"></textarea>
</div>
<div class="form_block">
<input type="hidden" name="next" value="" />
<input id="mg_comment_url" type="hidden" name="comment_url" value="" />
<input id="mg_comment_submit" type="submit" value="Remark" />
</div>
</fieldset>
SPECIFIC JS BLOCK THAT SENDS/READS RESPONSE:
$('input#mg_comment_submit').click(function(){
var comment = $("textarea#id_comment").val();
var comment_url = $('input#mg_comment_url').val();
$.getJSON(
comment_url+"?callback=?&comment="+comment+"&next=",
function(data){
console.log(data);
alert(data);
});
});
The JSON response:
[{"errors": {"comment": ["Weve detected that your submission contains words which violate our Terms and Conditions. Please remove them and resubmit test"]}}]
It's being returned as a mimetype of application/json. It validates in JSONLint. I also tried adding a couple AJAX functions to try to catch errors, and they're both silent. I can see the request going out in Firebug, and coming back as status 200 responses, which validate in JSONLint and which I can traverse just fine in the JSON tab of the response. If I put an alert before the getJSON, it runs; it's just that nothing inside of it runs. I also find that if I change .getJSON to .get, the alerts do run, suggesting it's something with the JSON. I'm out of ideas as to what the problem could be. Using Firefox 3.0.13.
The querystring parameter "callback=?" comes into play if you are using cross-site scripting or jsonp, if you are posting the same server, you don't need to use that.
If you need or want to use that option, the server side code needs to come back with the callback function included in the json response.
Example:
$jsonData = getDataAsJson($_GET['symbol']);
echo $_GET['callback'] . '(' . $jsonData . ');';
// prints: jsonp1232617941775({"symbol" : "IBM", "price" : "91.42"});
So either make a server side change if necessary or simple remove the "callback=?" parameter from the url.
Here's more info on jsonp
Are you able to manually call your service without any errors? Have you tried using firebug and looked under XBR to see the post/response of the JSON payloads? I normally use .NET as my endpoints, and with .NET 3.5 I need to use content type "application/json; charset=utf-8".
Here is an example of a working JSON call I use in .NET with jQuery 1.3.2
$.ajax({
type: "POST",
url: "WebService1.ASMX/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function(res) {
// Do your work here.
// Remember, the results for a ASMX Web Service are wrapped
// within the object "d" by default. e.g. {"d" : "Hello World"}
}
});
Have you tried it with $.ajax? You can then define both error and success callbacks and have better idea.
Can you try adding a global ajaxError function to log the error.
$.ajaxError( function(event, XMLHttpRequest, ajaxOptions, thrownError){
console.log( thrownError );
});