I'm developing a webpage which creates a form with various select tags dynamically. Unfortenatley the jquery submit function passes incorrect information to the php file (form_submit.php) that must process this information; the (netbeans 7.4) debugger always shows default (not selected) values in $_POST within the php file instead of the selected values . The even stranger part: when I copy (in the code below) the console output with the serialised formdata straight into the following ajaxcode (see code), the php debugger shows the correct -selected values within the $_POST array..(?)
The resulting form is quite substantial. The only theoretical cause I can think of is that therefore the execution of 'var dataAjax = $( this ).serialize();' takes time and is not finished when the following ajax call starts...(??)
The code:
$("#myForm").submit(function(event){
event.preventDefault();
var dataAjax = $( this ).serialize(); //does not work, but when copying the string from the console in line below it does work.
console.log('SUBMITTED FORM: '+ dataAjax );
//next line is only used as a test
//var dataAjax = 'agreementapproval0=SolarX_10&selected_emeterproductid0=SolarX_10_1_1&selected_eproductid0=SolarX_10_2_4&selected_emeterproductid1=NOSELECTION&selected_emeterproductid2=NOSELECTION&selected_eproductid1=NOSELECTION&selected_eproductid2=NOSELECTION&form_token=30688e467ee88167805ad0f330809d74';
$.ajax({
type: "POST",
url: "form_submit.php",
data: dataAjax,
dataType: "json",
async: true,
success: function(msg){
if(msg.statusgeneral == 'success'){
}
else
{
}//else
}, //succes: function
error: function(){
$("#errorbox").html("There was an error submitting the form. Please try again.");
}
});//.ajax
//make sure the form doesn't post
//return false; //depreciated
//} //if(form.valid()
});//$("#myForm").submit()
<form id="myForm" name="myForm" action="" method="post">
<div id="wrapper"></div> <!--anchor point for adding set of product form fields -->
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
<input type="submit" name="submitForm" value="Confirm">
</form>
It works fine http://jsfiddle.net/a9DN4/
You might have been trying to hook form before it have been created, try to wrap your code with
$( document ).ready(function() {
// Handler for .ready() called.
});
PS and move event.preventDefault(); to the 1st string of your function, as Kevin says.
Related
I have a form in which currently posts to a hard coded php page in the action of the form, this works fine, it posts to the DB no problem, but where things get tricky for me is I don't want to post to a new page so I have opted to use ajax. So I got rid of the action field from the form and put in some jquery to make an ajax call. the issues I am having is well..it doesn't work :D. Could someone take a look at my js file and explain to me what I am doing wrong or what I should do?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<form>
<p>Comment</p>
<textarea name= "comment" rows="6" cols="50"></textarea><br />
<input type="submit" name= "submit" value="submit" id = "submit">
</form>
$('#submit').on('click',function(){
$.ajax({
type : 'POST',
url : 'comment.php',
data : formData,
dataType : 'json',
})
});
You should handle the 'submit' event of the form over the 'click' event of the submit button. You should also return false; at the end of function to prevent the form from posting to a new page. You are handling the submit yourself. Also I would put the action attribute back on the form element for the rare occasion that JavaScript is disabled on the client. Give the form an id and target that. Your code is correct otherwise.
HTML
<form id="my-form" action="comment.php" method="post">
<!-- input fields -->
</form>
JavaScript
$('#my-form').on('submit', function(){
// code...
return false;
});
Providing the action attribute, as well as the method attribute, on the form element will make these available to access in your submit handler as well as providing a proper fallback for any JavaScript failures. That may not be necessary for this instance but may be helpful in the future.
Your handler could now look something like this:
JavaScript
$('#my-form').on('submit', function(){
// serialize the form
var formData = $(this).serialize();
$.ajax({
type : this.method,
url : this.action,
data : formData,
dataType : 'json'
})
.done(function (data) {
// do some stuff with 'data'
})
.fail(function (error) {
// do some stuff with 'error'
});
return false;
});
I have the following JS code:
<script>
$('#mpxModalEdit').on('show.bs.modal', function(e) {
var editId = $(e.relatedTarget).data('edit-id');
$(e.currentTarget).find('input[name="editId"]').val(editId);
});
</script>
This places the CORRECT edit-id value into a form text box name=editIdas I wish.
I would like to add another line of JS so that it ALSO places the value into a PHP variable since I need to make a subsequent
$query = "select * from playlists where id='editId'
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
So how to retrieve a value from JavaScript?
Well, you could stick the javascript value in a hidden form field...
That could be the best solution only.
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
Or the another way is to use AJAX.
PHP-Scripts are only run, when you load your page before any js is run or make an AJAX. In addition, PHP runs on the server, while JS is client-side.
My first suggestion would be, to really think, whether you need to do this (or even tell us, why you think it is).
If you really need it, you can perfom an AJAX and send your variable as data to the Server.
Using AJAX call you can pass js values to PHP script. Suppose you are passing editId js value to logtime.php file.
$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id');
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data: { editId : editId },
success: function(data)
{
alert("success!");
}
});
});
});
<?php //logtime.php
$editId = isset($_POST['editId']);
//rest of code that uses $editId
?>
Place the AJAX call after
$(e.currentTarget).find('input[name="editId"]').val(editId);
line in your js script.
then you can assign to your desired PHP variable in logtime.php file
I'm new to PHP and am trying to figure something out that I'm sure is very basic. What I am wanting to do is generate variables in javascript and pass these to a PHP page which then loads and displays. The problem is, I seem to be able to both POST variables to the PHP page and load the PHP page but am unable to load the PHP page with the variables that I POSTed.
Here is an example of my code:
index.php
...
<script language="javascript">
function passToPHP(){
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
data: {
varToPass: "foo"
},
success: function(){
window.location.href="/TraceExperiment/TraceExperiment.php";
}
})
}
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
TraceExperiment.php
<?php
$tempVar = $_POST["varToPass"];
echo("hello" . $tempVar);
print_r($_POST);
?>
What is happening when I click displayPHP is that the ajax POST succeeds and
TraceExperiment.php loads fine (it actually has a whole heap of other html, php etc. code that loads and displays fine but for simplicity I've excluded that) but the $_POST array seems to be empty.
i.e. what ends up being displayed when I try to echo and print the POST array and variables is:
Notice: Undefined index: varToPass in C:\xampp\htdocs\TraceExperiment\TraceExperiment.php on line 3
helloArray ( )
Any help resolving this would be much appreciated. Ultimately, I'm simply after a way to display a PHP page that uses variables passed from a javascript file.
You can dynamically create a form in JavaScript and submit it rather than calling ajax and refreshing the page:
<script language="javascript">
function passToPHP(){
$('<form action="/TraceExperiment/TraceExperiment.php" method="POST"><input type="hidden" name="varToPass" value="foo" /></form>').appendTo('body').submit();
}
</script>
<input type="button" value="displayPHP" onclick="passToPHP()"></input>
You can do a get request like this
<script language="javascript">
function passToPHP(){
var varToPass= "foo"
window.location = "/TraceExperiment/TraceExperiment.php?varToPass="+varToPass;
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
<?php
$tempVar = $_GET["varToPass"];
echo("hello" . $tempVar);
?>
or a post request by creating a simple form
$('#frm').submit(function(e){
var varToPass= "foo"
e.preventDefault();
$(this).find('#varToPass').val(varToPass);
$(this).submit();
});
<form id ="frm" method="POST" action="/TraceExperiment/TraceExperiment.php">
<input type="hidden" id="varToPass"/>
<input type="submit"/>
</form>
dont redirect to the same page on success. you are getting the undefined var on second go to that page
function passToPHP() {
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
dataType:text,
data: {
varToPass: "foo"
},
success: function(data) {
console.log(data);
}
})
}
try doing like this
if you want to show the message in the html
try
success: function(data) {
$('body').append(data);
}
There is 2 solution for This
by the different approach
Generate your variable value by JavaScript and than use
Write in TraceExperiment.php
function genratenumber(){
return "number"
}
window.location.href= "/TraceExperiment
/TraceExperiment.php?yourvar="+genratenumber()
</script>
<?php }else{
// get the value of $_GET['yourvar']
} ?>
Than get it by using $_GET['yourvar'] on same page
By using your approch
you need to put that variable in session (in ajax file) than only you can get that variable
I am creating a form that will get a search query request from the user on submit and will display the results after making an API call I would like to show the results without refreshing the page using AJAX. I am using PHP to connect to the API.
This is what I have so far but I can't get the results displayed. Regardless of the success of the API connection, I cant even get the entry of the form displayed in the same page without refreshing the page so I am not sure if I am doing it right. what am I missing? What else do I have to consider in order to make this work? Could someone please guide me to the right direction?
$(document).ready(function() {
$('#search-form').on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
console.log(data);
$('#results').html(data);
}
});
});
});
<form action='result.php' method='post' id='search-form'>
<input type='search' name='search'>
<input type='submit' value='submit'>
</form>
<div id='results'>Result comes here..</div>
// result.php
if(isset($_POST['search'])) {
$query = urlencode( $_POST[ "search"]);
$request = 'http://some.api/?query=' . $query;
$response=file_get_contents($request);
$result=json_decode($response);
echo ($result);
} else {
echo ("No search query has received");
}
.serialize() does not serialize submit buttons. Submit buttons are only sent in requests when they are pressed/trigger the submit action on the form they are in, .serialize() has no way of knowing any of that.
You'll just have to add that information manually or not check for it at all.
...
data: $(this).serialize()='&submit=ajax',
...
or
if(!empty($_POST['search'])) {
...
I suggest in this case, you just create a hidden field with the value like this:
<input type="hidden" name="search" value="submitted" />
And that's going to be there on a submit.
I have a form with action="" and many AJAX codes to validate or chain-select the form elements as below.
** My current code (Simplified) **
<?php
if( isset( $_POST['create_transaction'] ) ) {
// do something
}
?>
<div>
<!-- period information will be filled up by ajax -->
<input type="text" name="period" class="form-control" id="period" readonly />
</div>
<form id="form" method="post" action="">
<input name="r_date" type="date" value="<?php echo isset( $_POST['r_date'] ) ? $_POST['r_date'] : date( "Y-m-d" ); ?>" class="transaction_date" />
<input type="submit" name="create_transaction" value="Create" />
</form>
<script>
jQuery(document).ready(function($) {
// Do this and that...
/* Get period information if date is already filled up on page load */
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var $transaction_date = $(".transaction_date").val();
if( $transaction_date ) {
// call ajax for period <-- THIS IS THE PROBLEM CHILD.
jQuery.ajax({
url: ajaxurl,
data: 'action=get_period_by_date&transaction_date='+$transaction_date,
type: 'GET',
success:function(results) {
jQuery("#period").val(results);
}
});
}
});
</script>
Here I am retrieving a period name using the input date. For example, if the date is 2014-01-01, then the #period div will be filled up with PERIOD-01. If the date is 2014-08-25, then the #period div will be filled up with PERIOD-08. This date field is auto-filled up with today's date when the page loads.
The problem is that if I insert the AJAX code to retrieve period information using the date input, submitting the form (clicking the 'create' button) leads to 404 error. If I remove the code, the form works well.
There doesn't seem to be a problem in the get_period_by_date function since it correctly retrieves and shows period name.
What would be the cause of my problem?
404 error means that your AJAX request leads to an unexisting path. Thats the first issue you should solve :).
Use your console to debug this one:
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
You are using this var in a jQuery method. I think it will be literally interpreted. I don't think it's possible to use php syntax here.
I'm not sure if it's a good practice, but for a quick fix you could make a hidden field in your html page with that tag. And then you could easily get the value from it with the use of jQuery or javascript