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
Related
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
Ok I am confused with php, javascript and html and dont know what to do. On researching on the internet, i found js is client side and php is server side. when a php file is run on the browser, it converts everything into html and the page is loaded. Now let me tell you guys what i am doing.
I have a php file that give me some stats from a particular url (in the sample i am just showing url)
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Result URL = www.example.com
The above code echoes the url which is www.example.com. I added a textbox to this code which i believe is javascript+html
<script>
function myFunction() {
$url=myurl.value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Here the result is same. only difference is that it has a textbox and button above the result.
When I enter another url in the textbox and press submit, it does nothing probably because the page is already loaded. I want to replace the result of www.example.com to the one which is entered in the textbox without changing the .php file. There will always be a default url in the .php file. whenever the file is opened in the browser, the default statistics will be shown... only when the user enters new url and clicks submit, the stats should change.
How can I achieve this? I am behind this since more than a couple of hours now and not sure how to get this done. Please help me.... Thank you.
EDIT
Can I have two .php files? one for the user to enter url and submit and another one to get the entered url and echo it? If yes, how? If I understand this logic, i can get a start for what I am doing.
I think you are trying to do more with your js function, but syntactically it is combining js and php. It should look like this
function myFunction() {
var url = document.getElementById('myurl').value;
}
Although this doesn't really do anything other then assign the content of the text box to a variable.
EDIT
<script>
function myFunction() {
document.getElementById('url').innerHTML = document.getElementById('myurl').value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<? $url = "www.example.com"; ?>
URL = <span id="url"><?= $url; ?></span>
natzim is correct if you are wanting to write the url back to the php file. If you use javascript to change the action of the form, it will submit to a different page.
//javascript
function myFunction() {
//this should change the page that loads after submit.
//If you want to go to a new page that the user enters, leave this code in...
//If not, remove it
document.getElementsByTagName("form")[0].action = document.getElementById("myUrl").value;
}
That is assuming you have a form tag somewhere (which you will need to submit the page). Also I am not sure this code will run if you use a submit and not a button. If you used a button instead you could append this to the code above to submit the form:
//This would be part of your myFunction if you used a button instead of a submit input
document.getElementsByTagName("form")[0].submit();
as per my comment -
this code is your old php:
<?
$url="www.example.com";
echo "URL = " .$url;
?>
and this is the php I suggested:
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
this would check the myurl input from that was submitted to the server and set the value of $url to its value if it existed then the $url variable would be echoed to the page under the inputs.
This code is assuming you are using the POST method rather than the GET method when your form was submitted.
**EDIT: **
To clarify - here is your page with the modifications I am suggesting. (Please ignore the javascript above as it seems you will not need it):
<form action='www.example.com' method='post'>
<input type="text" name="myurl" id="myurl">
<input type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
</form>
I need to send a few values to PHP using AJAX. My code works great with input type "text" but "date" doesn't work :( maybe its becouse Im using "serialize()". I spend all day to fix this problem... Im wrealy dummy in JS and AJAX its somethink *** for me so if you know how to solve this bug I'll be very appreciate!
My code HTML/JS:
<form method="post" action="javascript:send('SendData.php','myform','result');" id="myform">
<input type="text" name="whois" value="5" /><br/>
<input value='2004-02-12' type='date' name="Date"><br/>
<input type="button" value="Send" onClick="send('SendData.php','myform','result');" />
</form>
<script type="text/javascript">
function send(url,form_id,result_div)
{
$.ajax({
type: "POST",
url: "SendData.php",
data: $("#"+form_id).serialize(),
success: function(html) {
$("#"+result_div).empty();
$("#"+result_div).append(html);
},
error: function() {
$("#"+result_div).empty();
$("#"+result_div).append("ERROR!");
}
});
}
</script>
and PHP
<?php
echo $_POST['whois'];
echo '<br>';
echo $_POST['Date'];
?>
Your code works for me... http://jsbin.com/finomificoyo/1/edit showing two POST with data
I think the problem is you ar using
data: $("#"+form_id).serialize(),
to get your "data" value. But you in your code I can not see where is your id?
<input value='2004-02-12' type='date' name="Date"><br/>
I thing jQuery is unable to find the object
$("#"+form_id)
Try this
<input id="dataVal" value='2004-02-12' type='date' name="Date"><br/>
And inside Ajax use
data:$("dataVal").val();
To perform a test only do that:
alert($("dataVal").val());
You are missing a few curly brackets, so the javascript probably wont actually compile.
The browsers javascript debugger should have been able to tell you this if you had looked.
I am not sure if you are using an old jquery library, but if you are using a fairly current version try this.
function send(url,form_id,result_div)
{
$.ajax({ type: "POST", url: "SendData.php", data: $("#"+form_id).serialize()})
.done( function(html) {
$("#"+result_div).empty();
$("#"+result_div).append(html);
})
.fail( function() {
$("#"+result_div).empty();
$("#"+result_div).append("ERROR!");
});
}
</script>
serialize() function returned string for get but you need use serializeArray for get all form data in array and send in backend if you use method get you can use serlialize function, but you use method post, for post use serilaizeArray() funtion
jQuery('#myform').serializeArray()
This form is working perfectly fine, e.g. it stops the form submitting, there's no javascript errors in the console log. However, when I press submit, I get an alert with nothing in it. I have searched the internet for multiple solutions and they all give the same for me.
Here's my Javascript/Html
<script>
$(function(){
$("#submit").click(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"templates/process-token.php",
data:$("#form").serialize(),
success:function(response){
alert(response);
}
});
});
});
</script>
<form id="form" method = "post" action = "security_check">
<input type = "text" name = "fld1" id = "fld1" />
<input type = "text" name = "result1" id = "result1" value = "value_from_php_page" disabled />
<input type="submit" value="Submit" id="submit">
</form>
And here's the PHP, it's so simple but doesn't work:
<?php
echo $_POST["fld1"];
?>
Any help here would be appreciated. Thank you.
Change data from $('#form').serialize() to a one test variable so you can see if it is JS or PHP that is causing the issue.
On your PHP page:
<?php
isset($_POST["fld1"]) ? $myvar1 = $_POST["fld1"] : $myvar1 = 'No data passed...';
echo $myvar1;
?>
This confirms that there is infact an fld1 in the $_POST, and if not, says so, taking away the guess work...
You could do this with JSON both ways. Here's how I would implement this kind of thing in JavaScript and PHP.
There's a great function in jQuery that is a shortcut for getting JSON data. It's a shortcut for $.ajax specifically for simple calls.
$.getJSON( "templates/process-token.php?"+$("#form").serialize(), function( data ) { alert( data.reponse ) } );
PHP could return a json encoded string so it can be accessed from the JavaScript code more easily.
<?php echo json_encode( array('response'=>$_POST['fld1']) ); ?>
That can happen only if the text box #fld1 is empty. Type something in the text box and it will work.
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.