jQuery bind after ajax load

Sometimes it is needed to add a jQuery event listener to an element that isn’t present in the DOM at the creation of the page but created during runtime or the result of an ajax call.

What doesn’t work is

jQuery(document).ready(function () {
    jQuery('.selector').on({
        click: function  (event){
            event.preventDefault();
            console.log('I work only with existing elements');
        }
    });
});

However, there is a way to achieve that.

jQuery(document).ready(function () {
    jQuery(document).on('click', '.selector', function (event){
        event.preventDefault();
        console.log('I work with a dynamically created elements');
    });
});

Jquery IE .html() Error

Ein einfacher html code, der per ajax verändert werden soll.

<div><img src="icons/reddotadd.gif" title="Add Page" id="AddPageTrigger" alt="Add Page" style="border:0; cursor:pointer;" /></div>
$("#AddPageTrigger").text("TEXT hier");

schlägt im IE fehl. Warum? Keine Ahnung, aber was funktioniert ist

$("#AddPageTrigger").parent().text("TEXT hier");

Ajax Undzeichen ( &) übertragen

Normalerweise gibt es ein Problem beim Übertragen von Daten per AJAX, wenn sich ein & Zeichen in dem zuübertragenden Text / Daten befindet. Das Javascript interpretiert das Undzeichen als Trennzeichen. Alles nach dem & Zeichen wird nicht mehr übertragen. Abhilfe schafft hier die funktion encodeURIComponent

 

var save_data = 'save_text=' + encodeURIComponent($(".edit_textarea").val());
		logging(save_data);
		//return false;
		$.ajax({
			type: 'POST',
			url: 'ajax.php',
			data: save_data,
			success: function (msg){
				console.log('OK: ' + msg);
			},
			error:function (xhr, ajaxOptions, thrownError){
				alert(xhr.status);
				alert(thrownError);
			}
		});

Jetzt kommen die Daten auch an.

JQuery Ajax cross domain request

If you try to do an ajax request on a different domain. You’ll get nothing. Looking a bit deeper into the request I noticed that the status code isn’t 200 or 403 nor 404 like expected. Nope it is 0. (jquery ajax statusCode 0). This means the browser doesn’t allow a crossdomain request. The easiest way for me to solve this was to create a proxy php script. Now I can send my ajax request to a url on my server while the PHP script does the real request to the other server.

This is the php script

/**
* GetFromHost()
*
* @param string $host
* @param int $port
* @param string $path
* @param string $referer
* @param bool $keepalive
* @return
*/
function GetFromHost($host, $port, $path, $referer,$keepalive=false) {

 $fsocket = fsockopen($host, 80, $errno, $errstr, 30);

 if($fsocket){
 $request =     "GET $path HTTP/1.1\r\n";
 $request .= "Host: $host\r\n";
 $request .= "Referer: $referer\r\n";
 $request .= 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) ';
 $request .= "Gecko/20021204\r\n";
 $request .= 'Accept: text/xml,application/xml,application/xhtml+xml,';
 $request .= 'text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,';
 $request .= "image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1\r\n";
 $request .= "Accept-Language: en-us, en;q=0.50\r\n";
 //$request .= "Accept-Encoding: gzip, deflate, compress;q=0.9\r\n";
 $request .= "Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66\r\n";
 if($keepalive==true){
 $request .= "Keep-Alive: 300\r\n";
 $request .= "Connection: keep-alive\r\n";
 }
 else
 {
 $request .= "Connection: close\r\n";
 }
 //$request .= "Content-Type: application/x-www-form-urlencoded\r\n";
 //$request .= "Content-length: ". strlen($data_to_send) ."\r\n";
 $request .= "\r\n";
 //$request .= $data_to_send;

 fputs($fsocket, $request);

 $res ='';
 while(!feof($fsocket)) {
 $res .= fgets($fsocket, 1024);
 }
 fclose($fsocket);

 return $res;

 }
 else
 {
 return false;
 //echo "Fehlgeschlagen: ".$fsocket . $host .':'. $port;
 }

}

$x = GetFromHost("www.example", "80", "/deep/url/kinda/", "");
$x = explode('Content-Type: text/html',$x);
$output = preg_replace('/\s+(\r\n|\r|\n)/', '$1', $x['1']);//remove white space and tabs at the line ends
echo $output;

maybe you have to edit the explode part for server to separate the header fom the real content.

Posts Tagged ajax

Archives by Month: