Sending an array using javascript ajax - javascript

In jquery I can do this
myAray=['abc', '123', 'more'];
$.post('myscript.php', {data:myAray}, function(data){
alert(data);
});
How can I do the same thing using plain javascript ? I want to send an array to my php script using POST method. I have found so many examples but all of them are jquery related.
Thanks in advance.

You will have to use XMLHttpRequest and serialize the array yourself:
function ajax(myArray) {
var xmlHTTP;
if (window.XMLHttpRequest) {
xmlHTTP = new XMLHttpRequest();
} else {
xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHTTP.onreadystatechange = function () {
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
// do whatever it is you want to do
}
}
//Serialize the data
var queryString = "";
for(var i = 0; i < myArray.length; i++) {
queryString += "myArray=" + myArray[i];
//Append an & except after the last element
if(i < myArray.length - 1) {
queryString += "&";
}
}
xmlHTTP.open("POST", "www.myurl.com", true);
xmlHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlHTTP.send(queryString);
}

Mess around with this.
JS
var myarray = Array("test","boom","monkey");
send("test.php", myarray);
function send(url, data)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
console.log(xhr.responseText);
}
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("data= " +data);
}
PHP
<?php
$array = explode(',', $_POST["data"]);
for($i=0,$l=count($array); $i<$l; $i++)
{
echo $array[$i].'<br>';
}
?>

Something like this:
post is either POST or GET.
params are only used in POST otherwise include what you need in the url for GET.
success and error are both string names of the functions, not the functions themselves, which is why you need executeFunctionByName, thanks to Jason Bunting:
How to execute a JavaScript function when I have its name as a string
getRemoteData = function (url, post,params, success, error){
var http = false;
if (navigator.appName === "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
http.open(post, url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {var resp; if (http.readyState === 4 && http.status == 200) { resp=http.responseText; executeFunctionByName(success, window, resp); }else if(http.status == 400){resp=http.responseText; executeFunctionByName(error, window, resp);}};
http.send(params);
return false;
};
function executeFunctionByName(functionName, context, args) {
args = Array.prototype.slice.call(arguments).splice(2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(this, args);
}

function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","jsArrayPhp.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("test[]=Henry&test[]=Ford");
}
Take attention here:
test[]=Henry&test[]=Ford"
Where test is the name of array you'll use in php.
In php
<?php
print_r($_POST['test']);
?>
It'd produce: Array ( [0] => Henry [1] => Ford )

Related

How to get id variable into ajax

js
function SearchInList(_id,_url,_place){
this.id = _id;
this.url = _url;
this.place = _place; /*How to get this value */
};
SearchInList.prototype.FindMe = function (_str){
this.str = _str;
if (this.str == "") {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var place = this.place;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("lista-ind").innerHTML = this.responseText; /*in this place */
}
};
xmlhttp.open("GET",this.url+"?id="+this.id,true);
xmlhttp.send();
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("lista-ind").innerHTML = this.responseText;
}
};
xmlhttp.open("GET",this.url+"?id="+this.id+"&hint="+this.str,true);
xmlhttp.send();
}
};
in HTML I have
<input type="text" placeholder="Search" id="search-ind" ></div>
<div id="lista-ind" class="lista"></div>
<script>
var id = <?php echo $_GET['id']; ?>;
var url = "showresults.php";
var place = "lista-ind";
var searchInd = new SearchInList(id, url);
var searchboxInd = document.getElementById("search-ind");
window.onload = searchboxInd.addEventListener("keyup", function(){
searchInd.FindMe(searchboxInd.value,place);
console.log(searchboxInd.value);
}, false);
window.onload = searchInd.FindMe("",place);
</script>
and when i have in function in onreadystatechange " document.getElementById("lista-ind")" it is working, but when I change to
document.getElementById(this.place) it is not.
how to pass this variable into that function?
this is how i made searching in lists.
thanks.
M.
If place is a global variable, outside the function, you not need this; just the variable name.
document.getElementById(place)
You're instantiating SearchInList without a place and FindMe does not take place as a parameter, so there is no way to get place to use in the object.
The easiest solution would be to add place as a parameter to FindMe
SearchInList.prototype.FindMe = function (_str, _place){
this.str = _str;
this.place = _place;
...

Dynamic Object Access from form to Ajax

Here is my JavaScript with Ajax code:
Actually i am using this for dynamically adding option in any number of select in which this function is called.
function loadabc(vm) {
var xmlhttp;
//alert(vm);
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//alert("called");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var jsonObj = JSON.parse(xmlhttp.responseText);
for(i = 0; i < jsonObj.length; i++) {
var createOption = document.createElement("option");
//alert("Jeason has Passed Data");
createOption.value = jsonObj[i].aId;
createOption.text = jsonObj[i].aName;
//alert("id" + createOption.value);
//alert("Name" + createOption.text);
document.impForm.vm.options.add(createOption);
//alert("Added");
}
}
}
xmlhttp.open("get", "${pageContext.request.contextPath}/Admin_Search_con?flag=loaddetail", true);
xmlhttp.send();
}
I am using ondblclick="loadabc(this)" for calling it. I want to access this vm object for creating options in select. How can I do so?
The solution is to use the param vm instead of referencing it as document.impForm.vm:
function loadabc(vm) {
var xmlhttp;
//alert(vm);
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//alert("called");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var jsonObj = JSON.parse(xmlhttp.responseText);
for(i = 0; i < jsonObj.length; i++) {
var createOption = document.createElement("option");
//alert("Jeason has Passed Data");
createOption.value = jsonObj[i].aId;
createOption.text = jsonObj[i].aName;
//alert("id" + createOption.value);
//alert("Name" + createOption.text);
vm.options.add(createOption); // <-- Here!
//alert("Added");
}
}
}
xmlhttp.open("get", "${pageContext.request.contextPath}/Admin_Search_con?flag=loaddetail", true);
xmlhttp.send();
}

How to make the data downloaded same across all the versions of browsers?

I am downloading a file in my java application using jquery.
It is downloading in correct format in IE8 where as Format is getting changed when i am using IE10.
Here is my code, where I am setting hearder.
function converthtml() {
var CustomerID = document.getElementById('customerID').value;
var ci = document.getElementById("ci").value;
var strvar;
strvar = term.textContent || term.innerText;
strvar = encodeURIComponent(strvar);
var xmlHttp;
var xmlHttp;
var flag = 0;
if (typeof XMLHttpRequest != "undefined") {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp == null) {
alert("Browser does not support XMLHTTP Request");
return;
}
xmlHttp.onreadystatechange = stateChange2;
function stateChange2() {
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
//alert("response : "+xmlHttp.responseText);
alert("Session value saved successfuly");
}
}
var params = "sessiondata=" + strvar + "&ci=" + ci + "" + "&customerID=" + CustomerID;
xmlHttp.open("POST", "DownloadSession", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(params);
// xmlHttp.send("sessiondata="+strvar+"");
document.getElementById("downloadSession").disabled = false;
}
I suspect the following statement is causing the format change
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Kindly suggest me an alternative that keeps content-type same across all the browser versions......

split value not getting in javascript

I have two jsp.one is user.jsp.In that jsp i am getting the record from the database and append space between the two records.for ex: ab9898329379 ab989832937937.The code for user.jsp is as follows.
String data ="";
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
data += rs.getString("user_registeration_code")+" " ;
System.out.println("-------a------"+data);
}
secondjsp is sys.jsp.In that i have used the ajax and getting the result of the above jsp in response.the code of the sys.jsp is as follows.
function showEmp(emp_value)
{
var fname = document.getElementById("txtfirstname").value;
alert(fname);
var lname = document.getElementById("txtlastname").value;
alert(lname);
if(document.getElementById("txtmobileno").value!="")
{
alert("1");
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{alert("2");
alert ("Browser does not support HTTP Request");
return;
}
var url="getuser.jsp";
url=url+"?emp_id="+emp_value+"&firstname="+fname+"&lastname="+lname;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
else
{
alert("Please Select Employee Id");
}
}
function stateChanged()
{
document.getElementById("txtfirstname").value ="";
document.getElementById("txtmobileno").value ="";
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
var showdata = xmlHttp.responseText;
var strar = showdata.split(" ");
alert(strar[0]);
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
i am not getting the expected result like strar[0]=ab9898329379,strar[1]=ab989832937937.
please help.
Thanks in advance
Rushang
Use for loop to get values
for (var i = 0; i < strar .length; i++) {
alert(strar[i]);
}

Parsing or using variables from a called script?

I have an AJAX function which loads content from a file and displays in the file that called it.
But the script that was called I want to loop an array which is actually set in the script that called it... this is main script that calls the file:
function call_file(file, div_id) {
var xmlhttp;
if(window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(div_id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send();
}
var global = new Array();
global[0] = 1;
global[1] = 2;
call_script('html.html', 'main');
html.html is the file that is called which has this:
<script>
i = 0;
for(var id in global) {
alert(i + ' = ' + id);
i++;
}
</script>
Is this at all possible?
One way is to extract the script and eval it yourself. For example:
//....
document.getElementById(div_id).innerHTML = xmlhttp.responseText;
var str = xmlhttp.responseText;
var reg = /<script>([^>]*)<\/script>/img;
while(reg.test(str))eval(RegExp.$1);
//...

Categories