PHP - AJAX Process HTTP requests
I have a form with x number of fields. When submitted, I want to;
- get all input data, $var = $_POST['input']
- validate开发者_C百科 input, (!empty($var) && is_numeric($var))
- stick it in an array, array_push($myArray, $var)
- generate URLS, $url.=$var
- process the URL's without leaving the page
1 - 4 already done in php
Simply, im not familiar with Ajax. Been a decade since ive touched Javascript. Im not sure if i should be using javascript to do the whole process. However, would prefer php to validate, Ajax to do http requests. Any sample code/sites available that passes php var's/array to Ajax to handle http requests?
You'll want to use some kind of format to pass data from the server to the client. I recommend JSON. PHP has a built-in function to encode an array into it, and JavaScript parses it natively.
As for the AJAX part itself, I recommend using a framework like JQuery. Makes it way simpler, and you don't have to deal with the different browsers yourself.
$.ajax({
url: "yourpage.php",
success: function(data){
alert(data);
}
});
I guess something like this-
$urlfield = explode(",", $urls);
You want to pass this array via jQuery AJAX, with this:
<form id="myForm">
<input type="hidden" value="'.$urlfield.'">
<input type="submit" id="processURL" class="Submit" name="ok" value="Send Reply"/>
</form>
And here's your jQuery:
$("#processURL").click(function(event){
event.preventDefault();
var urlUsed = $("#urlfield").val();
$.ajax(
{
type: "POST",
url: urlUsed,
data: ,// you can send some data
beforeSend: function() {
$("#processingURL").show(); //SOME FUNCTION TO SHOW URL PROCESSING
},
success: function() {
alert("Success");
}
});
});
// browser support code
function getXMLHTTP()
{ //fuction to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
// external file to linkup
function secondpage(countryId) {
var strURL = "secondpage.php?country=" + countryId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('sid').innerHTML = req.responseText;
} else {
document.getElementById('sid').innerHTML = req.responseText;
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
in secondpage.php page ( i will get $_REQUEST['country'];)
精彩评论