Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

jquery issue in IE and Opera... odd issue... 1

Status
Not open for further replies.

snowboardr

Programmer
Feb 22, 2002
1,401
PH
Below is a simple jquery function, calling a json php file I have run through every possible thing i can think of but its not running on IE (compatibility mode ) and Opera 10...

Google Chrome, IE 8, Firefox, Safari all run this script without an issue.

I have checked my json file and it is returning valid json
Code:
{"t1":"For Sale","t2":"Free","u1":"1%2Ffor-sale%2F","u2":"1.624%2Ffor-sale%2Ffree%2F"}

i added headers to the php / json file
Code:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

its as though opera and ie compatibility are not seeing the $.ajax function, however it is going inside the function i tested for that!


Code:
 //#read online that cache was an issue for IE

$.ajaxSetup({cache:false});

 jQuery.fn.loadBread = function(){	

		var ar = arguments[0] || {}; // It's your object of arguments
		var page = ar.page;
		var qs = ar.qs;
		var iid1 = ar.idone;
		var iid2 = ar.idtwo;
		
		var url = page+"?"+qs;
		var sData = $.ajax({
		  url: url,
		  dataType: 'json',
		  data: sData,
		  success: function(sData) {
			 	 //#using plugin for json eval   
				var e = $.toJSON(sData);	
				var t1 = $.evalJSON(e).t1; 
				var t2 = $.evalJSON(e).t2; 
				var u1 = $.evalJSON(e).u1; 
				var u2 = $.evalJSON(e).u2; 
				alert(u2);
		  }});

					
   };

Jason

[red]Army[/red] : [white]Combat Engineer[/white] : [blue]21B[/blue]

 
this may be off centre but I'm confused by using the variable sData in two different contexts.

it probably is irrelevant but maybe cleansing that will unlock something

there is a lot of json evaluation etc going on here. typically jQuery will convert the incoming ajax response as a javascript object if it is told (or detects) that the response is json.

so in your case the json conversion has already been done and the variable passed into your success function is already an object.

you are also setting the data argument to the variable sData. however the sData argument does not seem to exist at that point. and you are setting the url to have an explicit query string appended. i am assuming that the only variable that you wish to transfer is that which you encode in the url. since we do not know the contents of the qs variable we cannot tell whether the var is correctly formatted for use as a GET variable. for the sake of clarity i am assuming it is not formatted as a key=value pair (although I guess since the script works on some browsers then it is probably ok). it is also unclear whether you have properly encoded the data (or perhaps jQuery does this on the fly - i always use a serialize method to be sure).

assuming that the response is a simple set of json encoded variables, i imagine that your code should look more like this

Code:
jQuery.fn.loadBread = function(){    

        var ar = arguments[0] || {}; // It's your object of arguments
        var page = ar.page;
        var qs = ar.qs;
        var iid1 = ar.idone;
        var iid2 = ar.idtwo;
        $.ajax({
          url: page,
          dataType: 'json',
          data: $.serialize({qs: qs}), //assume that the value pair should be qs[label]=qs[value].  The serialisation may not be necessary
          success: function(rData) {
                var t1 = rData.t1;
                var t2 = rData.t2;
                var u1 = rData.u1;
                var u2 = rData.u2;
                alert(u2);
          }});      
   };

you might also want to check out the abstracted functions like $.getJSON(), $.post() etc. No functional difference but perhaps slightly easier/cleaner on the eye.

another difference between my usual approach and yours is that I always return json objects as text in an html document. I do not use application/json as a content type. I don't remember why precisely but i think it may have been because some of my test browsers tried to save the incoming data to a document rather than handle it as text. I do not see a downside in using text/html but have done no exhaustive testing on this.
 
Sorry Billy, im in process of getting a new host setup so i dont have access to a webserver for the next 12 hours or so... I think ill just drop ajax support for <= E 7 and Opera...

Your tips help a lot jpadie, I add an error function to see what was going on... i also changed my code around you were right i was doing my json request slightly wrong... however they way i did it worked in every browser except ie 8/[C] / and Opera

This way is working good except for ie 8 [c]/ and opera


Code:
	$.ajax({
					  url: "/includes/json.bread.php",
					  dataType: 'json',
						  data: qs,
					  success: function(rData) {
							alert(rData.t1);
							
					  }
			  });
		  };
the json output via php / db with json headers posted above
Code:
{"t1":"For Sale","t2":"Antiques","u1":"1%2Ffor-sale%2F","u2":"1.615%2Ffor-sale%2Fantiques%2F"}

the above json is returning a parsing error in IE 8 Compatibility mode and Opera i checked my json in JSONlint, its valid... i also did some research and it appears that my json maybe jsonp ? because its lacking the [ ] and its not in array form so to speak..

Maybe i'm wrong but i think this maybe an opera bug as far as IE goes... well any version below IE 8 can go where the sun don't shine... of only every person in the world used google Chrome or firefox life as a web developer would be less hair-pulling and late nights!


Code:
$.ajaxSetup({
		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);
			}
		}
	});



Jason

[red]Army[/red] : [white]Combat Engineer[/white] : [blue]21B[/blue]

 
jpadie, it doesn't even enter the


$.getJSON(url,params,function(rData){

function however it is going into my loadBread function i show an alert, but its not returning anything, in dragon fly error wise... working perfectly in chrome, ff, ie 8, safari, but opera is killing it

it is show / hiding my loading icon

$("#load").ajaxStart(function(){
$(this).show();
});
$("#load").ajaxComplete(function(){
$(this).hide();
});


Jason

[red]Army[/red] : [white]Combat Engineer[/white] : [blue]21B[/blue]

 
oh and sorry forgot to answer your question... i have tried all different mime types including text/html , plain etc etc with and without... ok i just tried something and have it working... but its odd...

it works in this situation:

non database drive output: json.test.php
Code:
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
?>
{"t1":"For Sale","t2":"Auto","u1":"1%2Ffor-sale%2F","u2":"1.617%2Ffor-sale%2Fauto%2F"}


Same headers

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

database drive output: json.bread.php

Code:
{"t1":"For Sale","t2":"Auto","u1":"1%2Ffor-sale%2F","u2":"1.617%2Ffor-sale%2Fauto%2F"}

Jason

[red]Army[/red] : [white]Combat Engineer[/white] : [blue]21B[/blue]

 
is it up on the web somewhere that we can see it?
 
i have created a local version.

Code:
<?php
$o = new stdclass;
$o->t1 = "For Sale";
$o->t2 = "Free";
$o->u1 = "1/for-sale";
$o->u2 = "1.624/for-sale/free/";

echo json_encode($o);
exit;
?>

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
    <head>
        <title>A bread test</title>
        <meta http-equiv="content-type" content="text/html;charset=utf-8" />
        <script src="jQuery.js" type="text/javascript">
        </script>
		<script type="text/javascript">
			jQuery.loadBread = function(){
            
                var ar = arguments[0] || {}; // It's your object of arguments
                var page = ar.page;
                var qs = ar.qs;
                var iid1 = ar.idone;
                var iid2 = ar.idtwo;
                $.ajax({
                    url: page,
                    dataType: 'json',
                    data: {
                        qs: qs
                    }, //assume that the value pair should be qs[label]=qs[value].  
                    success: function(rData){
                        $('#result').html(rData.u2);
                    }
                });
            };
		</script>
        <script type="text/javascript">
            $("document").ready(init);
            
            function init(){
                $("#myButton").bind('click', doRequest);
            }
            
            function doRequest(e){
                e.stopPropagation();
                e.preventDefault();
                var o = {
                    page: 'untitled.php',
                    qs: 2,
                    idone: 'something',
                    idtwo: 'something else'
                };
                $.loadBread(o);
            }
          </script>
    </head>
    <body>
        <p>
            <button id="myButton">
                Press Me
            </button>
        </p>
        <p id="result">
            No Current Results
        </p>
    </body>
</html>

i can confirm that this works in
* chrome for mac (4.0.249.49)
* firefox for mac (3.5.7)
* safari for mac (4.0.4 (6531.21.10))
* Opera for mac (10.10 build 6795)

i am using jQuery 1.4.1

hth
 
Thanks for your help jpadie I appreciate the time to make your sample code.. Your example made me solve the problem... Opera doesn't like returns in its json!
so since it was getting it from the database it pushes the code down the page thus not printing it out on the first line!

Try putting echo "\n"; above the json_encode code...


GRRR... why does it have to be that easy





Jason

[red]Army[/red] : [white]Combat Engineer[/white] : [blue]21B[/blue]

 
good stuff. in php this can be solved by trim() before echoing the output. using text/html as a content type should also have helped somewhat because jQuery will hunt the return string to find the bit that is json
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top