Why does jquery $ .ajax remove line breaks in data, but $ .get doesn't?

I call the same PHP script using $ .ajax and $ .get and get two different results.

$. ajax breaks the lines from the data passed through the function, but $ .get does not.

I tried explicitly setting the dataType type for text and html with no luck. Most options for $ .get are the same in $ .ajax by default.

http://api.jquery.com/jQuery.ajax/

This is mistake?

Here is the exact code I'm using:

$.get("lib/ajax_scripts/set-product-value.php", { input_id: input_id, val:value }); $.ajax({ url:"lib/ajax_scripts/set-product-value.php", type:'GET', data:'input_id='+input_id+'&val='+value}); 

Below is the code where anyone can try who has access to a server with PHP and firebug support. Look at the firebug answer for each request, you will see that <br /> added to $ .get, and not to $ .ajax.

ajaxtest.html

 <form method="GET" onsubmit="return false"> <textarea id="data" name="data">a b c</textarea> <input type="submit" value="Submit" id="submit"> </form> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript"> $('#submit').click(function(){ var data = $('#data').val(); $.get("data.php", { data: data }); $.ajax({ url:"data.php", type:'GET', data:'data='+data}); }); </script> 

data.php

 <?php echo nl2br($_GET['data']); ?> 
+7
source share
2 answers

$ Ajax returned text that skipped line breaks when I added it to my html. Since I wanted to keep the formatting, I had to add tags to it. So I used the string function like this:

var part1 = / \ n / g;

var newc_data = old_data.replace (part1, "<br>");

This is probably a good reason to avoid formatted text. But in my case, I want to write some intelligence for converting text to json.

+2
source

You should get the same results. According to the docs for jQuery.get :

This is an abbreviated Ajax function that is equivalent to:

 $.ajax({ url: url, data: data, success: success, dataType: dataType }); 

Also, if you look at the jQuery source code , you can clearly see that .get is just a wrapper for .ajax :

 jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); 

Are you sure you are not passing other parameters to jQuery.ajax ? You can post the code that you use for each of them to find out if there is anything else here.

+1
source

All Articles