Ajax function content type - javascript

I don't know ajax very well but have the following function:
function saveViaAJAX() {
var canvasData = $("#wPaint").wPaint("image");
var postData = "canvasData="+canvasData;
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function() {
if (ajax.readyState == 4) {
document.getElementById("debugFilenameConsole").innerHTML="Saved as<br><a target='_blank' href='"+ajax.responseText+"'>"+ajax.responseText+" </a><br>Reload this page to generate new image or click the filename to open the image file in a new window.";
}
}
ajax.send(postData);
}
This works fine but I have another variable i want to pass to testSave.php
<select id="website_string" name="website_string">
<option value="" selected="selected"></option>
<option value="A4">A4</option>
<option value="A5">A5</option>
</select>
I'm trying to pass this in the same function but it's ("Content-type", "application/x-www-form-urlencoded") I think.

Related

$_GET JavaScript and AJAX...

I am relatively new to PHP and I am (trying to) developing my first AJAX code...
I am trying to pass an attribute from a select with several options, each option with its very own unique attribute "values" that is a String.
The PHP file GETs the value and does something with it (for instance prints it out). And the generated file is then returned to my main HTML page.
Here is the source code...
Here is my javaScript:
function showUser(myElement) {
var str = myElement.options[myElement.selectedIndex].getAttribute("values");
if (str == "") {
document.getElementById("myResponse").innerHTML = "";
return;
} 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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myResponse").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
}
My HTML is as following:
<form>
<select name="users" onchange="showUser(this)">
<option values="">Select a person:</option>
<option values="Rasmus Lerdorf">Creator of PHP</option>
<option values="Linus Torvalds">Developed Linux</option>
<option values="Dennis Ritchie">Developper of C</option>
</select>
</form>
<br>
<div id="myResponse"><b>Person info will be listed here...</b></div>
My PHP is:
<?php
$q = intval($_GET['q']);
echo $q;
?>
I get 0 instead of the text string, what is wrong with my code?
Silly me,
I copied and pasted a basic example from a tutorial and I did not realize that the PHP code was casting the string that was sent over the GET to an integer.
$q = intval($_GET['q']);
The code should be :
$q = $_GET['q'];
On my earlier stage of the development I was indeed passing an integer, so the code was working.
The code returned 0 instead of an error because the intval of a string is 0 on failure.
Writing down the question here I realized the mistake...

Wordpress and Ajax

I've have created a custom table in mysql. I've entered a bit of test data just to see if I can pull some results. The query was successful when I ran it just in the template, so I know it works. As I have tried to convert it into a Ajax request seems that no data is being passed. I'm not sure what it is I am missing, or possibly an error I have entered somewhere, but it seems when I try to turn it into an Ajax request nothing happens.
Any ideas?
PHP
$q = intval($_GET['q']);
$pull = $wpdb->get_results(
"
SELECT ID, department, contact, forms
FROM referrals
WHERE ID = '$q'
"
);
foreach ( $pull as $requestdata)
{
echo $requestdata->department;
echo '<br />';
echo $requestdata->contact;
echo '<br />';
echo $requestdata->forms;
}
AJAX
<script>
function displayData(str) {
if (str=="") {
document.getElementById("txt").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","<?php echo content_url(); ?>/themes/child/get-referral.php?q="+str, true);
xmlhttp.send();
}
</script>
HTML
<select name="users" onchange="displayData(this.value)">
<option value="">Select a person:</option>
<option value="1">Test 1</option>
<option value="2"Test 2</option>
</select>
<br>
<div id="txt"></div>
You need to change your ajax request to wp-admin/admin.ajax.php.
If you open that file you will find there is a constant setting named DOING_AJAX. Only the requests to this link can avoid the normal header being sent to browser because of setting DOING_AJAX to ture.
Actually you can debug like this: visit <?php echo content_url(); ?>/themes/child/get-referral.php?q=xx, you will find there are other info sent. thats why that ajax doesnt work.
Switched to this. Hopefully it helps someone else out.
HTML
<select id="mySelect" onchange="pullData()">
<option value="">Select</option>
<option value="options">options</option>
<option value="someother1">someother1</option>
<option value="someother_2">someother_2</option>
</select>
<div id="referral">Test</div>
AJAX / JS
<script>
function pullData() {
var xhttp;
//url variables
var url = "/wp-content/referrals/";
var selectedValueIs = document.getElementById("mySelect").value;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("referral").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", url+selectedValueIs+'.txt' , true);
xhttp.send();
}
</script>

dependent drop downlist generation

I'm trying to make a dependent dropdown list using ajax and php but not able to get the desired result
here is my code of ajax
<html>
<head>
<title>findperson</title>
<script type="text/javascript">
function configureDropDownLists(ddl1,ddl2) {
var x=ddl1.value;
var service;
var url='service.php?data='+x;
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP");
}
if(XMLHttpRequestObject) {
XMLHttpRequestObject.open("GET",url);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
service=XMLHttpRequestObject.responseText;
for (var i=0;i<service.length;i++ ){
var opt = service[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
ddl2.appendChild(el);
}
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<form method="post" action="problem.php">
<select name="city" id="city" onchange="configureDropDownLists(this,document.getElementById('service'))">
<option selected="selected" value="">City</option>
<option value="jhansi">Jhansi</option>
<option value="lucknow">Lucknow</option>
</select>
<select id="service">
<option selected="selected" value="">Service</option>
</select>
<input type="submit" name="proceed" value="Next"/>
</form>
</body>
</html>
this is my php file
<?php
include_once('db.php');
$db=new db();
$sql=$db->database_initialise();
$city=$_GET['data'];
$query="select service_name from service_offered where city='$city'";
if($result=$sql->query($query)){
if($result->num_rows >0){
$i=0;
while($row=$result->fetch_array()){
$service[$i]=$row[0];
$i++;
}
}
}
var_dump($service);
?>
problem is that in second dropdown list no changes occur on selecting a city
Replace var_dump($service)
echo json_encode($service);
A couple of problems here:
your PHP is not sending the correct response. What you want to do is have PHP send a JSON response.
once PHP sends this JSON response, you then need to parse this into an object
Once your response is in object format, you can then iterate through the results.
Try this:
PHP (this is an example of what will be returned from your DB):
$response = array(
array(
"id" => "1",
"name" => "something"
)
);
header('Content-Type: application/json');
echo json_encode($response);
JS:
function configureDropDownLists(ddl1, ddl2) {
var url = 'submit.php?data=' + ddl1.value;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = xmlhttp.responseText;
var obj = JSON.parse(json);
for (var i = 0; i < obj.length; i++) {
var opt = obj[i];
var el = document.createElement("option");
el.textContent = opt.name;
el.value = opt.id;
ddl2.appendChild(el);
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
Your issue is that you are returning the $service array from your PHP and accessing it in your AJAX as a string. service=XMLHttpRequestObject.responseText; returns a string object. In your for loop it looks like you are trying to index through an array. However, you can't index through a string like that and get what you are expecting.
The best thing is to use echo json_encode($service); like Leo suggested, then in your AJAX transform the responseText by using JSON.parse
var json = JSON.parse(XMLHttpRequestObject.responseText);
Then in the for loop
var opt = json[/*i or column name*/];
or
var opt = json.service_name[i];
Note: To return a JSON string in PHP, you have to set the header: header("Content-type: application/json");
Hope that helps!

in 3 dependent box, 3rd box is not populating value using ajax and vbscript in asp classic

I am populating 3(triple) dependent box using ajax and vbscript in asp classic page. 1st and 2nd boxes working ok. if i select STATE in 1st box then, in 2nd box CITY list is populating but when i select 2nd box (CITY), in 3rd box CENTER list is not populating.
my ajax script as below given:
<script language="javascript" type="text/javascript">
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getcity(stateId) {
var strURL="findcity1.asp?state="+stateId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
function getCenter(StateId,CityId) {
var strURL="findCenter.asp?state="+stateId+"&city="+cityId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('centerdiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
My code for populating STATES, CITY AND CENTER as below given
<%
dim Objrs_state, str_state, objCmd_state
Set objCmd_state = Server.CreateObject("ADODB.Command")
Set Objrs_state = Server.CreateObject("ADODB.Recordset")
str_state = "SELECT ASId, ASName FROM State_Name ORDER BY ASName Asc"
With objCmd_state
.ActiveConnection = MM_connDUdirectory_STRING
.CommandText = str_state
.CommandType = adCmdText
end with
Objrs_state.open objCmd_state, , 1, 2
%>
<select name="statid" onChange="getcity(this.value)">
<option>Select State</option>
<%while not Objrs_state.eof%>
<option value="<%=Objrs_state("ASId")%>"><%=Objrs_state("ASName")%></option>
<%Objrs_state.movenext
wend
Objrs_state.close
set Objrs_state = nothing
set objCmd_state = nothing%>
</select>
'populating CITY as below given
<span id="citydiv"><select name="city">
<option>Select City</option>
</select></span>
'populating CENTER as below given
<span id="centerdiv"><select name="center">
<option>Select Center</option>
</select></span>
FindCity.asp
Set objCmd = Server.CreateObject("ADODB.Command")
Set Objrs = Server.CreateObject("ADODB.Recordset")
str = "SELECT * FROM city_Name where ASId =? ORDER BY ACName Asc"
....
....
<select name="city" onChange="getcenter(stateID,this.value)">
<option>select city</option>
<% Do While Not Objrs.EOF %>
<option value="<%=objrs("ACId")%>"><%= Objrs("ACName")%></option>
<%
Objrs.MoveNext
Loop
%>
</select>
FindCenter.asp page
Set objCmd = Server.CreateObject("ADODB.Command")
Set Objrs = Server.CreateObject("ADODB.Recordset")
str = "SELECT * FROM Center_Detail where Center_state=? and Center_city=? ORDER BY Center_Name Asc"
....
....
<select name="center">
<option>select center</option>
<% Do While Not Objrs_center.EOF %>
<option value="<%=objrs_center("CnId")%>"><%= Objrs_center("Center_Name")%></option>
<%
Objrs_center.MoveNext
Loop
%>
</select>
1st and 2nd box populating and working fine but in 3rd box center list related to select city is not showing. Please help me out to solve this issue.

2 select menu filters with Jquery disable, pass values to one function

I have 2 select menus whose values i want to get passed to a function.
I am trying to use jquery to disabled the 2nd select until the first one is selected.
I am having 2 issues with this:
My jquery does not seem to want to disable the 2nd select menu.
Also how can i pass the 1st select menu value to the onchange
function value in the second select menu.
Thanks in advance
Function
function showlog(str, username) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getlog.php?username=" + username + "&q=" + str, true);
xmlhttp.send();
}
JQUERY
$(document).ready(function() {
var linkOrder = [
"employee_user",
"acyear"
];
$('select.linked').not('#' + linkOrder[0]).attr('disabled', 'disabled');
$('.linked').change(function() {
var id = $(this).attr('id');
var index = $.inArray(id, linkOrder);
$('#' + linkOrder[index + 1]).removeAttr('disabled');
});
});
FORM
<form>
<select id="employee_user" name="employee_user" class="linked">
<option value="">Select</option>
</select>
<select id="acyear" name="acyear" onchange="showlog(this.value, 1st select value" class="linked">
<option value=""></option>
</select>
</form>

Categories

Resources