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
Related
I am calling a PHP service with below ajax code :
jQuery.ajax({
url: 'index.php?option=com_sheet&task=getReportsData',
timeout: 300000,
dataType: "json",
type: "GET",
data: {
'project': projectsStr,
'startweek': startweek,
'endweek': endweek
}
}).done(function(response) {
if (response.success && response.data) {
var projectData = response.data;
if (projectData.projectReportData.length > 0) {
loadDataTable(response.data);
} else {
jQuery('#projectReportData').html("<br/><h2>No Matching Results</h2>");
}
}
}).fail(function(jqXHR, textStatus) {
jQuery(".overlay")[0].style.display = '';
if (textStatus === 'timeout') {
alert('Failed from timeout');
}
alert(textStatus);
});
The php code that provides the response prints the response with :
$data = (object)array_merge(['projectReportData' => $projectReportData]);
header("Content-Type: application/json");
$post_data = json_encode($data, JSON_FORCE_OBJECT);
ob_start('ob_gzhandler');
echo new JResponseJson($data);
ob_end_flush();
jexit();
This ajax works fine sometimes and is able to parse the JSON. But most of the times gives "parsererror".
Below code fetch the data from the DB :
$db = JFactory::getDbo();
$query = "CALL getReportData('" . $startweek . "','" . $endweek . "')";
$db->setQuery($query);
$res = $db->query($query);
$returnArr = [];
$i = 0;
while( $r = $res->fetch_assoc()){
$projectReportData[$i] = $r;
$i++;
}
when i change dataType to text the pointer reaches the .done() but console.log(response) returns a blank.
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'];
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;
}
Here is my HTML
<input x-webkit-speech id="mike" name="string" style="position: relative;" disabled lang="ru" />
Then when the field is changes,
This function executes
$(document).ready(function(){
$('#mike').bind('webkitspeechchange',function()
{
a= $(this).val();
recognizeAjax(a);
}) ;
});
function recognizeAjax(string) {
var postData ="string="+string;
$.ajax({
type: "POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php',
success: function(data) {
// 'data' is a JSON object which we can access directly.
// Evaluate the data.success member and do something appropriate...
if (data.success == true){
alert(data.message);
}
else{
alert(data.message+'hy');
}
}
});
And here is my PHP (please don't say anything about the way i connect to DB it doesn't metter right now)
<?php header('Content-type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', true);
// Here's the argument from the client.
$string = $_POST['www'];
$quest=1;
$con=mysql_connect("localhost", "******", "*********") or die(mysql_error());
mysql_select_db("vocabulary", $con) or die(mysql_error());
mysql_set_charset('utf8', $con);
$sql="SELECT * FROM `text` WHERE event_name = 'taxi' AND quest_id = '".$quest."'";
$result = mysql_query($sql);
mysql_close($con);
while($row = mysql_fetch_array($result))
{
if ($string == htmlspecialchars($row['phrase']))
{
$data = array('success'=> true,'message'=>$row['phrase']);
// JSON encode and send back to the server
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
} else {
// Set up associative array
$data = array('success'=> false,'message'=>'aint no sunshine');
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
}
}
When i change the dataType to "text" in the javasript function - i receive an alert with 'undifiend'
But when chenge it to 'json'.. i receive nothing (chrome debuger see nothing)
I set up all encodings to this article http://kunststube.net/frontback/
And i checked it with simple POST requests - it works perfect.
The problem with json.
Any suggestions?
Thanks
Just remove the datatype="json" bit and change the data bit to data: { "string": string }
After that try a print_r(json_decode($_POST['string']));. I'm quite sure that will get you your data.
And indeed remove your beforeSend callback.
I think the prob is the code var postData ="string="+string;
jQuery expects this to be a proper JSON Object.
Next: $string = $_POST['www']; takes a parameter named "www" from your post request, but the name above is "string" (at least).
Try either (!) this:
var getData ="www="+string;
$.ajax({
type: "POST",
dataType: "json",
data: null,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php?' + getData,
and server:
$string = $_GET['www'];
or this (php)
$string = $_POST['string'];
$stringData = json_decode($string);
// catch any errors ....
$quest=$stringData[....whatever index that is...];