Reputation: 76
I have two files, one runs calculations in PHP once and stores them into variables in javascript. The second file holds mySQL query to be sent to database. How can I send the javascript variables from the first file, too the second file and store them as variables.
-I am loading the second .php file using a .load() function. So it is not refreshing and re- directing to the second .php file.
Is this possible to do with out ajax? If it is only possible with ajax, how do you set it up (new to ajax) ?
$("#st").click(function()
{
var s = $("#st").val();
var a = $("#AA").val();
var t = ((s*1)*(a*1)+(a*1)*(1/3)).toFixed(2);
var c = (t*95).toFixed(2);
var text = $('#st').children("option:selected").text();
document.getElementById('Tim').innerHTML ='<p>'+ t +' </p>';
document.getElementById('Obj').innerHTML ='<p>'+ text +'</p>';
document.getElementById('Tot').innerHTML ='<p>$'+ c +'</p>';
});
var Customer = <?php echo json_encode($q);?>;
var Dr= <?php echo json_encode($o);?>;
var Pd = <?php echo json_encode($p);?>;
var Qp = <?php echo json_encode($a);?>;
var Qs = <?php echo json_encode($r);?>;
var Cam = <?php
if($Camera==1){
$CameraOutput = "XL";
echo "XL";
}
if($Camera==2){
$CameraOutput = "SL";
echo "SL";
}
?>;
Upvotes: 0
Views: 833
Reputation: 1074038
Edit: You mentioned in a comment on another answer that you're using jQuery, so I've edited the below.
Is this possible to do with out ajax?
Yes, but you probably don't want to. You'd do it by creating a form element, setting its action
, setting its method
, adding fields to it, and submit
ing it:
var form;
form = $("<form>")
.attr("action", "/path/to/php/file.php")
.attr("method", "POST");
$("<input type=hidden>")
.attr("name", "fieldName1") // I'm assuming hardcoded field names
.val(fieldValue1) // And values coming from variables
.appendTo(form);
$("<input type=hidden>")
.attr("name", "fieldName2")
.val(fieldValue2)
.appendTo(form);
form[0].submit(); // Note the [0], so we're using `submit` on the actual HTMLFormElement
Note that the response will replace the current window.
If it is only possible with ajax, how do you set it up (new to ajax) ?
There are thousands of examples out there. :-) Here's another:
$.ajax({
url: "/path/to/php/file.php",
type: "POST",
data: {"fieldName1": fieldValue1, "fieldName2": fieldValue2},
success: function() {
// Called if the request succeeds
},
error: function() {
// Called if the request succeeds
}
});
Upvotes: 2
Reputation: 4309
AJAX is an acronym for asynchronous JavaScript and XML. If you want to run your second php file without redirecting to it, you can use AJAX because it will run your second php file 'in the background'. AJAX with JQuery is extremely easy to use aswell.
Taken from http://api.jquery.com/jQuery.ajax/
Example: Save some data to the server and notify the user once it's complete:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
Upvotes: 3