sending already used variable via ajax - php

I'm using jquery datepicker on a page. Next to datepicker i have a section which will show events on mouseenter of the datepicker. I have figured out a way to get the date into the header of this section. The problem i am having is getting that variable over to the php page that will be displayed on mousenter.
Below is the page that the datepicker and events will be shown:
<div id=events>
<div id=eventcontent>
</div>
</div>
<div id=eventsheading>
<div id=headingcontent>
</div>
</div>
<div id = "datepicker">
</div>
This is the Jquery i am using to fill in the header with the date (which works), send the same variable to events.php (which doesnt work), and show events.php in the content div (which does work as when i highlight a date, hello is shown):
$(document).on('mouseenter', '.ui-datepicker-calendar .ui-state-hover', function(e){
var daynum1 = $(this).text();
var month1 = $('.ui-datepicker-month').text();
var year1 = $('.ui-datepicker-year').text();
var Date = daynum1 + " " + month1 + " " + year1;
$('#headingcontent').html(Date);
//ajax call with date information
var request = $.ajax({
url: "events.php",
type: "POST",
data: {Date: Date},
dataType: "html"
});
$.ajax({
url: "events.php",
cache: false,
success: function(html){
$("#eventcontent").append(html);
}
});
});
Below is events.php:
if(isset($_POST['Date']))
{
$date = $_POST['Date'];
echo <<<_END
<p>$date</p>
_END;
}
else
{
echo <<<_END
<p>hello!</p>
_END;
}
once i get this bit working, events PHP will be changed to select events from mysql.
To clarify, the problem i am having is getting variable date to send via ajax with this code:
//ajax call with date information
var request = $.ajax({
url: "events.php",
type: "POST",
data: {Date: Date},
dataType: "html"
});
i cant seem to find anywhere that explains how data: {...}, should be used and I'm guessing this is my problem.
Sorry if the code is just completely wrong i'm very new to learning it all and thanks for any help.

you must not use variable names which collide with inbuilt objects as #CBroe said.
and rest like this
var myDate = daynum1 + " " + month1 + " " + year1;
$('#headingcontent').html(myDate);
$.ajax({
url: "events.php",
type: "POST",
data: {myDate: myDate},
dataType: "html",
success: function(html){
$("#eventcontent").empty();
$("#eventcontent").append(html);
}
});
no need for second ajax call

Related

How to pass javascript variable value to php variable using ajax to store in session in codeighter

I am working in codeighther and want to pass my javascript variable value to php so that I can store it in session and then store to database.
Following is what I have tried so far.
<div id="wrapper">
<button id="detect-button">Detect Device</button>
</div>
<script>
$('#detect-button').ready(function() {
var detector = new MobileDetect(window.navigator.userAgent)
var test = document.write("Mobile: " + detector.mobile());
//document.write( "Phone: " + detector.phone());
//document.write( "Tablet: " + detector.tablet());
// document.write( "OS: " + detector.os());
// document.write( "userAgent: " + detector.userAgent());
});
$.ajax({
type: 'Post',
url: '<?php echo $base_url ?>Home/index',
data: ({
value: +detector.mobile()
}),
cache: false,
success: function(data) {
$('#results').html(data);
}
</script>
<p id="results"> </p>
you can pass you test varibale data like,
$.ajax({
type: 'POST',
url: '<?php echo $base_url ?>Home/index',
data: {field1 : test},
cache: false,
success: function(data) {
$('#results').html(data);
}
And you can fetch data in PHP like $_POST['field1']
For more details, please visit http://thisinterestsme.com/simple-ajax-request-example-jquery-php/
I would recommend you to make use of the $.post or $.get syntax of jQuery for simple cases.
Define detector as a global variable. Its current scope is restricting its use

How to use ajax to pass a variable to a php file using POST method?

I have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});

ajax post data and insert to database

I am trying to insert comment using ajax. Everything works fine except the $_POST. It doesn't seem to post the data so the comment field in table is empty. Other things work fine, like inserting date. I only have problem with the ajax (no problems in php).
Anyway, here is my code:-
<head>
<script>
function su_post(id) {
$("#load_post").show(),
$("#post_submit").click(function() {
var c_post = $("#c_post").val();
var dataString = '&c_post=' + c_post;
$.ajax({
type: "POST",
url: '/script/post.php',
data: "id=post_script" + id,
cache: false,
success: function(){
$("#load_post").fadeOut();
}
})});
};
</script>
</head>
<body>
<form id="form_post" method="post" action="javascript:su_post(1)">
<label for="c_post">Post your updates/status</label>
<input type="text" name="c_post" id="c_post" />
<br /><br /><input type="submit" id="post_submit" value="Post" />
</form>
</body>
edit: since you might not have understood me; there is a problem in obtaining the value you type in the input box and posting or sending the value to post.php. When I put data: {id: post_script + id, c_post: c_post}, it the code doesn't seem to load the php file at all. (gets stuck on posting -> http://prntscr.com/10dmjt)
Thank you in advance :)
The data property in your ajax() function needs to be of Object type. Like this:
data: { id: "post_script" + id }
You also had some syntax errors, your function should look like this:
function su_post(id) {
$("#load_post").show();
$("#post_submit").click(function() {
var c_post = $("#c_post").val();
var dataString = '&c_post=' + c_post;
$.post("ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val(),rand:Math.random() });
$.ajax({
type: "POST",
url: '/script/post.php',
data: { id: "post_script" + id },
cache: false,
success: function(){
$("#load_post").fadeOut();
}
});
});
}
You are calling the function javascript:su_post(1), so it would seem that your data field contains {id: "post_script1"} only. Where is your "comment" being passed to the AJAX? You don't do anything with the var dataString after assigning a value to it...
Maybe you intend to have something like this line:
data: "id=post_script" + id + dataString,
since, I think dataString contains &c_post=whatever the comment is after you did
var c_post = $("#c_post").val();
var dataString = '&c_post=' + c_post;
I do wonder whether you need some additional quoting in the dataString as well... I don't believe the $(#c_post).val() function takes care of it, so I suspect you need an escape() somewhere - or does the ajax do it for you? I guess that's where #errieman's {} comes in handy... it turns the entire thing into an object and takes case of the escaping for you. That would make the line you need:
data: {id: post_script + id, c_post: c_post}
I doubt any of this turns out to be exactly right, as I'm having to guess what you are trying to do - but I do hope one of these will give you inspiration to solve your problem.
It seems to have worked when I took out the statement $("#post_submit").click(function() and put var c_post = $("#c_post").val();var dataString = '&c_post=' + c_post; on the top.Now my code looks like this :-
function su_post(id) {
var c_post = $("#c_post").val();
var dataString = '&c_post=' + c_post;
$("#load_post").show(),
$.ajax({
type: "POST",
url: '/script/post.php',
data: {c_post:c_post},
cache: false,
success: function(){
$("#load_post").fadeOut();
}
});
};

Typeahead input field and query passed to PHP with AJAX

I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call

jQuery lightbox from database through PHP/Ajax forces to double click the first time

It's a weird issue. I've to click on certain buttons (having some ids). The id is passed through Ajax in a PHP script. That id is searched in the database, and the matching entries are passed as data in which is shown in my jQuery lightbox. However, I have to double-click on the button for the first time.
My HTML structure is as follows:
<div class="boxes">
Show it
</div>
<div class="boxes">
Show it
</div>
And the Javascript function is:
$('.button').click( function() {
$.ajax({
type: 'POST',
url: 'functions/db.php',
data: {id: this.id},
dataType: 'json'
}).done(function(data) {
$('#'+data[0]).avgrund({
//data [0] is both the id being clicked and that stored in the database
height: 200,
holderClass: 'custom',
showClose: true,
template: '<p>'+data[2]+'</p>' +
'<div>' +
''+data[0]+'' +
''+data[1]+'' +
'More' +
'</div>'
});
});
});
My relevant PHP script:
$id = $_POST['id'];
$result = mysql_query("SELECT * FROM `eventdetails` WHERE `id` = '".$id."'");
$array = mysql_fetch_row($result);
echo json_encode($array);
I'm running the files on an XAMPP server on Windows 7. Is it normal that I've to double click for the first time? How can I improve it?
EDIT #1
One of the users suggested of using success instead of done in Ajax. Still, it requires a double-click. Here's the javascript code using success in Ajax.
$('.button').click( function() {
$.ajax({
type: 'POST',
url: 'functions/db.php',
data: {id: this.id},
dataType: 'json',
success:(function(data) {
$('#'+data[0]).avgrund({
height: 200,
holderClass: 'custom',
showClose: true,
template: '<p>'+data[2]+'</p>' +
'<div>' +
''+data[0]+'' +
''+data[1]+'' +
'More' +
'</div>'
});
})
});
});
to init avgrund with ajax data set its special param called "openOnEvent" to "false"
it will look like
$.ajax({
type: 'POST',
url: 'testpost.php',
dataType: 'json',
data: { id: this.id },
success: function(id) {
$('#' + id).avgrund({
openOnEvent: false,
height: 200,
template: '<p>content <b>' + id + '</b> here!</p>'
});
}
});
docs - https://github.com/voronianski/jquery.avgrund.js#update-sep-30-2012
test page - http://labs.voronianski.com/test/test-avgrund.html

Categories