This question already has an answer here:
Viewing data returned by ajax in IE9
(1 answer)
Closed 9 years ago.
I have tried to send an AJAX request and wanted to see what I've send.
But unfortunately I'm not able to do it.
There exists a select option element that I will fill later with the response if everything works.
<script type="text/javascript">
$(document).ready(function(){
$('select[name="domains"]').change(function(){
var requestStr = $(this).val();
// send Ajax request
$.ajax({
cache: 'false',
type: 'POST',
data: {select:requestStr},
url: 'myHandler.php',
dataType: 'json',
success: function(data){
var json = JSON.parse(data);
alert(json.response); // Here you get the value
if(data.status == 'success')
alert("Thank you for subscribing!");
else if(data.status == 'error')
alert("Error on query!");
var str = "<option value=''>Please Select</option>";
//$.each(data, function(i, items){
// str += "<option value='"+items.id+"'>"+items.name+"</options";
//});
$('select[name="countries"]').html( str );
},
// When an error occurs, the error function is called.
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
});
});
The PHP handler Looks like this:
<?php
require_once 'myClass.php';
if (isset($_POST['select']))
{
// log event
$filename = "log.txt";
$fd = fopen($filename, "a");
$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $_POST['select'];
fwrite($fd, $str . "\n");
fclose($fd);
$handler = new myClass();
$dataAjax = $handler->getName($_POST['select']);
echo json_encode($dataAjax);
}
<?php
class myClass {
function getName($data)
{
return $data;
}
}
I thought I can use the request parameter and return it but there is nothing I can see.
Oh, I use Internet Explorer so I can't use Firebug.
EDIT
I added a few rows to log my request.
But the log file is empty.
UPDATE
Now there is some progress:
I can see this in the request-text "select=QD".
But when I echo it with echo json_encode($dataAjax);
I get a error window with Error.Parsing JSON Request failed.
I don't get it why the 'success' function won't work!
The response is json encoded.
Oh btw. is it right that I can't use "return" in PHP to send my response back to AJAX?
You can print out request at server side and log it into file/syslog/etc.
if (isset($_POST['countries']))
{
$handler = new myClass();
$dataAjax = $handler->getName($_POST['countries']);
echo json_encode($dataAjax);
}
------------------------------------------------------
dataType: 'json'
if you just want to see the headers,post,response,html then try firebug
function IsJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
this will check whether the response is json or not
Related
Here is my little script code I want to get data from codeingiter controller. I get json data from controller to view ajax, but It print with html page code.
any one can help me here, How can I solve this.
I only want to get json data ans a variable data to my page.
this is output that I am getting but this is comming with html code and I don't want html code.
[{"id":"1","p_name":"t_t11","p_type":"t_t1","paid_type":"0"},{"id":"2","p_name":"t_t12","p_type":"t_t1","paid_type":"1"},{"id":"3","p_name":"t_t1","p_type":"t_t1","paid_type":"0"}]
I have follow some question answers but can't et success, because that question's answers not related to me.
Link 1
Link 2 and many more...
<script>
$("a.tablinks").on('click',function(e){
e.preventDefault();
var p_name = $(this).attr('value');
alert(p_name);
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'text',
type: "POST",
data:{p_name : p_name},
success : function(data){
alert(data);
if(data !=""){
var obj = JSON.parse(data);
alert(obj.id);
/*$.each(obj, function(key,val){
console.log(key);
console.log(val); //depending on your data, you might call val.url or whatever you may have
});*/
}else{
alert(data+ '1');
}
},
error : function(data){
//var da = JSON.parse(data);
alert(data+ '2');
//alert(da+ '2 da ');
}
});
});
</script>
Here is controller code.
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
echo json_encode($query['res']);
$this->load->view('teq', $tabs_data);
}
You added view at the end of your function that return view's code.
Remove line:
$this->load->view('teq', $tabs_data);
You can either use
if ($this->input->is_ajax_request()) {
echo json_encode($data_set);
}else{
//Procced with your load view
}
Or if you're avoiding ajax request check then please pass any extra paramter from your ajax call then then check for its existence at your controller and on behalf of it proceed your conditional statement . it will solve your problem
Change your controller method like this:
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
// if ajax request
if ($this->input->is_ajax_request()) {
echo json_encode($query['res']);
return; // exit function
}
$this->load->view('teq', $tabs_data);
}
In your ajax code chage dataType: to json
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'json',
type: "POST",
data:{p_name : p_name},
success : function(res)
{
if(res !=""){
alert(res.id);
}else{
alert(res+ '1');
}
}
});
And in your controller
public function gettabdata()
{
if($this->input->post('p_name'))
{
$p_name = $this->input->post('p_name');
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
if($query['res'])
{
$resp = $query['res'];
}
else
{
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
}
else
{
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
$this->load->view('teq', $tabs_data);
}
}
Hope this helps :)
I have a problem where some of my data is not getting through to php. I think the problem lies in ajax sending it. I send about 10 attributes, from which some are strings and some are integers. This is just simplified example of what I did. Few of the values given that it misses are integers, I think. And some values are got from cordova.Localstorage with storage.getItem("itemkeyname"); There's no problem with connection, because I get at least error message back saying "missing data" etc, etc..
I've tried PHP's isset() instead of empty(), which didn't change anything.
var_dump() returns array of send attributes, but few last attributes are cut-off or missing.
//when submitbtn is pressed
$("#submitbtn").click(function () {
// First I get data from input elements from page
$name = $("#name").val();
$name2 = $("#name2").val();
//debug to see $name's value
alert("name: " + $name + ", name2: " + $name2);
// then I check it's not empty/null
if ($name && $name2) {
//then call ajax and send data to server
$.ajax({
url: "http://localhost:1234/phpfile.php",
type: "POST",
data: {
name: $name,
name2: $name2
},
dataType: "text",
success: function (response) {
alert(response);
},
error: function (err) {
$output = JSON.stringify(err);
alert($output);
}
});
}
});
On the server side phpfile.php
<?php header('Content-Type: text/html; charset=utf-8');
//store missing data on array
$data_missing = array();
if(empty($_POST['name'])) {
$data_missing[] = "name";
} else {
$name = trim($_POST['name']);
}
if(empty($_POST['name2'])) {
$data_missing[] = "name2";
} else {
$name2 = trim($_POST['name2']);
}
//check there's no data missing
if(empty($data_missing)) {
//do stuff
} else {
echo 'missing data: ';
foreach($data_missing as $missing) {
echo '$missing , ';
}
}
?>
echo '$missing , ' won't work should be echo "$missing , "
In your JS code the dataType is defined as "text" (plain), while PHP defines its response as text/html.
Try to check the input values as:
if( !isset($_POST["name"]) || strlen(trim($_POST["name"])) == 0 ) {
$data_missing[] = "name";
}
I know this is silly Question but i have occurred this error again and again
My Question is
php script are send me the right data but when i set the if condition in
success:function(data)
data then show me the one alert if i put the right value and wrong value
This is Js Code
function SetTheAmount_man()
{ //Get
var member_id = $('#mem_un_id').val();
// alert(member_id);
$.ajax({
url:"<?php echo
base_url();?>demo_insert.php",
data: {member_id:member_id},
type: "POST",
success:function(data){
//alert(data);
// alert(member_id);
if (data == 'success')
{
alert("123");
}
else
{
alert("456");
}
//window.open('http://www.google.com');
//alert(data);
// $("#secheme_interest_value").html(data);
}
});
}
This is PHP Code demo_insert
if(isset($_POST['member_id']))
{
$mem_un_id=$_POST['member_id'];
$sql_in= mysql_query("select mem_un_id,deleted from phppos_customers where mem_un_id='".$_POST['member_id']."' and deleted='0'");
//$row = mysql_affected_rows($sql_in);
$row=mysql_fetch_array($sql_in);
if($row['mem_un_id']!=''){
echo "success";
}else{
echo "error";
}
//echo $row['mem_un_id'];
}
#Deepak Acharya: Use the datatype in you ajax hit and then check if it helps, try all the datatypes available most likely to use
text
html
json
What is the result of alerting the incoming response?Uncomment this:
//alert(data);
Try to change this:
if(data == 'success')
{
alert("123");
}
else
{
alert("456");
}
to this:
if( data == "success" ) {
alert("123");
}
if( data == "error" ) {
alert("456");
}
I have to validate my form which does a scheduling. I used ajax and php to do a query and search that time - that was choosen in a select - in the database. If there's one row saved, it returns 1 (or false), if doesn't, returns 0 (or true). Anyway, in the function callback, even it's true, the validate error appears, as if it had a real error. Printing the value, we see the value, but i dont know why it shows the error. I've tried everything, and nowhere i found the answer for this.
The js file: alteraDiv.js
jQuery.validator.addMethod('confereDia', function(value){
alert("entrou no método");
if (conf(value) == '0'){
alert("entrou no if");
return true;
}else{
alert("entrou no else");
return false;
}
});
var verifica;
function setVerifica(x){
verifica = x;
}
function conf(value){
$.ajax({
async: false,
url: 'confereDia.php?horarioInicial='+value,
dataType: 'text',
success: function(data) {
alert("entrou no success");
setVerifica(data);
alert("value:"+value);
return verifica;
},
error: function(data){
alert("ERROR. Dados: " + data);
}
});
}
The php file: confereDia.php
$horarioInicial = $_GET["horarioInicial"];
$query = "SELECT idAgendamento FROM agendamento WHERE horarioInicial = '$horarioInicial'";
$results = mysql_query($query);
if (mysql_num_rows($results) == 0) {
echo '0'; //good to register
} else {
echo '1'; //already registered
}
There are more codes in the files, but i think these are necessary for you understand and help me.. THANK YOU!!!
Can somebody can tell me why my code will suddenly callback to error and suddenly can successful randomly?Thanks.
function get_timeframe(){
var v_fldname = "xUPH_exclude_Timeframe";
if ($.trim(v_fldname) != '') {
//alert(v_fldname);
$.ajax({
url:"../ajax/get_timeframe.php",
dataType: "json",
data:{v_fldname: v_fldname},
success: function(data) {
if ( data.result != null ) {
$.each(data.result, function(){
var code_value = this['code_value'];
document.getElementById('v_xUPH_exclude_Timeframe').value = code_value;
//alert(" get v_xUPH_Scan_Count");
});
}
},
error: function(data) {
alert("get_timeframe error");
}
});
}
}
The following php code.
if (isset($_REQUEST['v_fldname']) === true) {
require '../Connections/con_meditop.php';
$query = mysql_query("
SELECT code_mstr.code_value
FROM code_mstr
WHERE code_mstr.code_fldname = '" . mysql_real_escape_string(trim($_REQUEST['v_fldname'])) . "'
");
$result = array();
if(mysql_num_rows($query) == 0)
{
$result = null;
}else{
while ( $row = mysql_fetch_array($query) )
array_push($result, array('code_value' => $row[0]));
echo json_encode(array("result" => $result));
}
}
The issue is on the receiving end of your Ajax call--get_timeframe.php. Press F12 and click the network part of the console, then send the Ajax call. You'll see get_timeframe.php show up in the network console and then turn red. Click it and look at the response body.
Or instead of alert("get_timeframe error"); Do console.log(data); to see a run-down of the error in the console (press F12).