how to do $_POST for datepicker in php/codeigniter - php

First, I'm using the codeigniter framework and I'm a beginner in JS and AJAX, so please bear with me.
I read this question, so I tried to follow the answers.
This is the script (UPDATED):
$(function() {
$( "#datepicker").datepicker().click(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
return false;
});
});
And this is my datepicker HTML code:
<input type="text" id="datepicker" name="datepicker"
value="<?php echo isset($umat['tanggal_lahir'])?$umat['tanggal_lahir']:""?>"/>
My questions are (UPDATED):
Is the URL I provided in AJAX above correct?
How should I pass the data from AJAX to PHP (url: "<?php echo base_url(); ?>backend/umat/add")?
Thanks for your help :D

What you have missed here:
your click event is outside of the doc ready handler, that should be inside doc ready so that when page gets ready the element should be available to click.
You have missed a closing }); tag of the click event.(does not matter though)
so try this:
$(function() {
$( "#datepicker").datepicker();
$("#datepicker").click(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: {frmData : $('#form_daftar').serialize()}, // <----send this way
success: function(data) {
console.log(data.date);
// here data is the returned data from the specified url and make sure
// that url is generating a proper json structrue.
// suppose there is a key named date which holds the submitted date so
// data.date will get you the date.
}
});
}); //<----you missed this closing of click function.
}); //<----------put everything before this closing of doc ready handler.
Although you can chain it too like this:
$(function(){
$( "#datepicker").datepicker().click(function() {
//......ajax function in click here
});
});
See a demo here

Another approach would be to use the datepicker inbuilt methods to trigger ajax request like
$('#datepicker').datepick({
dateFormat:"yyyy-mm-dd",
onSelect:function(){
$.ajax({
type: 'POST',
url: "<?php echo site_url('backend/umat/add'); ?>",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
}
});
Check the manual or inbuild functions and callbacks with your datepicker js.

try it:
$(function() {
$( "#datepicker").datepicker();
$("#datepicker").change(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
});
php get data form ajax:
<?php
$date = $_POST["datepicker"];
?>

Related

Add custom $_POST before submitting form with jquery

First of all, sorry if this is a duplicate. I've looked and seen some solutions but none worked. I've been trying to do this simple thing for like 3 hours with no result.
I'd have this html:
<form method="post" action="?c=Logo&action=save" id="form">
<!-- some inputs -->
<img src="" data-filename="new-logo.png">
<input type="submit" value="submit">
</form>
Here I'd like to modify the form so my php file will recognise $_POST['new-logo'].
// $_POST['new-logo'] = $('img').data('filename')
$logo = new Logo($_POST['new-logo']);
$logo->save();
I guess I should use the jQuery function $.post() but somehow I can't manage. Thank you all for your help :-)
SOLUTION
Finally since I found a very simple solution. Since I want my data to be processed in my php file, I simply added an <input type="hidden"> and modified its value with JS :-)
You could also make the data array from scratch like this:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: {key1:"value", key2:"value2"},
dataType: "json",
success: function(data) {
//do success stuff here
},
error: function() {
//do error stuff here.
}
});
});
You can add it as a hidden input.
$("#form").submit(function() {
$(this).append($("<input>", {
type: "hidden",
name: "new-logo",
value: $(this).find("img").data("filename")
});
});
you can add this to you're post request like this :
$('#form').on('submit', function(e){
e.preventDefault();
var $form = $(this);
var datastring = $form.serializeArray();
datastring.push({name:'new-logo', value:$form.find('img').data('filename')});
$.ajax({
type: "POST",
url: $form.attr('action'),
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
});
$logo = new Logo($_POST['new-logo']);
Is "new Logo" a function or something? Pretty sure that can't have a space.

Pass Jquery variables to PHP using AJAX

I'm trying to make an app where if you click on a div, the data-id will be put into a variable, which will give PHP the select parameters to look for. Here's my code to better explain it.
HTML:
<div class="box" data-id="caption"></div>
JQuery:
$('.box').click(function () {
var caption = $(this).data('id');
});
After Googling I found the best way to do this is through AJAX, which I then proceeded to try:
$.ajax({
url: 'index.php',
type: 'GET',
dataType: 'json',
data: ({ caption }),
success: function(data){
console.log(data);
}, error: function() {
console.log("error");
}
});
However, this doesn't seem to work. If there's a better way to do what I mentioned above, I'm open to new ideas.
EDIT
Here is my PHP code.
if(isset($_GET['caption'])){
echo $caption;
$select = "SELECT * FROM pics WHERE text = '".$caption."'";
}
?>
Look through the api at jQuery.
Your data key should contain a json object -
$.ajax({
url: 'index.php',
type: 'GET',
dataType: 'json',
data: {caption: caption},
success: function(data){
console.log(data);
}, error: function(error) {
console.log(error);
}
});

auto load data from database using jquery

I would like to display newly inserted data from database. I found the below code from another question and it does what I want but it only shows the data when clicked. So can someone tell me how can I make the data auto load every 5 secs?
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<input type="button" id="display" value="Display All Data" />
<div id="responsecontainer" align="center">
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function (response) {
$("#responsecontainer").html(response);
setTimeout(load, 5000)
}
});
}
load(); //if you don't want the click
$("#display").click(load); //if you want to start the display on click
});
Try to add setTimeout:
success: function(response){
$("#responsecontainer").html(response);
setTimeout(success, 5000);
}
You can use function setTimeout as a timer to trigger. For detail, please look at below code:
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
setTimeout(loadData, 5000);
}
});
};
You may use jquery's setInterval() or setTimeout() inside onload();
refer to the following questions, its answer explains well what you need exactly.
Calling a function every 60 seconds

$.ajax not execute jquery code from php

I'm trying to execute a jquery code from a php page called by ajax.
Change html of div.error
Here's the code(If there is an easier way just tell/post):-no $.load
HTML/jQuery: jquery.js already linked
<input type='text' id='test'>
<div id='error' style='display:inline-block;'>CHANGE HERE</div><bR>
<input type='submit' value='run' id='button'>
<script type='text/javascript'>
$('#button').click(function(){
$.ajax({
url: "test.php",
type: "POST",
data: "test="+ test,
success: function(jqXHR){
},
error: function() {
alert('error');
}
});
});
</script>
test.php
<script type='text/javascript'>
$('#error').html('working');
</script>
The test variable that you are using doesn't seem to be declared anywhere. Try hardcoding first. Also the {key:value} syntax is preferred as it ensures to properly url encode the value when sending to the server:
data: { test: 'some value' }
and if you want to use a variable, make sure you have declared it:
$('#button').click(function() {
var test = 'foo bar';
$.ajax({
url: 'test.php',
type: 'POST',
data: { test: test },
success: function(data) {
},
error: function() {
alert('error');
}
});
});
Also if you want the javascript to execute in your php script remove the <script> tags:
$('#error').html('working');
and specify the dataType parameter to script in your $.ajax call:
dataType: 'script'
Another possibility is to have your test.php script simply return the value:
working
and then inside the success callback refresh the DOM:
success: function(data) {
$('#error').html(data);
},
The JavaScript from inside test.php won't run because you've never told it to. It's not just gonna run because you loaded it. It needs to be in the DOM to run.
Try this:
$.ajax({
url: "test.php",
type: "POST",
data: "test="+ test,
success: function(data){
$(data).filter('script').appendTo('head');
},
error: function() {
alert('error');
}
});
Your test.php script should output what you want to display.
it should look something like:
echo "<html>";
echo "<div>working</div>";
echo "</html>";
so that it returns something. Right now, you are returning only javascript.

Jquery ajax get request

I am new to jquery and php, I have two input fields, zip and city, the city shall output a value based from the zip that the user input. The jquery script shall call a URL: http://domain.com/city?zip.php="zip; so that zip.php will return an echo value that will output to the city input field.
I tried using ajax getXMLHTTP. some times it works but sometimes not
Please Refer to the following code snippet below:
<input type="text" id="zip_code" name="zip_code" />
<input type="text" id="city" name="city" />
<script type="text/javascript">
// Some Jquery code here for ajax get request to http://domain.com/city?zip.php
</script>
if you are using jquery the use $.ajax option instead of getXMLHTTP
function passzipvalue(zip)
$.ajax({
type: "GET",
url : 'http://domain.com/city.php='
data:"zip="+zip,
success: function(msg){
$("#formsData").html(msg);
}
});
}
something like this or
$.get('http://domain.com/city.php?zip='+zip,function (msg){
$('#formsData').html(msg);
});
if you want to populate it in some input fields use .val instead of .html
Use jQuery.get, documented here. In the success handler, use the data argument to populate the city input.
Sample:
$.get('http://domain.com/city.php?zip='+$('#IdOfZipInput').val(), function (data){
$('#IdOfCityInput').val(data);
});
Use jQuery AJAX. For example:
var zip = $('#zip').val();
$.get('http://domain.com/city.php?zip='+zip,function (data){
$('#city').val(data);
});
$.ajax({
url: 'http://domain.com/city.php?zip='+zip,
type: get,
success: function(data){
$("div").html(data);
}
});
use this data will be displayed
If its a constantly updating element then use jquery.post as ie caches the "get" results.
jQuery.post('call.php',{ action: "get"}, function (data) {
jQuery('#content').append(data);
});
FInd the tutorial here http://vavumi.com/?p=257
try to use the jquery ajax
$.ajax({
type: "POST",
url: 'sample/test.php',//your url
data: data,//data to be post
cache: false,
success: function(html) {
alert(html);//response from the server
}
});
$.ajax({
url: 'url',
beforeSend: function (xhr) {
//show loading
}
}).done(function (data, xhr) {
//hide loading
//success
}).fail(function (xhr) {
//hide loading
//error
});

Categories