Jump to content

is this AJAX code good enough ?


Go to solution Solved by Jacques1,

Recommended Posts

Hello

I have this Ajax code witch working good, but I'm not really good at javascript I just started 1 month ago, so I'm not sure if this code is perfect or not, or is there any way to improve this AJAX code.

HTML/AJAX

<input type="text" id="text_1" />
<button name="js_btn_func" id="js_btn_func" onclick="ajax()" > Execute JavaScript / AJAX Function </button>
<div id="success_2"></div>
<div id="result_2"></div>
<div id="error_2"></div>
<script>
try {
	var results_area_2 = document.getElementById("result_2");
	var error_area_2 = document.getElementById("error_2");
	var success_area_2 = document.getElementById("success_2");
	function ajax(str) {
		var xhttp;
		var str = document.getElementById("text_1").value;
		if (str == "") {
			document.getElementById("result_2").innerHTML = "";
			return;
		}
		xhttp = new XMLHttpRequest();
		xhttp.onreadystatechange = function() {
			if (xhttp.readyState == 4 && xhttp.status == 200) {
				results_area_2.innerHTML = xhttp.responseText;
				success_area_2.innerHTML = ('Success: Script is <b>ON</b>');
			}
		}
		xhttp.open("POST", "action.php?name="+str, true);
		xhttp.send();
	}
}
catch(e){
    alert('An error has occurred: '+e.message)
	error_area_2.innerHTML = ('Error: Script is <b>OFF</b>');
}
</script>

PHP

<?php
$random_query = mt_rand(1, 9999);
if (isset($_REQUEST["name"])){
	$q = $_REQUEST["name"];
	echo "Hello <b>$q</b>! random number : $random_query ";
}

?>

Thanks in advance. ::)

Link to comment
https://forums.phpfreaks.com/topic/299536-is-this-ajax-code-good-enough/
Share on other sites

  • Solution

Your code has several problems:

  • It is vulnerable to cross-site scripting attacks, because you insert the user input straight into your HTML markup. Of course this is just a toy example, but when you write real applications, you need to be much, much more careful when using innerHTML.
  • You've forgotten to URL-encode the content of str before using it for the name parameter. This will lead to a misinterpretation of the input if certain characters are present. For example, try entering “Paul&Mary” or “Joe#Blow”. You'll see that both are truncated, because “&” starts a new parameter, and “#” denotes a URL fragment. You need to run str through encodeURIComponent().
  • You have no error handling. If the HTTP response code is something other than 200, you don't do anything.
  • You're using the ajax() function as an event handler before it's even defined.
  • Your ajax() function has a parameter, but you never use it.
  • The code you've wrapped in a try statement cannot possibly throw an exception, so the whole statement is useless. I guess what you actually meant to do is catch exceptions in the function. So put the try statement into the function.

In general, people today rarely write low-level JavaScript code to make Ajax requests. This is certainly useful for learning, but in the long run, you should look into frameworks like jQuery. Then you don't have to write tons of boilerplate code for such a simple task.

  • Like 1

Thanks for the detailed explain it really make more sense, and I know about jQuery but I just prefer to use Javascript because I'm still learning.

sorry if I'm asking to much but, can you give me a better code example if it's possible, I'll be Very Thankful, still new with JavaScript.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.