Jquery ajax to php and returning values

Hi all,

I have a basic form. On form submittal I want to post the values via ajax to some php script. The php script performs a calculation (based on the form inputs) and displays a series of charts. I want to show these charts on the page that has the form.

So I think what Im asking is - how do I return the html output of my php file into a div container on the page which has the form.

Thanks

The php code echos out the html output for the chart.
The response of your ajax request is where the php chart will be found.

Yes, thats right

document.getElementById("mydivcontainer").innerHTML = response

@bolton, I can’t tell for sure what exactly you are asking. However, there’s a nice, simple example of using AJAX (via jQuery) with PHP at StackOverflow which may help you.

Can you clarify what the problem is; are you just trying to get started doing this, or is there a specific problem you’re encountering during the process?

If you’re actually submitting the form by hitting a button, that won’t work; you’ll send a request to the server, which will load the page with your content. You’ll want to hijack the button’s onclick, and run the AJAX from there, as in the StackOverflow post I pointed to.

sort of true. You can use a submit button to send ajax, and you can use the submit event to do it, you just have to preventDefault to stop the browser from also submitting the form.

2 Likes

Hi guys,

I almost have this working!

My jquery code is:

$("#btn-calculate").click(function(event){
    event.preventDefault();
    var myVar1 = $("#myVar1").val();
    var myVar2 = $("#myVar2").val();
    $.post("process.php",
	{"myVar1": myVar1},function(data) {
    	$('#results').hide().html(data).fadeIn();
		$('.progress .progress-bar').css("width",
		function() {
			return $(this).attr("aria-valuenow") + "%";
		}
	)
    }, "html");
});

myVar1 is passed to process.php and the result is passed back to the page. How can I pass myVar2 to the process.php page? Ive tried something like:

{"myVar1": myVar1; "myVar2": myVar2},function(data) {

but that doesnt work. How do I do this please?

Ah! I just solved this. It needed commas instead of semi-colons. (I thought I tried that!)