I have an Ajax Call when tab is clicked in bootstrap 3.0
Below is the JS code
$('[data-toggle="tab"]').click(function (e) {
var $this = $(this);
loadtab = $this.attr('href');
if(loadtab=="#odhis"){
var email = $("#email");
$.ajax({
type: "POST",
url: "../orders.php",
data: {'email':email.val()},
dataType: "json",
success: function(response){
console.log(response);
},
error: function(xhr, status, error){
console.log(xhr.responseText);
}
});
}
});
PHP file orders.php
function getCustomOrderHistory(array $data){
$cstm = array();
if( !empty( $data ) ){
$trimmed_data = array_map('trim', $data);
$mail = mysqli_real_escape_string( $this->_con, $trimmed_data['email'] );
$checktable = "SELECT * from `orders` WHERE csmail='$mail'";
$resultcstm = mysqli_query($this->_con, $checktable);
while($row = mysqli_fetch_array($resultcstm)){
$cstm[] = $row;
}
}
return $cstm;
}
Now, when i print_r($cstm) then it prints the results in PHP file.
but in JS success response is empty.
Any help please?
Since your dataType: "json", instead of return just encode the $cstm array and echo it, like this:
function getCustomOrderHistory(array $data){
$cstm = array();
if( !empty( $data ) ){
$trimmed_data = array_map('trim', $data);
$mail = mysqli_real_escape_string( $this->_con, $trimmed_data['email'] );
$checktable = "SELECT * from `orders` WHERE csmail='$mail'";
$resultcstm = mysqli_query($this->_con, $checktable);
while($row = mysqli_fetch_array($resultcstm)){
$cstm[] = $row;
}
}
$json = json_encode($cstm);
echo $json;
}
Related
I try to get some data from my MySql db. I have 2 files:
// client/book.js
$(document).ready(function () {
$("#btnJSonDB").bind("click", function () {
var request = $.ajax({
url: "book.php",
type: "GET",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
console.log(result);
}
}); //end ajax
request.fail(function( jqXHR, textStatus ) {
console.log("Request failed: " + textStatus);
});
}); //end click
}); //end ready
and server side:
// server/book.php
$db = new mysqli(DATA_HOST,DATA_UTENTE,DATA_PASS,DATA_DB );
$select = "SELECT * FROM bk_book";
$strJSon = "{\"book\":{}}";
$query = #mysqli_query($db,$select);
if( $query ) {
$result = [];
while($result[] = mysqli_fetch_array($query, MYSQLI_ASSOC));
#mysqli_close($db);
$strJSon = "{\"book\":" . json_encode($result) . "}";
}
echo $strJSon;
I try in my localhost space (windows-xampp) and all it's ok, In meteor I recive an error message:
Parse error
I try to comment datatype (json problem?) and I see the html page without my data.
The result is a correct json format:
{
"book":[
{
"nrent":"xxxxxx",
"start_date":"2017-01-05",
"end_date":"2017-01-12",
"user_ID":"15",
"booking_status":"estimate",
"note":"",
"adults_numb":"0",
"children_numb":"0",
"booking_bill":"630.00",
"name":"Camera Bi",
"first_name":"dddd",
"last_name":"ddd",
"mail":"dddd#dddd.it",
"telephone":"ddddddd"
},
{
"nrent":"fffff",
"start_date":"2017-01-08",
"end_date":"2017-01-27",
"user_ID":"25",
"booking_status":"active",
"note":"",
"adults_numb":"2",
"children_numb":"0",
"booking_bill":"1710.00",
"name":"Camera Ba",
"first_name":"pippo",
"last_name":"puppo",
"mail":"fff#pippfffo.it",
"telephone":"ffffff"
},
{
"nrent":"aaaaa",
"start_date":"2017-01-28",
"end_date":"2017-02-01",
"user_ID":"24",
"booking_status":"estimate",
"note":"",
"adults_numb":"0",
"children_numb":"0",
"booking_bill":"380.00",
"name":"Camera Ba",
"first_name":"ffff",
"last_name":"wwww",
"mail":"no#email.it",
"telephone":""
},
null
]
}
I try the https://jsonformatter.curiousconcept.com/ and is correct
$db = new mysqli(DATA_HOST,DATA_UTENTE,DATA_PASS,DATA_DB );
$select = "SELECT * FROM bk_book";
$jsonObject = new stdclass();
$query = #mysqli_query($db,$select);
if( $query ) {
$result = [];
while($result[] = mysqli_fetch_array($query, MYSQLI_ASSOC));
#mysqli_close($db);
$jsonObject->book = $result;
}
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($jsonObject);
I'm creating an ajax script to update a few fields in the database. I got it to a point where it worked but it sent the user to the php script instead of staying on the page so I did some googling, and people suggested using either return false; or e.preventDefault() however, if I do this, it breaks the php script on the other page and returns a fatal error. I might be missing something being newish to AJAX but it all looks right to me
JS:
$(document).ready(function() {
var form = $('form#edit_child_form'),
data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$('#submit_btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = ". $parent_id ." ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = $child_row[0]");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
it's probably something really small that I've just missed but not sure what - any ideas?
my solution:
I var_dumped $_GET and it returned null - changed to $_REQUEST and it got my data so all good :) thanks for suggestions
Try the following instead.
I moved the form data inside click and enclosed the mysql queries values in single quotes.
JS:
$(document).ready(function() {
var form = $('form#edit_child_form');
$('#submit_btn').on('click', function(e) {
e.preventDefault();
var data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'get',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = '". $parent_id ."' ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = '$child_row[0]'");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
You are using an AJAX POST request so in your PHP you should be using $_POST and not $_GET.
You can just change this:
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
to this:
$descriptions = $_POST['descriptions'];
$child_id = $_POST['child_id'];
$parent_id = $_POST['parent_id'];
Here is my ajax function in response I am getting result but I don't know how to set that response in my page. Is it possible with json_decode or I have to try something else
JSON file is
<?php
$group_id = $_POST['group_id'];
$query = "SELECT *,group_id FROM contact JOIN addressgroup ON addressgroup.contact_id = contact.contact_id WHERE group_id IN (".$group_id.") GROUP BY contact.contact_id";
$res = mysql_query($query);
$data = array();
$k=0;
while($row = mysql_fetch_array($res))
{
$data[$k][0] = $row['user_id'];
$data[$k][1] = $row['first_name'];
$data[$k][2] = $row['middle_name'];
$data[$k][3] = $row['last_name'];
$k++;
}
echo json_encode(array($data));
?>
AJAX function
var myarray;
function getcon() {
myarray = [];
myarray.push($(".group_id").val());
$.ajax({
dataType: "json",
type: "POST",
url: "getcon.php",
data: 'group_id=' + myarray.join(),
success: function(data) {
totalRecords=data.length;
zone.fnClearTable();
for(var i=0; i < (data.length); i++) {
zone.fnAddData([
data[k][0],
data[k][1],
data[k][2],
data[k][3],
]);
}
return false;
}
});
return false;
}
As your Response is an JSON object..
you have to use it like this:-
replace
echo json_encode(array($data));
by
echo json_encode($data); /* because $data is already an array*/
and keep it same as it was earlier
while($row = mysql_fetch_array($res))
{
$data[] = $row['user_id'];
$data[] = $row['first_name'];
$data[] = $row['middle_name'];
$data[] = $row['last_name'];
$k++;
}
<script>
var myarray;
function getcon() {
myarray = [];
myarray.push($(".group_id").val());
$.ajax({
dataType: "json",
type: "POST",
url: "getcon.php",
data: 'group_id=' + myarray.join(),
success: function(data) {
console.log(data)/* check the structure of data here*/
zone.fnClearTable();
zone.fnAddData([
data.user_id.,
data.first_name,
data.middle_name,
data.last_name,
]);
return false;
}
});
return false;
}
</script>
JSON is an object! Your are getting object, so in your ajax function You must use some loop function like for or $.each JQuery functions.
`success : function (data) {
$.each (data,function(key,val){
$("#someId).html(key + " - " + val)
}
}`
I'm trying to send a php form data via AJAX (without the refresh) and display data in new form. I echo query but it didnt work. On AJAX response it shows me getReportAj form on call.The code goes like this:
Javascript
function getReport()
{
var dataString = "grNo=" +$(".grNo").val();
$.ajax({
type: "GET",
url: "getReportAj.php",
data: dataString,
success:function(data)
{
$('#result').html(data);
}
});
}
getReportAj.php
<?php
include "include/config.inc.php";
if(!isset($_SESSION['s_activName']) && !isset($_SESSION['s_userType']) || isset($_SESSION['s_userType']) && $_SESSION['s_userType'] == 'Student') {
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
header("Location:checkLogin.php");
}
else {
if(isset($_REQUEST['submit'])) {
$selectReport = "SELECT * from gradeterm1
WHERE studentId = ".$_POST['studentId']."
AND termValue = 1
LEFT JOIN studentmaster ON studentmaster.studentId = gradeterm1.studentId";
$selectReportRes = mysql_query($selectReport);
if($reportRow = mysql_fetch_array($selectReportRes)); {
$eReadingPro = $reportRow['eReadingPro'];
$eReadingFlu = $reportRow['eReadingFlu'];
$eReadingCom = $reportRow['eReadingCom'];
$eWritingCre = $reportRow['eWritingCre'];
$eWritingHan = $reportRow['eWritingHan'];
$eWritingGra = $reportRow['eWritingGra'];
$eWritingSpe = $reportRow['eWritingSpe'];
$eWritingVoc = $reportRow['eWritingVoc'];
$ewSpeakinCon = $reportRow['ewSpeakinCon'];
$ewSpeakinRec = $reportRow['ewSpeakinRec'];
$ewSpeakinCla = $reportRow['ewSpeakinCla'];
$eListingComp = $reportRow['eListingComp'];
$eListingCon = $reportRow['eListingCon'];
$extraReading = $reportRow['extraReading'];
$activityPro = $reportRow['activityPro'];
$hiReadingPro = $reportRow['hiReadingPro'];
$hiReadingFlu = $reportRow['hiReadingFlu'];
$hiReadingCom = $reportRow['hiReadingCom'];
$hiWritingCre = $reportRow['hiWritingCre'];
$hiWritingHan = $reportRow['hiWritingHan'];
$hiWritingGra = $reportRow['hiWritingGra'];
$hiWritingSpe = $reportRow['hiWritingSpe'];
$hiWritingVoc = $reportRow['hiWritingVoc'];
$hiwSpeakinCon = $reportRow['hiwSpeakinCon'];
}
}
}
include("./bottom.php");
$smarty->display('getReportAj.tpl');
?>
<script>
function getReport()
{
var dataString = "grNo=" +$(".grNo").val();
$.ajax({
type: "GET",
url: "getReportAj.php",
data: dataString,
success:function(data)
{
$('#result').html(data);
console.log(data);
}
});
}
</script>
in success event.. put the console.log(data) then run the script and check in console.
Here's my php responding to my jQuery calls.
<?php
if ( isset( $_POST['icnumber']) && $_POST['icnumber'] != '' ) {
$custic = $_POST['icnumber'];
$response = array();
$response['status'] = 'false';
$sql ="SELECT * FROM ctrl_cust WHERE cust_ic='$custic'";
$raw = mysql_query($sql,$link) or die('Query 1 '.mysql_error());
if ( $data = mysql_fetch_assoc( $raw ) ) {
$response['status'] = 'true';
$response['custid'] = $data['cust_id'];
$response['custname'] = $data['cust_name'];
}
header("Content-Type: application/json", true);
echo json_encode($response);
}
?>
and here's the jQuery
$(function() {
$('#icnumber-form').submit(function() {
var icno = $('#icnumber').val();
$.ajax({
type : 'POST',
url : 'php/create_process.php',
data : icno,
dataType: 'json',
success : function(data){
console.log(data);
},
beforeSend:function(){
$('.cust-exist-view').fadeIn();
}
});
return false;
})
});
The thing is, console.log returns NULL, but when I submit the form without javascript enabled, it returns this :
{"status":"true","custid":"00001","custname":"John"}
I wonder what is the problem...I've been running around in circles for hours...Help me please?
icnumber is not getting post, change data: icno, to data: {icnumber: icno}, and try