Fetching data from database using PHP and AJAX - php

I want to fetch data from database using PHP and Ajax, which is first encoded into JSON.
But data is not printed properly on the screen. It shows elements of four rows in single line separated by comma.
$(document).ready(function() {
$(function()
{
$.ajax({
url: 'demo2.php',
data: "",
dataType: 'json',
success: function(data)
{
var name = data[0];
var email = data[1];
var msg = data[2];
var date1 = data[3];
$('#output').html("<div id='container'>" + name + " " + email + " " + msg + " " + date1 + "</div><br>");
}
});
});
});

Try this:
$(document).ready(function() {
$(function()
{
$.ajax({
url: 'demo2.php',
data: "",
dataType: 'json',
success: function(data)
{
console.log(JSON.stringify(data));
var obj = JSON.parse(data);
// Iterate object:
my_text=''
$.each(obj, function(index, value) {
console.log(value);
my_text += value
});
// var obj = JSON.parse('{ "name":"John", "email":"email#domain.com", "msg":"Hello"}');
$('#output').html("<div id='container'>" + my_text + "</div><br>");
}
});
});
});
Fiddle:
https://jsfiddle.net/fks3j500/

Related

Updating database table with AJAX on change

I'm trying to update a database column once an input field has changed.
however the code below just isn't doing it and am puzzled.
<script>
$("#addline1").change(function() {
var itemVal = $("#addline1").val();
var dataString = "companyid=" + companyid + "&addline1=" + itemVal;
processChange(dataString);
});
function processChange(dataString){
$.ajax({
type: "POST",
url: "../inc/dataforms/test.php",
data: dataString,
complete: function(data) {
var Resp = data.responseText;
console.log(Resp);
}
});
};
</script>
companyid is already defined elsewhere on the page.
I've tried change, onchange...
My PHP code is:
mysqli_query($dbc,"UPDATE `comp_companies` SET `regoffice1` = '$_POST[addline1]'
WHERE `company_id` = '$_POST[companyid]'");
Saying unexpected token (
somewhere in here
$("#addline1").change(function() {
var itemVal = $.("#addline1").val();
var dataString = "companyid=" + companyid + "&addline1=" + itemVal;
processChange(dataString)
});
I suggest you to use an object instead of a string... To pass the data, as the method used is POST.
(Assuming companyid is defined...)
<script>
$("#addline1").change(function() {
var itemVal = $("#addline1").val(); // Remove the extra dot that was here
// var dataString = "companyid=" + companyid + "&addline1=" + itemVal;
// I suggest the following:
var dataObj = {companyid:companyid, addline1:itemVal};
processChange(dataObj);
});
function processChange(dataObj){
$.ajax({
type: "POST",
url: "../inc/dataforms/test.php",
data: dataObj,
dataType: "json", // If you expect a json as a response
complete: function(data) {
var Resp = data.responseText;
console.log(Resp);
});
});
});
</script>

Loop through ajax response in jquery

I got the following ajax response.
{"ord_item_Json_string":"[{\"code\":\"1002\",\"item\":\"Diamond Softy\",\"size\":\"15 inch\",\"color\":\"Light Blue\",\"qty\":\"2\",\"price\":\"849.45\",\"amount\":\"1698.90\"},{\"code\":\"1001\",\"item\":\"sAMPLE\",\"size\":\"Cob\",\"color\":\"Naturtal\",\"qty\":\"5\",\"price\":\"434.05\",\"amount\":\"2170.25\"}]"}
now the problem is that i want to display only code and item fields & value but i am unable. please help me how to access that fields.
my code is following.
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (data) {
$("#OrdItem").html(data);
console.log(data);
return true;
},
error: function () {
alert('Not Working');
$('#ord_buyer_pack_inst').empty();
}
});
Try this:
var abc = {"ord_item_Json_string":"[{\"code\":\"1002\",\"item\":\"Diamond Softy\",\"size\":\"15 inch\",\"color\":\"Light Blue\",\"qty\":\"2\",\"price\":\"849.45\",\"amount\":\"1698.90\"},{\"code\":\"1001\",\"item\":\"sAMPLE\",\"size\":\"Cob\",\"color\":\"Naturtal\",\"qty\":\"5\",\"price\":\"434.05\",\"amount\":\"2170.25\"}]"}
var a = JSON.parse(abc.ord_item_Json_string)
$.each(a, function(index,value){
console.log(value.code+'--'+value.item)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
try the code below...in success callback you will be getting data in json object format. so just get value using its key.
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (jsonResponse) {
var itemsList = jsonResponse.ord_item_Json_string;
$.each(itemsList, function (index, value) {
console.log(value.code + '--' + value.item);
});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
try this: you can try below code where you can iterate over json array and read each attribute
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (data) {
var dataStr = "";
var jsonData = data.ord_item_Json_string; // this is already json
jsonData = JSON.parse(jsonData);//value need to parse
for (var i = 0; i < jsonData.length; i++) {
var ord= jsonData[i];
console.log(ord.code);
dataStr += ord.code;
}
$("#OrdItem").html(dataStr);
console.log(data);
return true;
},
error: function () {
alert('Not Working');
$('#ord_buyer_pack_inst').empty();
}
});
JSFiddle

Got Twice trigger on change paste keyup

So i have scanner and input text, if scanner get value max 9 digit, is will insert ot my database (automacly). These my coding
$(window).load(function(){
$( "#scannerinput" ).focus();
$('#scannerinput').bind("change paste keyup", function(){
var barcode = $(this).val();
var judul = $(this).attr("target-judul");
var dataString = "judul=" + judul + "&barcode=" + barcode;
if(this.value.length ==9){
$.ajax
({
type: "POST",
url: url+"ajax",
data: dataString,
cache: false,
success: function(data)
{
//window.location.href = url;
}
});
$( "#scannerinput" ).blur();
//console.log(dataString);
}
});
});
My problem is my code make insert twice or get trigger twice. How to make it just once trigger??? Any idea??
add array of exist data:
var exists_dataString_arr=[]; //array of exist data
$(window).load(function(){
$( "#scannerinput" ).focus();
$('#scannerinput').bind("change paste keyup", function(){
var barcode = $(this).val();
var judul = $(this).attr("target-judul");
var dataString = "judul=" + judul + "&barcode=" + barcode;
if((this.value.length ==9)&&(exists_dataString_arr.indexOf(ataString)<0)){ //if not in array
$.ajax
({
type: "POST",
url: url+"ajax",
data: dataString,
cache: false,
success: function(data)
{
//window.location.href = url;
exists_dataString_arr=[];
}
});
exists_dataString_arr.push(dataString); //add data in array
$( "#scannerinput" ).blur();
//console.log(dataString);
}
});
});

How to pass array back to PHP using Ajax [duplicate]

Is it possible to work with a response from AJAX request in PHP? I am not really a JS dev so i am polling my hair out with this one.
I have sort of hacked this together:
var base_url = 'http://dev.local/westview/public';
$('select.child_id').change(function() {
var child_id = $('#child_id');
var dataString = 'child_id=' + child_id;
$.ajax({
type: "POST",
url: base_url + "/finance/payment-history",
data: dataString,
dataType: 'html',
success: function(html) {
alert(html);
},
});
return false;
});
The function appears to work ok, it gives me an alert with the correct data.
{"payments":[{"id":"19","child_id":"21","club":"Breakfast Club","term":"Half Term 3","amount":"15.00","pdate":"2015-02-25","notes":"","created_at":"2015-02-11 12:16:32","updated_at":"2015-02-11 12:16:32","starting_debt":"0","debt_start_date":"2015-01-05"},{"id":"20","child_id":"21","club":"After School Club","term":"Half Term 3","amount":"11.50","pdate":"2015-02-25","notes":"","created_at":"2015-02-11 12:16:49","updated_at":"2015-02-11 12:16:49","starting_debt":"0","debt_start_date":"2015-01-05"}]}
I need to be able output this to the user so that it is readable. A lot of guides I find describe replacing data but as it stands there is no data until a child_id is selected.. i then want it show the above data in a readable way.
I have no idea how to start working with the data in my view file(php).
Thanks
[EDIT]updated with working code:
var base_url = 'http://dev.local/westview/public';
$('select.child_id').change(function() {
var response = "";
var child_id = $('#child_id').val();
var dataString = 'child_id=' + child_id;
$.ajax({
type: "POST",
url: base_url + "/finance/payment-history",
data: dataString,
success: function(response) {
var json_obj = $.parseJSON(response);
var output = "<ul>";
for (i=0; i < json_obj.payments.length; i++)
{
var payment = json_obj.payments[i];
var date = moment(payment.pdate).format('Do MMM YYYY');
output += "<li>£" + payment.amount + " - " + date + " (" + payment.club + ")</li>";
}
output += "</ul>";
$('.history-section').html(output);
},
dataType: "html"
});
});
Do like this.
var data = $.parseJSON("your_json");
var output= "<ul>";
for (i=0; i < data.payments.length; i++){
output += "<li>" + data.payments[i].id + ", " + data.payments[i].child_id + "</li>";
}
output += "</ul>";
use
dataType: 'json',
instead
dataType: 'html',
and then use each to fetch the record from response in success function
Use $.parseJSON() For Convert Json Format Data To Array
Right code at sucess of ajax..
Like,
var data = $.parseJSON(html);
data in you get array format of responce
You need to use json_encode() in your php file to send the data back as an array
For example;
$myarray = array("data1"=>"value1","data2"=>"value2");
echo json_encode($myarray);
You can then access the data separately in the js file like this;
success: function(html) {
alert(html.data1);
alert(html.data2);
},
You also need to change the dataType to 'json'
$('input[name=\'product_attribute[' + attribute_row + '][name]\']').catcomplete({
delay: 0,
source: function(request, response) {
$.ajax({
url: 'index.php?route=catalog/attribute/autocomplete&token=<?php echo $token; ?>',
type: 'POST',
dataType: 'json',
data: 'filter_name=' + encodeURIComponent(request.term),
success: function(data) {
response($.map(data, function(item) {
return {
category: item.attribute_group,
label: item.name,
value: item.attribute_id
}
}));
}
});
},
select: function(event, ui) {
$('input[name=\'product_attribute[' + attribute_row + '][name]\']').attr('value', ui.item.label);
$('input[name=\'product_attribute[' + attribute_row + '][attribute_id]\']').attr('value', ui.item.value);
return false;
}
});
You Can map your json something like this

Get the json encoded data to ajax success

I have a php file with encoded json. What I would like to do is to get each data(maxVote and Id) from encoded json
Here is my php file named results.php
<?php
$result = array();
array_push($result,array("maxVote"=>300,"id"=>"li_2"),array("maxVote"=>200,"id"=>"li_1"));
echo json_encode($result);
?>
Since I am new to ajax and json,
what are the codes to put on success so that i will get each maxVote's and each id's
$.ajax({
url: "results.php",
success: function(){
...
}
});
Thanks in advance!
You can use:
$.ajax({
dataType: "json",
url: 'results.php',
success: function(data){
var items = [];
$.each(data, function(key, val) {
items.push(key + ' : ' + val + '</br>');
});
$('body').append(items.join(''));
}
});
or
$.getJSON('results.php', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key + ' : ' + val + '</br>');
});
$('body').append(items.join(''));
});
Add the data parameter to your success function:
$.ajax({
url: "results.php",
success: function(data){
$.each(data, function(id, elt) {
// use data[id].maxVote or elt.maxVote
}
}
});

Categories