not working combobox in IE8 - php

I used tje following code to populate a combobox with data. It works in Firefox and Google Chrome but not in IE8.
$.ajax({
type: "POST", url:"reg/data/data.php",
data: {
cat:"Y",
//toUser: "4",
// ignoreMessages:"1
},
success: function(data){
$.each(data, function (i, elem) {
$('#catogery').append( new Option(elem.id) );
//console.log(elem);
});
}
});
PHP:
$result = mysql_query("SELECT DISTINCT CATCODE from subjectmaster");
$messages;
header('Content-type: application/json');
$return_arr = array();
while($row = mysql_fetch_array($result)) {
$row_array['id']=$row[0];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);

Remove the comma from after the cat:
$.ajax({
type: "POST", url:"reg/data/data.php",
data: {
cat:"Y"
},
success: function(data){
$.each(data, function (i, elem) {
$('#catogery').append( new Option(elem.id) );
//console.log(elem);
});
}
});

You have mentioned "," in data array and there is no element after that. Remove "," and it should work.
data: {
cat:"Y", //<------Remove this comma
//toUser: "4",
// ignoreMessages:"1
}

Related

Problem with json data source on ui autocomplete

I have a problem with my code. I receive data via ajax and it works, but the problem is that when I try to search for an element and all the elements appear so the search does not work properly.
JS code :
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
PHP code :
$data = array();
while($line = mysqli_fetch_object($liste_grp) ){
$data[] = array("label"=>$line->grp_nom,"value"=>$line->grp_nom ,"id"=>$line->groupement_id);
}
echo json_encode($data);
result
you should send the text you are searching for to ajax request so your autocomplete function should be
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque ,
term: request.term
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
request.term is your search text and in your example it is group text
and also you need to modify your mysql query and add condition (like)
for example
$rs = mysql_query("SELECT * FROM table WHERE colum LIKE '%" . $_POST['term'] . "%'");
and finally you can check https://jqueryui.com/autocomplete/#remote-jsonp
I would advise the following jQuery:
$( "#grp_name" ).autocomplete({
source: function(request, response) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id: request.term
},
success: function( data ) {
console.log(data);
response(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
This is a small change. This will send the request.term to your PHP Script. For example, if the user types "gro", this will be sent to your script and would be accessed via:
$_POST['marque_id']
This would assume your SQL Query is something like:
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column LIKE '?%'");
$stmt->bind_param("s", $_POST['marque_id']);
$stmt->execute();
$liste_grp = $stmt->get_result();
$data = array();
while($line = $liste_grp->fetch_assoc()) {
$data[] = array(
"label" => $line['grp_nom'],
"value" => $line['grp_nom'],
"id" => $line['groupement_id']
);
}
$stmt->close();
header('Content-Type: application/json');
echo json_encode($data);
This uses the MySQLi Prepared Statement, and will help prevent SQL Injection. I also included the JSON Header as good practice. The result of search "gro" would be something like:
[
{
"label": "GROUPE DATAPNEU TEST",
"value": "GROUPE DATAPNEU TEST",
"id": 1
}
];
Thanks guys i found a solution it works better
i used tokeninput with many options
http://loopj.com/jquery-tokeni
$.ajax({
url:"ajax_get_societe_authorisation",
method:"POST",
scriptCharset: "iso-8859-1",
cache: false,
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
console.log(data);
$("#soc_name").tokenInput(data
,{
tokenLimit: 1,
hintText: "Recherche une société par son nom",
noResultsText: "Aucune société trouvé",
searchingText: "Recherche en cours ...",
onAdd: function (data) {
$("#soc_id").val(data.id);
},
onDelete: function (item) {
$("#soc_id").val("");
}
}
);
}
});

jQuery -> AJAX -> PHP

I've been searching and searching, but unfortunately I can't find any answers that relates to my problem.
I'm having trouble to read data that I've sent through jQuery (ajax) in my PHP script.
jQuery:
$('.sendOrder').click(function(){
if (validateForm() == true) {
(function($){
var convertTableToJson = function()
{
var rows = [];
$('table#productOverview tr').each(function(i, n){
var $row = $(n);
rows.push ({
productId: $row.find('td:eq(0)').text(),
product: $row.find('td:eq(1)').text(),
size: $row.find('td:eq(2)').text(),
price: $row.find('td:eq(3)').text(),
quantity: $row.find('td:eq(4)').text(),
});
});
var orderObj = [];
orderObj.push({
name: $("#customerName").val(),
email: $("#customerEmail").val(),
phone: $("#customerPhone").val(),
order: rows
});
return orderObj;
console.log(orderObj);
}
$(function(){
request = $.ajax({
url: 'shop/sendData.php',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(convertTableToJson()),
success: function(ret) {
console.log(ret);
}
});
When I'm looking at Chrome it seems to be sent correctly with json:
[
{
"name":"Kristian",
"email":"kristian#example.com",
"phone":"12345678",
"order":[
{
"productId":"Prod #",
"product":"Produkt",
"size":"Str",
"price":"Pris",
"quantity":"Antall"
},
{
"productId":"09",
"product":"Bokser",
"size":"2 meter (249kr)",
"price":"249,- eks mva",
"quantity":"1 stk"
},
{
"productId":"09",
"product":"Bokser",
"size":"2 meter (249kr)",
"price":"249,- eks mva",
"quantity":"1 stk"
}
]
}
]
In my sendData.php I've got it pretty plain:
<?PHP header('Content-Type: application/json');
echo json_encode($_POST);
The return I'm getting are:
[]
What am I doing wrong? What have I forgotten?
$_POST expects an identifier. In your AJAX you'll have to supply one, for example:
request = $.ajax({
url: 'shop/sendData.php',
type: 'POST',
dataType: 'json',
// note the change here, adding 'json' as the name or identifier
data: { json: JSON.stringify(convertTableToJson())},
success: function(ret) {
console.log(ret);
}
});
Then you should be able to see the JSON string in $_POST['json']
Solved by using file_get_contents("php://input") instead of post.
I.e
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params)) {
$decoded_params = json_decode($json_params);
echo $decoded_params[0]->name;
}
Returned "Kristian"

How do i get a single value from a row in my datatable

I am using the jquery plugin DATATABLE.
I want to get a single value from a selected row in my datatable (the ID) but i dont how to do so. The value should be saved and given to a textbox.
Here is my Code:
var oTable = $('#dataTable').dataTable();
$.ajax({
url: 'process.php?method=fetchdata',
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
]);
}
},
error: function(e){
console.log(e.responseText);
}
});
$('#dataTable tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
oTable.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
Hopefully someone can help me!
in php:
$id = $_POST['id'];
$row = mysql_query("select * from _yourtable_ where id='$id'");
...
in the js:
You must send id to the file process.php by POST or GET method:
id = $('#textBoxSelector').val();
$.ajax({
url: 'process.php?method=fetchdata&id='+id,
method: 'post',
dataType: 'json',
success: function(s){
console.log(s);
...
}
});

getting data from PHP file with json is failing

I can't get each data from PHP file, i'm always having AJAX failure, i tried many things, and looked for some pages for this problem but i can't find any solution, this is where i came last.
This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="someclass"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
e.preventDefault();
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM table WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$jsondata1 = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
echo json_encode($jsondata1);
}
mysqli_close($con);
I think there is no need to share HTML file, but if you want i can share with you.
Thank You!
You are overriding the array value in the loop and echo $jsondata1, so you are sending many different arrays with the echo inside the loop, try this code:
$jsondata1 = array();
while($row = mysqli_fetch_array($result)) {
$jsondata1[] = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
}
echo json_encode($jsondata1);
e.preventDefault(); is a problem. e is not defined and if it was the default action would have already occurred by the time the success function was called. Try
$('a[class="someclass"]').click(function(e){
e.preventDefault();
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
You need to encode the complete response.
when you echo each encoded it will not work.
Do something like
$jsonArray = array();
while(){
array_push($jsonArray, array($row['data1'], $row['data2']);
}
echo json_encode($jsonArray);
You're calling json_encode multiple times when what you need to be doing is assigning those intermediate variables to an array and encode that array using json encode for the return.
PHP:
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM table WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
$jsondata1 = [];
while($row = mysqli_fetch_array($result)) {
$jsondata1[] = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
}
mysqli_close($con);
die(json_encode($jsondata1));
JavaScript:
$(document).ready(function () {
var doc = $(document);
doc.on('click', 'a.someclass', function(e){
e.preventDefault();
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});

Array size is always 1 in ajax

I have a function which gets the value of each checked checkbox i was able to get the value successfully by using an alert example it results to 1,2,3 which is correct but when i get it from php the array size is always 1.
HTML CODE:
function doit() {
var p = [];
$('input.cb').each(function () {
if ($(this).is(':checked')) {
p.push($(this).attr('rel'));
}
});
$.ajax( {
url:'page.php',
type:'POST',
data: {list:p},
success: function(res) {
alert(res);
}
});
alert(p)
}
PHP CODE:
<?php
$list = $_POST['list'];
echo count($list);
?>
Use this code :
var jsonData = JSON.stringify(p);
$.ajax( {
url:'page.php',
type:'POST',
data: {list:jsonData},
success: function(res) {
alert(res);
}
});
And in PHP :
$list = json_decode($_POST['list']);

Categories