I have a form with x number of fields. When submitted, I want to;
get all input data, $var = $_POST['input']
validate 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'];)
Related
I want to get the api values using json. if I click the json button I did not get any response I don't know why this is not running yesterday I have checked with api method it is in post only.I don't know where i am lacking.
Here is my code:
<script type="text/javascript">
function json()
{
xmlhttp= new XMLHttpRequest();
var url="http://new.ezeeinfosolutions.com/busservices/auth/getAuthToken?namespaceCode=demo&username=ram#demo.com&password=newnew&devicemedium=WEB";
alert(url);
//var url="dbarr.php";
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var ret_arr=JSON.parse(xmlhttp.responseText);
json_arr(ret_arr);
}
}
xmlhttp.open("POST",url,true);
xmlhttp.send();
}
function json_arr(x)
{
var res="";
var i;
for(i=0;i<x.length;i++)
{
res+=x[i].name+" "+x[i].mobile+"</br>";
}
document.getElementById('print').innerHTML=res;
}
</script>
<form name="f1" action="" method="post">
<input type="submit" onClick="json();" value="Json">
<p id="print"></p>
</form>
i can suppose what "http://new.ezeeinfosolutions.com" isnt your domain and you nead create some php mirror file on your server.
This file will get response from http://new.ezeeinfosolutions.com and return json.
their can few possible solution, if any of them get you to success than chear up :)
try to set response type.
xmlhttp.responseType = 'json';
try to use xmlhttp.response instead of xmlhttp.responseText
use this example to compare.
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
var status;
var data;
// http://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
successHandler && successHandler(xhr.response);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('https://mathiasbynens.be/demo/ip', function(data) {
alert('Your public IP address is: ' + data.ip);
}, function(status) {
alert('Something went wrong.');
});
Read More:https://mathiasbynens.be/notes/xhr-responsetype-json
i have page that do add new record by old way ajax, this code was add new record and return the error or done result message , how can i print the message on div and print result on other div. i try but some one tell me to use JOSN, how can i do that
<script language="JavaScript">
$(document).ready(function() {
});
$("#closeerr").live('click', function() {
$("#gadget").hide();
});
var HttPRequest = false;
function doCallAjax(Mode,Page,ID) {
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 'AjaxItemsGroupsRecord.php';
var pmeters = "titems_groups_GroupName=" + encodeURI( document.getElementById("items_groups_GroupName").value) +
"&titems_groups_sys_type_ID=" + encodeURI( document.getElementById("items_groups_sys_type_ID").value ) +
'&myPage='+Page +
"&tID=" + ID +
"&tMode=" + Mode;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.setRequestHeader("Connection", "close");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 3) // Loading Request
{
document.getElementById("mySpan").innerHTML = "looding";
}
if(HttPRequest.readyState == 4) // Return Request
{
document.getElementById("mySpan").innerHTML = HttPRequest.responseText;
}
}
}
</script>
If jQuery is an option... As mentioned in my comment I'd recommend you try out jQuery http://jquery.com/ as you look to be fairly new to JavaScript.
It makes AJAX requests a lot simpler and you don't have to worry about making XMLHttpRequest work cross browser.
For making an actual AJAX request see: http://api.jquery.com/jQuery.ajax/
Now if you want to use JSON you need to convert the data to return in your PHP script.
This is really easy, you just pass the data in json_encode() and it will convert the data to a JSON string. You then just echo it out so that it's returned to the AJAX request.
echo json_encode($data);
Now if you've setup your AJAX request to expect a JSON response then you can use the data that comes back. So something like this:
$.ajax({
url: 'request.php', // the php you want to call
dataType: 'json' // the type of data being returned
}).done(function(json) {
// you now have a json object
});
If you can only use native JavaScript...
If you can't use jQuery then it roughly works the same way. You'd have the code in your example for the AJAX request. You'd still use json_encode() in the PHP. The only difference is when the data comes back you'd need to parse it like so:
JSON.parse(json);
For more info on this last bit checkout: Parse JSON in JavaScript?
I have a php function in which some pdf is being created. I have a button and I want to call that function on button click and then redirecting to a url. What can be the simplest method of doing that?
If you need to call a PHP method, I'd use AJAX. Something like this:
var btn = document.getElementById("button_id");
btn.onclick = function () {
// Make AJAX request
// On success, do this:
window.location.href = "url to redirect to";
};
The code for "Make AJAX request" can be Googled easily, and I will provide it in a minute :)
UPDATE:
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Firefox, Chrome, Opera 8.0+, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (e) {
throw new Error("This browser does not support XMLHttpRequest.");
}
}
}
}
}
return ajaxRequest;
}
The AJAX code -
var req = ajaxFunction();
req.onreadystatechange = function (response) {
if (response.status == 200 && response.readyState == 4) {
window.location.href = "url to redirect to";
}
}
req.open("POST", "your PHP file's URL", true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(null); // Or send any `key=value&` pairs as a string
There are various ways to accomplish this. I would call the PHP function in ajax and redirect based on the functions return value. The following example uses jQuery:
jQuery:
$.ajax({
url: 'createpdf.php',
success: function(data) {
if (data) window.location = 'link/to/new/path';
}
});
PHP:
function create_pdf(){
//Create PDF
//If PDF was created successfully, return true
return true;
}
<form name="input" action="whatever.php" method="get">
...
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
function mehdi(rno)
{
alert(rno);
return rno * 10;
}
</script>
<input type="button" name ="submit" value="ثبت و تایید" onclick= " mehdi('10')">
<?php
?>
how can i use from returned value from mehdi() function?
In this case you can't since PHP is used only to render HTML.
You will have to use AJAX (AHAH) for it:
http://en.wikipedia.org/wiki/Ajax_%28programming%29
You can't! Javascript runs on the browser, after your PHP script has finished executing.
You can't PHP is processed first and then page executes javascript.
you can send Ajax request thought to your PHP scripts.
You can't do it directly. You have to use AJAX.
Once code comes to client side and it executes there, your server side script would have terminated already.
If you do need to send JavaScript return values, pass them back to server using AJAX.
you could do an ajax request within the medi function and the request could sent it via post to an file like "mehdi_js_result.php" :)
var ajaxify = function(obj) {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e) {
xmlHttp = null;
}
}
}if (xmlHttp) {
obj.method = obj.method.toUpperCase();
xmlHttp.open(obj.method, obj.url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if(obj.method == 'POST') {
if(typeof(obj.params) != 'undefined') {
xmlHttp.setRequestHeader("Content-length", obj.params.length);
}
}
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
var json = eval(xmlHttp.responseText);
if(json.success) {
if(typeof(obj.success) == 'function'){obj.success(xmlHttp.responseText);}
}
else {
if(typeof(obj.failure) == 'function') {obj.failure(xmlHttp.responseText);}
}
}
};
if(obj.method == 'POST' && typeof(obj.params) != 'undefined') {
xmlHttp.send(obj.params);
}
else {
xmlHttp.send(null);
}
}
};
function ajax(mehdi_result) {
ajaxify({
method: 'POST',
url: 'mehdi_js_result.php',
params: 'result='+result,
success: function(response) {
var json = eval(response);
alert('success callback function! '+json.data);
},
failure: function(response) {
var json = eval(response);
alert('failure callback function! '+json.data);
}
});
}
How can I use javascript to send a one way message to php? I would like to get the browser information from javascript and just send it to php in the background. I know I can get some of this from php, but I'd rather use javascript. Is there a way to do this without a framework like jquery?
Yes, you can do it with something like this:
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
alert('Here goes something');
self.xmlHttpReq.send('browser info here');
}
}
}
This will send "browser info here" as POST in the php page you pass to the function as url. I didnt test it though
You would have to submit an AJAX request to a PHP script. Yes, you could do it without using a framework but I wouldn't advise it.
You need to make an AJAX call to a PHP page, preferably using POST. Any data you want to send needs to be sent along with the request.
I recommend using a framework such as jQuery, but if you insist on using raw JavaScript, you want to research XMLHttpRequest.
// fix for older IE versions
// see http://blogs.msdn.com/b/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
if( typeof window.XMLHttpRequest === 'undefined' &&
typeof window.ActiveXObject === 'function') {
window.XMLHttpRequest = function() {
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
return new ActiveXObject('Microsoft.XMLHTTP');
};
}
function postData(url, data, errhandler) {
var req = new XMLHttpRequest;
req.onreadystatechange = function() {
if(this.readyState === 4 && this.status !== 200 && errhandler)
errhandler(this);
};
try {
req.open('POST', url, true); // async post request
req.send(data);
}
catch(e) {
if(errhandler)
errhandler(req);
}
}