Unable to post variables with jquery post [duplicate] - php

This question already has answers here:
Unable to post variables with jquery post()
(2 answers)
Closed 9 years ago.
I am trying to pass variables from a modal form to another page. I declare the variables from the form with the id tags in each selection.
Page reloads to test.php, however no variable can be echoed.
javascript
var id = $( "#id" ),
name = $( "#name" )
$.post("jqtest/test.php", { device_id: "id", device_name: "name" });
load('jqtest/test.php');
test.php
echo $_POST['device_name'];
echo $_POST['device_id'];

var id = $( "#id" ), name = $( "#name" )
/*
if have tag like <input id='id' value='ABC'> and want to get ABC , $( "#id" ).val();
if have tag like <div id='id' >ABC</div> and want to get ABC,$( "#id" ).html();
*/
$.post("jqtest/test.php", { device_id: "id", device_name: "name" });
/*
after get id and name , need
$.post("jqtest/test.php", { device_id: id, device_name: name });
*/
load('jqtest/test.php');
/*
useless delete this line
if need callback, ref:
$.post("test.php", { name: "John", time: "2pm" })
.done(function(data) {
alert("Data Loaded: " + data);
});
*/

You do not call load to get the contents of the post!
$.post("jqtest/test.php", { device_id: "id", device_name: "name" }, function (data) {
//handle the response here
console.log(data);
});
Also the use of load like that is wrong, unless you are calling some sort of function.
Edit,
Based on your comments, the echo does not work since you are loading a NEW page, you are not dealing with the post code in the Ajax request. If you want to navigate to the page the form submits to, than submit an actual form! You are using Ajax wrong.

Related

Datatables - filter sql query by bootstrap-datepicker values

I have 2 bootstrap datepickers(#start,#end) and a Datatable which returns 150.000 rows from MS SQL Server via PHP.I want by default the start date to be 7 days earlier nad the end date to be Today.
I need to find a way to filter the Sql Query (in a PHP file) with WHERE condition between #start and #end datepicker values.If i use no filter the returned JSON is 60 MBs which freezes the browser and consequently i can't even filter the Datatable in the client.
I have already used $.fn.dataTable.ext.search.push to filter the Datatable on the client and it works ,but i want to filter the JSON output from the Sql Query before it returns to the browser.
How can i dynamically pass these date values via ajax.url in the Sql Query which is in the backend PHP file?
var curdate = moment().subtract(7, 'day').toDate();
$( '#end' ).datepicker( 'setDate', new Date() );
$( '#start' ).datepicker( 'setDate', curdate );
var start = $('#start').val();
var end = $('#end').val();
$("#start").datepicker({ language: 'el', autoclose: true,
onchangeDate: function () {
var start = $('#start').val();
table.ajax.url('queries.php?q=employees_full&start='+start'&end='+end); //do i miss a + here??
//table.ajax.reload();
table.draw(); }});
$("#end").datepicker({ language: 'el', autoclose: true,
onchangeDate: function () {
var end = $('#end').val();
table.ajax.url('queries.php?q=employees_full&start='+start'&end='+end); //do i miss a + here??
//table.ajax.reload();table.draw(); }});
$('#start, #end').change(function () {
//table.ajax.url('queries.php?q=employees_full&start='+start+'&end='+end);
// table.ajax.reload();
table.draw();
});
1)What is the difference between table.ajax.reload() and table.draw ?
2)i also get an error in JSON output"Conversion failed when converting date and/or time from character string." .Probably the #start datepicker value is undefined,i don't know why??
3)Is the order of the commands right?
4)The dates in the Datepicker are in Format dd/mm/yyy but in the Sql Query queries.php?q=employees_full are in Format yyyy-mm-dd.I use prepared statements and have used the following:
(CONVERT(date,SUBSTRING(CONVERT(varchar, ?, 100), 4, 3) +SUBSTRING(CONVERT(varchar, ?, 100), 1, 3)+SUBSTRING(CONVERT(varchar, ?, 100), 7, 4)))
AND
$stmt = sqlsrv_prepare( $conn, $sql , array(&$_GET["start"],&$_GET["start"],&$_GET["start"]));
The Datatable is :
var table = $('#example').DataTable({
//"serverSide": true,
"ajax" : { url: 'queries.php?q=employees_full&start='+start'&end='+end ,
dataType: "json",
dataSrc: '' },
"order": [[ 5, "desc" ]],
"autoWidth": true,
"deferRender": true ,
"columns": [
{ "data": "username", "title": "Username" }]
});
EDIT 15/3/19
After a lot of research,i ended up to this.
I initialize the bootstrap datepickers and with the ajax.data option i pass the parameters(date objects) to the php Sql Query.
1)Is it better to pass the parameters as date objects instead of strings so that the conversion and comparison in the Sql Query is easier?
2)Should the initialisation of the Datepickers be before or after the Datatable?
3)Should i use 2 events .change and .on('changedate') for the datepickers so that both values to have been set before the initialisation of the datatable?
When i load the page , I get error : input1 is not defined
and after that when i pick different dates,i get TypeError: table is undefined.
I still can't find the right order of the commands i should use.
Any help would be appreciated!
var curdate = moment().subtract(7, 'day').toDate();
$("#start,#end").datepicker({ language: 'el', autoclose: true});
$( '#end' ).datepicker( 'setDate', new Date() );
$( '#start' ).datepicker( 'setDate', curdate );
$('#start, #end').datepicker({ language: 'el', autoclose: true}).change(function () {
//var thisval = this.value; //this.val--> undefined
var start= $( '#apo' ).datepicker( 'getUTCDate' );// returns datetime object
var end= $( '#ews' ).datepicker( 'getUTCDate' );// returns datetime object
var input1={ startdate: $( '#start' ).datepicker( 'getUTCDate' ),
enddate: $( '#end' ).datepicker( 'getUTCDate' ) };
//table.ajax.url("queries.php?q=employees_full"); //do i need this?
//table.ajax.reload(); //or table.draw();
});
var table = $('#example4').DataTable({
"ajax" : { url: "queries.php?q=employees_full" ,
dataType: "json",
dataSrc: '' ,
data: input1 },
......});
In the PHP Sql Query queries.php?q=employees_full i prepare the statement with
... WHERE alldates.alldate >= (CONVERT(date, ?)) and alldates.alldate <= (CONVERT(date, ?))
and
$stmt = sqlsrv_prepare( $conn, $sql , array(&$_POST["startdate"],&$_POST["enddate"]));
What am i missing?

Parsing in jQuery Autocomplete

I have generated some data from a MySQL query that I want to do two things with. The data is an array of names and IDs.
First I want to use the name portion for a jQuery autocomplete, so that the name is what you can select in the field.
Secondly, I want to fire on select in the autocomplete something that will place the ID of the selected item into a hidden field.
Here is my JQuery:
$("#contact").autocomplete(
source: function(request, response){
$.ajax({
url: "ajax/grabdata.php?",
type: "GET",
data: request,
success: function (data) {
response($.map(data, function (el) {
return {
label: el.item.name,
value: el.item.id
};
}));
}
});
},
width: 260,
matchContains: true,
selectFirst: false,
select: function(event, ui){
$('#contact').val(ui.label);
$('#id').val(ui.value);
}
});
Here is how I grabbed the data in PHP (grabdata.php):
$sql = "SELECT DISTINCT contacts.id, contacts.firstname, contacts.lastname FROMcontacts WHERE (firstname LIKE '%$q%' OR lastname LIKE '%$q%')";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
$kdata[] = array(
"name" => $rs['firstname'].' '.$rs['lastname']."\n",
"id" => $rs['ID']."\n",
);
$dataset[] = $kdata;
}
I can get the data, but I am having trouble parsing it into what I want. The name should be selectable in the autocomplete field, and the ID should be filled in based on the name chosen.
As far as I can see, you are not using the select method parameters as you should:
select: function(event, ui){
$('#contact').val(ui.item.label);
$('#id').val(ui.item.value);
}
You are missing the ".item". Check the documentation: http://jqueryui.com/autocomplete/#remote

Assign data to a variable in jquery

I have this code,
$(function() {
//var asd = '<?php $regions_list_full; ?>';
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
//icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
//icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
//icon: "sizzlejs_32x32.png"
}
];
$( "#find" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#find" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#find" ).val( ui.item.label );
//$( ".module h1" ).val( ui.item.value );
$(":header.title").html(ui.item.value);
//$( "#project-description" ).html( ui.item.desc );
//$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
actually this is from the autocomplete of jQueryUI, and I have an array of values which are fetched from the database. What I want is to replace my values into the var projects =[{value:asd}] such that my suggestions of the autocomplete will be the data from the database. How would I do this?
You don't want to use source: projects you probably want to define a function for the source using an AJAX call like this
$( "#search_address" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: '/path/to/script',
dataType: 'json',
data: 'whatever you need here', // i.e. term value
dataFilter: function (data, type) {
// do whatever you need to here to change data into proper autocomplete array format
// if JSON data is already in correct format you can just do this.
response($parseJSON.(data));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// handle error here
},
success: function(data) {
// maybe check for case of empty data object here (i.e. successful URL request, but no data returned)
return data;
}
});
}
});
Now you typically want to limit the number of results returned by your API (maybe 10 or 20 records at most), as it is likely a bad UI experience to have 1000 items show up in autocomplete. On a good autocomplete the number of results should decrease dramatically after a few letters have been types in. This also make you script perform much better in that you are only processing a handful of returned records. For the same reason, you may also want to use the minLength property of autocomplete to not even bother starting the request until X number of characters are entered.
Change
source: projects,
to
source: url_to_script
Form which script you'll send your json. See this example. If you see the source code, you'll see that in source property they use source: search.php.
Similarly, you can use your own script path and return a json data from that script, where that data will coming from server.
jQuery autocomplete will send a a querystring along to the url that you provide in the source: url , this query string will be term so remember that , because I don't think autocomplete docs tell you that , then from there you use the term querysting to query the database and send back items that start with term , You do not request every row in the database and store them in javascript variable, that would not make sense - what if there are 2,000,000 entries in the database?

Pass existing php array to jquery

I have a PHP array I want to pass to my jquery (replace the test array with my php array).
Array
(
[12] => Some Text
[6] => Another text
[11] => one more text
)
Jquery:
$('#SearchUser').typeahead({
source: [
{ ID: 1, Name: 'Toronto' },
{ ID: 2, Name: 'Montreal' },
{ ID: 3, Name: 'New York' },
{ ID: 4, Name: 'Buffalo' },
{ ID: 5, Name: 'Boston' },
{ ID: 6, Name: 'Columbus' },
{ ID: 7, Name: 'Dallas' },
{ ID: 8, Name: 'Vancouver' },
{ ID: 9, Name: 'Seattle' },
{ ID: 10, Name: 'Los Angeles' }
],
display: 'Name',
val: 'ID',
itemSelected: updateID
});
So how can I set the var for "source" to my php array?
Suggestions?
As always,, you are awesome!
-Tom
How I'd done it in one of my projects was,
$.get("<?= $baseUrl ?>search/data", function (data) {
var dataObject = JSON.parse(data);
$('#q').typeahead({
'source': dataObject,
// 'items': 5
});
});
and my search controller's data method is:
echo (json_encode($arr)); // $arr is ["a","b","c"] etc. but you can have an associated array too.
Basically, the point of showing my code is to say use json
You can use json_encode function of php to conver a php array to json. Then you can use the json as javascript array.
http://www.php.net/manual/en/function.json-encode.php
I don't know how you get data from php code to javascript code, but if you print data as json, you can take it via an ajax call.
Use PHP's json_encode() function to create a string that is a valid JSON, and then read that with jQuery's $.getJSON().
Something like this:
get_array.php
$someArray = /* whatever */;
echo json_encode($someArray);
read_array.js
$.getJSON('get_array.php', function(data) {
// data now contains your array
});
Alternatively, you could do something like this:
<script type="text/javascript">
var someArray = <?php echo json_encode($someArray); ?>
</script>
If you don't want the separate files and don't mind using a global variable for it.
You can do the following:
<script type="text/javascript">
var jsArray = <?php echo json_encode($phpArray); ?>
</script>
but it is a bad practice to mix language X with language Y.
Well, take a look at my answer to this post in which you can do the following in a better way:
Is echoing Javascript code condtionally based on server-side logic considered harmful?
Hope this helps :-)

JQueryUI Autocomplete - Trigger on all events

I'm using JQuery UI Autocomplete to pull records from a caller database. This works fine for records that are in the database but I want to improve handling for new records.
For example, if a user chooses a name from a suggestion, I use the return id later in the form. This works fine. If the value is not found in suggestions I am struggling to trigger the script since it is currently triggered from a select event, and there doesn't appear to be a onblur event for this function which I think is what I'm after. I'm new to JQuery and have already spent a day trying to sort it.
Code so far is:
$("#contact_name").autocomplete({
source: "get-caller-names.php",
minLength: 2,
select: function(event, ui) {
$('#contact_id').val(ui.item.id);
$('#contact_name').val(ui.item.name);
$('#contact_email').val(ui.item.email);
$('#contact_phone').val(ui.item.phone);
$('#contact_addr').val(ui.item.address);
}
});
All suggestions welcome, thanks.
Code in case others have the same issue...
// auto-suggest jqueryui
$("#contact_name").autocomplete({
source: "GetCallerNames.php",
minLength: 2,
select: function(event, ui) {
$('#contact_id').val(ui.item.id);
$('#contact_name').val(ui.item.name);
$('#contact_email').val(ui.item.email);
$('#contact_phone').val(ui.item.phone);
$('#contact_addr').val(ui.item.address);
},
change: function(event, ui) {
$.ajax({
type: 'GET',
url: 'GetCallerNames.php',
dataType: 'json',
data: {term:$(this).val()},
success: function(data) {
if (data!=null&&data!='') {
$('#contact_id').val(data[0].id);
$('#contact_email').val(data[0].email);
$('#contact_phone').val(data[0].phone);
$('#contact_addr').val(data[0].address);
}
}
});
}
});
Could you not add a new handler for change eg:
$( ".selector" ).autocomplete({
select: function(event, ui) { ... },
change: function(event, ui) { ... }
});

Categories