ford prefect
ford prefect

Reputation: 7378

AJAX with javascript vs. Php Form

So I am a student working on a website for a private client. In my web design class we have been taught to mostly use forms to pass values from the client to the server with action=someFile.php. The class has also briefly mentioned using ajax to pass from the client using javascript and jquery using something like:

request = $.ajax({
        url: "persistTestimonial.php",
        type: "POST",
        data: {"testimonial": testimonial},
        dataType: "json"
    });

I also had an internship with a company where I was writing c# services passing back and forth between client and server with canjs for mvc. In the context of mvc and c# backend writing ajax calls using the way above makes sense. Since the class harps on graceful degradation I don't entirely see the benefit of javascript ajax instead of php forms other than that the entire page doesn't have to reload. I just want to know what is best practice and what exactly the benefits are.

Upvotes: 0

Views: 597

Answers (1)

Muhammad Umer
Muhammad Umer

Reputation: 18097

The main benefit of ajax is Not reloading of page that is Win-Win for both server and client.

Client doesn't have to wait again, experience is fluid. Think of Facebook app, You scroll to bottom and more posts load up..it's much better than pressing next again and again to wait for next 50 posts load..but with ajax you can get 2 by 2.

For server, not having to send same resources over and over again is big help on money side. Second, lot of computations can be done on client side and choose what to do next or where to go..saving server more money.

Even the usual way, where you click submit and forum submits. The action parameter is not used. That's ancient way of doing this..simplest true. But not very good. The reason is because you can't modify, validate, and do anything else. As for submits asap. So usually you attach submit event handler to form then cancel event propagation, run checks and do whatever you gotta do then if happy then manually submit it.

From server side it really isn't a big deal. If it comes via ajax or directly from browser address bar. Any request is just that a http get/post request.

For Example..http://jsfiddle.net/9pB8s/

var form= document.getElementById('f'),
    txt= document.getElementById('txt');

form.onsubmit= doStuff;

function doStuff(e) {
    if (!isNaN(txt.value)) {
        txt.value='Thanks for Interest!';
        txt.setAttribute('readonly','readonly');
        setTimeout(function(){
            f.submit();
        },1000);
    }
    return false;
}

Returning false cancels the event from firing. But when text is just numbers the js manually submits it. Timer is added just for effect.

Upvotes: 1

Related Questions