How to send or get date value by ajax - javascript

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()

Related

Post Method to URL from a onclick function

I need help on something that sounds easy but is difficult for me.
So when someone clicks on this div:
<div onclick="<go to url sending data using the post method>">Click Me</div>
I want it to send data to a PHP file that will take the information that i want it to. I would use the GET function but I have heard that its easily hackable. If their is a lot simpler solution or something more secure please help me out.
If you need to use div you can do it like this but I suggest that you use button or input of type submit.
<form id="form-id" method="post" action="your-php-file-url">
<input type="hidden" name="your-variable-name" value="your-variable-value">
<div onclick="document.getElementById('form-id').submit();">Click Me</div>
</form>
Also you may use jQuery or some other JS library.
NOTE: Keep in mind that if the data that you send is provided via browser it's really easy to manipulate (doesn't mater if you use POST or GET) so it's important to check it out when you process it.
Using form would be ideal. If for some reason if you don't want to use form or want to build a dynamic app then use it in this way.
//jquery library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="someInput">
<div onclick="sendData()">Click Me</div>
<script>
function sendData(){
//get the input value
$someInput = $('#someInput').val();
$.ajax({
//the url to send the data to
url: "ajax/url.ajax.php",
//the data to send to
data: {someInput : $someInput},
//type. for eg: GET, POST
type: "POST",
//datatype expected to get in reply form server
dataType: "json",
//on success
success: function(data){
//do something after something is recieved from php
},
//on error
error: function(){
//bad request
}
});
}
</script>
You can use <form> to send data
<form action="yourpage.php" method="post">
//form contents
<input type="submit" value="Submit">
</form>
The action URL specifies the URL of the page to which your data has to be send.

How to load PHP page with variables passed from javascript

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

404 error because of ajax code?

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

Ajax form not getting a reply from php file

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.

jquery submit function does not 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.

Categories