I am adding a onSelect function on datepicker to Post the selected value using ajax and echo post data using load function
My jquery code is
$('#merchant_datepicker').datepicker({
onSelect: function (formattedDate,date,inst) {
var merchant_datepicker = $('#merchant_datepicker').val();
{
$.ajax({
url:'../calendar.php',
method:"POST",
data:{merchant_datepicker:merchant_datepicker},
success:function(data){
$('#order_wrap').load("../calendar.php");
alert(data);
}
});
}
}
});
and my calendar.php is
<?php
$new_date=$_POST["merchant_datepicker"];
echo $new_date;
?>
<p>Hello</p>
I am getting the data in alert and also div#order_wrap shows "Hello" after selecting a date but I can't echo the $_POST["merchant_datepicker"]
Please help. Thanks
You are currently making two requests to calendar.php (one is the ajax POST, the other is the .load() call). If you just want to take the response of the POST and put it in to #order_wrap, use the data var that you already have.
$('#order_wrap').html(data);
Or instead of .html maybe .append or .prepend depending on what exactly you're wanting to do.
Related
EDIT: The question has more to do with altering the variable (valueA) than anything. I am already getting the desired load result using the script below. I am trying to attach something to the script that will ultimately alter valueA once clicked.
I am designing multiple pages that will load into a main content div on click using .load
index.php
//Setting default value
$valueA = 5;
//Created separate div to allow me to monitor the variable and changes
<div><?php echo $valueA; ?></div>
//Loading first page into div
<div id=main_content>
<?php include 'page1.php'; ?>
</div>
Included in page1.php is a button that will load the page assigned to it.
page1.php
<button id="button1">Click Me!</button>
<script>
$(document).ready(function(){
$('#button1').click(function(){
$('#main_content').load('page2.php').hide().fadeIn('slow');
$.ajax({
type: 'POST',
url: 'index.php',
success: $valueA += 5,
});
});
})
Upon clicking, page2.php will load, but the value will remain 5. I am trying to figure out how to add the 5 using the ajax script to the valueA. Ultimately, the new page would load, and the value would increase to 10.
The incrementing of your php variable has to be done in a php script, not javascript. Javascript inherently knows nothing about your php, and vis-versa.
The other thing to mention is that the success property on the $.ajax object is a function, so you should define it as such. See jQuery Documentation for full details on $.ajax
$.ajax({
...
...
success: function () { ... }
});
Edit
After clarification, here is an updated, more thorough example.
HTML
<div id="valueAContainer"><?php echo $valueA; ?></div>
jQuery
$.ajax({
url: "yourphpscript.php",
method: "GET" (or post, whatever is applicable),
data: { valueA: $("#valueAContainer").text() },
success: function (data) {
$("#valueAContainer").text(data);
}
});
PHP
// get valueA variable from request
$oldValue = $_GET['valueA'];
// Do whatever you want to it - increment, save to DB, etc.
$updatedValue = $oldValue + 5;
// Return updatedValue to javascript
echo $updatedValue
To give you the most basic view of my question, I'm trying to create a page that is very similar to how facebook and twitter's dashboards and comment systems work. You have one page that will continuously create form elements (posts) from database rows in a loop as the user scrolls down. Users will then be able to comment on each of these posts. I want to be able to use ajax to submit comments on each post individually without reloading the page.
I run into a problem where when I try to submit a comment on any form other than the first one that is loaded on the page. In addition the ajax only posts the first form elements on submit (due to each form and elements having the same name I'm guessing).
Below is my comment loading script: [forgive the old php, I know I need to update it to mysqli or PDO]
php
<?php ...
$query = mysql_query("SELECT * FROM `posts`");
while ($row = mysql_fetch_array($query)) {
echo "
<div name='comment_body'>
<form name='comment_form'>
<td>User: ".$row['user']."</td>
<td>Post: ".$row['post']."</td>
<textarea name='comment'></textarea>
<p name='post_id' style='display:none;'>".$row['post_id']."</p>
<input type='submit' name='submit'>
</form>
";
$query2 = mysql_query("SELECT * FROM `comments` WHERE `post_id` = $row['post_id']");
while ($row2 = mysql_fetch_array($query2)) {
echo "
<td>User: ".$row2['user']."</td>
<td>Comment: ".$row2['comment']."</td>
</div>
";
}
... ?>
jscript
<script>
$('.comment_form').on('submit', function (e) {
e.preventDefault();
$.ajax ({
type: 'post',
url: 'submit_comment.php',
data: {comment : $('#comment').val(), post_id : $('#post_id').text()}
success: function() {
$("#comment_body").load("load_comments.php #comment_body");
}
});
});
</script>
The script works to a point because when I comment on the first post, it works as expected. I just can't seem to figure out how to target the forms further down the page individually. Here's an example:
The very top post has a post_id value of 40. If I comment on post_id = 38, ajax will submit the empty comment field and post_id = 40 into the database.
Any help with the script form targeting would be great. If I need to rebuild my php query to give each echoed form element an individual name, that's fine as well. Thanks in advance!
The data you're trying to send to in the ajax call is using:
$('#comment').val(), post_id : $('#post_id').text()
But your HTML doesn't have anything with an ID="comment" and ID="post_id". (the '#' in your selector means getElementById.) So you aren't sending any data to your php page. You need to use the correct selectors to get that data. (see below)
Get rid of the 'form' tags you don't need them. Change your
<input type="submit">
to a:
<input type="button" class="comment-submit">
Then your script can be:
<script>
$('.comment-submit').on('click', function (e) {
e.preventDefault();
// get a referenct to this particular comment_body div
var $commentbody = $(this).closest('.comment_body');
// find the textarea within this particular comment_body
var commenttext = $commentbody.find('textarea[name="comment"]').val();
// find the post_id paragraph within this particular comment_body
var postId = $commentbody.find('p[name="post_id"]').text();
$.ajax ({
type: 'post',
url: 'submit_comment.php',
data: {comment : commenttext , post_id : postId}
success: function() {
$comment_body.load("load_comments.php #comment_body");
}
});
});
</script>
Frankly I'm not sure what your success function is trying to do. But I think you need to work on it too. Normally an ajax call will return data so your success function should have a return value and that would be used to populate some part of your screen. The jQuery 'load()' function is another ajax call inside the success callback of an ajax call. I really don't think you want or need to do this.
You cannot select a unique form by class because your class is identical across all forms. Add an "id" field to the form element like this:
"<form name='comment_form' id='"+ .$row['id'] +"'>"
Then select a given form using that unique ID, and add your event handler. This must be in the same scope as you define your form. Like this:
$('#'+ .$row["id"]).on('submit', function (e) {
//Handle the event
})
I am using codeigniter and grocerycrud.
I have a view, in this view I have some dropdowns, those dropdowns are being feed from the controller:
public function programar_ruta()
{
if($this->model_privilegios->validar_usuario()==true)
{
$data['destinos'] = $this->model_querys_usuario->get_destinos();
$this->load->view('usuario/dynamic_form2',$data);
}
}
My model function code:
public function get_destinos ()
{
$this-> db ->select('*');
$this-> db ->from('destinos');
$this -> db -> where('empresa', $_SESSION['empresa']);
$query = $this->db->get();
return $query->result();
}
Inside of my form I have the dropdowns and a button heading to a controller function that allows to add a new "Destino":
<td width="18%" align="left">
<select name="destinos[]" id="origen0">
<?php foreach($destinos as $row)
{ echo '<option value="'.$row->nombre.'">'.$row->nombre.'</option>'; } ?>
</select>
<input type="button" value="..." onClick="window.open
('<?php echo base_url()?>index.php/usuario/destinos/add','Nuevo Destino','width=800,height=600')" title="Agregar nuevo destino"/></td>
The code "index.php/usuario/destinos/add'" is heading to a standar grocerycrud function.
My question is: there is a way to add the new element into the dropdown options without refreshing the window?
Yes, via AJAX -!
Here is what I'm going to walk you through:
1). the window that opens displays a form, which adds a destination to your database.
2). A timer-script will wait for the window to close, and fetch the new destino and add it to your menu.
3). You'll need to add in the server-side script that handles the JS's request...
So-! first, you'll want to take that 'onClick' out, and handle your JS in a separate place -
Let's start by changing:
<input type="button" value="..." onClick="window.open([...]
to:
<input type="button" id="newDestino" />
Now, in your JS, you need to give it a click handler:
$("#newDestino").click(function(){
var desinoMas = window.open('/index.php/usuario/destinos/add','Nuevo Destino','width=800,height=600');
var windowCloseChecker = setInterval(function() {
if (win.closed) {
clearInterval(timer);
addDestino();
}
}, 1000);
});
The part where you do <?php echo base_url() ?> is not necessary - just use the absolutepath: '/index.php'
--- If i am missing something, and it is really necessary - just throw the script toward the bottom of the page in a <script> tag, and use your <?php echo like normal
So now, let us define our addDestino function:
function addDestino(){
$.ajax({
url : "index.php/usuario/destinos/updateClientMenu",
method: "POST" // this is really irrelevant,
success: function(response){
$("#origen0").html(response);
}
});
}
You'll see that I named the script index.php/usuario/destinos/updateClientMenu -- you can name it whatever you want, but that script needs to generate some simple html to add to your DOM.
You can get away with the following code, which should be quite familiar to you-!
<?php
//[...] You'll obviously need to re-query for the destinos, here.
foreach($destinos as $row)
{ $response .= '<option value="'.$row->nombre.'">'.$row->nombre.'</option>'; }
echo $response;
?>
You noticed that I stored all the $destinos into a variable before echoing it.
Now, the echo $response feeds back into the success function in our addDestinos function-!! - which simply takes that response and replaces the html of the menu, with the fresh HTML.
So, to clarify and wrap it up, it all goes something like this:
The button gets clicked, a new window opens with a form - when the form is filled out, it submits to create a new destino. When the window closes, a script notices the window is closes and asks the server for a new desinos menu. The server responds with a refreshed list of destinos.
NOW -! This script can be improved -!
So, I suggest you try it for yourself, as an exercise:
Instead of getting the whole list, just get the most recently added destino.
(You'll need to use $.append() instead of $.html() in this case )
Good luck -!
I'm thinking ajax is the best way to go here, you can try something like:
...
var addedData = $(this).closet('origen0').find('input_id').val();
$.ajax({
url: <?php echo base_url('index.php/usuario/destinos/add');?>,
type: 'POST',
data: addedDate
...
I have a php page which includes jQuery and a script.js file. When I put the following function inside my php file, the function gets executed and works as intended:
<script>
$('#scoreboard-overview').load('getusers.php?q=<?php echo $NewString; ?>').fadeIn("slow");
</script>
What does it do? Wel it reloads the div with id scoreboard-overview in my php file with data from an external php file called getusers.php
This all works great.
Now in the script.js file (which is loaded at the end of the php page, right before </body>), I also want to reload this div when the updatescore.php file is done updating the database via a form. I have this code for it:
$.ajax({
type: "POST",
data: $("#form").serialize(),
cache: false,
url: "updatescore.php",
success: function() { //reload overview
$('#scoreboard-overview').load('getusers.php?q=' + document.getElementById('str') + '').fadeIn("slow");
}
});
So after success it should execute the jQuery function:
function () { //reload overview
$('#scoreboard-overview').load('getusers.php?q='+document.getElementById('str')+'').fadeIn("slow");
}
I verified the code. The database gets updated using updatescore.php but after this (so after success), the div isn't refreshed. So this success part of code isn't working. What am I doing wrong?
ps: '+document.getElementById('str')+' should give me the same result as echo $NewString; only taken from the div with id str (since php doesn't work inside a js file?)
document.getElementById('str') is going to return the HTML element with the 'str' id, not the text within the element. I'm not sure what this element actually looks like, but you might do something like document.getElementById('str').textContent.
I was wondering what the best way was the handle creating a generic javascript function that makes an AJAX request and calling it with 'onclick', keeping in mind I need the loaded ajax results to still work with this function. Also, I'm using JQuery and PHP. Something along the lines of:
Like Post
<script>
function postLike(post_id){
$.ajax({
async:true,
dataType:"html",
position:"html",
success:function (data, textStatus) {
$("#post-"+post_id+"-like").html(data);
},
url: "domain\/likes\/like\/"+post_id
});
return false;
}
</script>
Doesn't seem to work for me though.
Thanks!
I'm not sure what your problem is, but this is how I would handle it. Note that this avoids the issue when the post id is alphanumeric since it appends it to the href and extracts it from there. Note that the it starts hidden and is displayed only if javascript is enabled (which is required to make it work anyway).
To find your problem you should consider adding an error handler and using Firefox/Firebug to view the requests (and responses) as they are made.
<a class="like" href="#<?php echo $post_id; ?>");" style="display: none'">Like Post</a>
<script type="text/javascript">
$(function() {
$('.like').show().click( function() {
var post_id = $(this).attr('href').replace(/^#/,'');
$.ajax({
async:true,
dataType:"html",
success:function (data, textStatus) {
$("#post-"+post_id+"-like").html(data);
},
url: "domain/likes/like/"+post_id
});
return false;
}
</script>
An alternative to support both javascript/non-javascript enabled browsers
Note: your backend code needs to be able to distinguish between AJAX and non-AJAX requests. Note you can do this using the X_REQUESTED_WITH header (HTTP_X_REQUESTED_WITH) added by jQuery when making AJAX calls. It is possible to spoof so be careful how you use this check -- like not basing any authentication or authorization decisions on it. When you get an AJAX request, just return the HTML snippet. For non-AJAX you'll need to render the entire page again.
<a class="like" href="/domain/likes/like/<?php echo $post_id; ?>");">Like Post</a>
<script type="text/javascript">
$(function() {
$('.like').show().click( function() {
var url = $(this).attr('href');
$.ajax({
async:true,
type: 'post', // technically it changes data so post is RESTful
dataType:"html",
success:function (data, textStatus) {
$("#post-"+post_id+"-like").html(data);
},
url: url
});
// cancel the default link action so we don't get two like's
return false;
}
</script>
The best way is binding functions to onclick (or .click in jQuery) event by jQuery .bind, .live or .delegate functions.
First of all if you are using jQuery, you don't need to use onclick attribute of anchor tag(it feels very obtrusive). try this syntax:
<a href="#" id="postLike" <other attributes>>Like Post</a>
<script type="text/javascript">
$('#posLike').click(function(){
$.ajax({
async:true,
dataType:"html",
position:"html",
success:function (data, textStatus) {
$("#post-"+post_id+"-like").html(data);
},
url: "domain\/likes\/like\/"+post_id
});
return false;
});
</script>
Here is what I normally do to fix this problem:
In your PHP, when you need to loop out the posts and generate the links, assign unique ids for the anchors, like this:
foreach ($posts as $post) {
echo "<a href='javascript://' class='like-anchors' id='like-post-{$post['id']}'>Like Post</a>";
}
Then in your JS code, you can do this:
$(document).ready(function() {
$('.like-anchors').click(function() {
var id = $(this).attr('id').substring(10);
$.get("domain/likes/like/"+id, function(data) {
$('#post-'+id+'-like').html(data);
});
});
});
Note
You are not making use of post or any advance Ajax functions. $.get should be enough. Feel free to comment on this.
Using href="javascript://" because I don't want the browser to scroll to top
Even better, you can just assign a global id to the wrapper div, so you won't exhaust your ids. Says if I have post, content, and like button, I would do this:
PHP
<?php foreach($posts as $post): ?>
<div class="post-body" id="post-<?php echo $post['id'] ?>">
<div class="post-content"></div>
<div class="post-controls">
Like This Post
</div>
</div>
<?php endforeach; ?>
JS
$(document).ready(function() {
$('.post-like').click(function() {
var parent = $(this).parent().parent();
var id = parent.attr('id').substring(5);
$.get("domain/likes/like/"+id, function(data) {
parent.children('.post-content').html(data);
});
});
});
There are many ways to complete the task. These are just my 2 cents
Cheers