Hi there I have Problem with my Code I just want to validate States which is generated from Ajax response.text
Here is the JQuery for State Field:
$(document).ready(function () {
var form = $("#addStudentfrm");
var state = $("#state");
var stateInfo = $("#stateInfo");
state.blur(validateStates);
state.keyup(validateStates);
function validateStates() {
if (state.val() == '') {
state.addClass("error");
stateInfo.text("Please Select/Enter State");
stateInfo.addClass("error5");
return false;
} else {
state.removeClass("error");
stateInfo.text("");
stateInfo.removeClass("error5");
return true;
}
}
});
Here PHP Function for Get All States in Respected Country:
public function getAllCountryStates($post){
$que = "Select * from ".WMX_COUNTRY." where code = '".$post[value1]."'";
$cRes = $this->executeQry($que);
$cResult = $this->getResultRow($cRes);
$cId = $cResult['id'];
$stateObj = new Admin;
$rdat = $post['opr'];
$rdtar = explode('.', $rdat);
$res = #mysql_fetch_row(mysql_query("Select * from ".$rdtar['1']." where id = ".$rdtar['0']));
$usts = $res['state'];
$result = $stateObj->selectQry(WMX_STATE,"country_id=$cId",'','');
$number = $stateObj->getTotalRow($result);
if($number > 0){
$getSelect ="<select name='state' id='state' class='textboxcss'>";
while($stateVal = $stateObj->getResultRow($result)){
$getSelect.="<option value='".$stateVal[state]."'>$stateVal[state]</option>";
}
$getSelect.="</select>";
}else{
if($usts!=''){
$getSelect = "<input type='text' name='state' id='state'class='textboxcss' value='$admnState'/>";
} else {
$getSelect = "<input type='text' name='state' id='state' class='textboxcss'/>";
}
}
echo $getSelect; }
In the Initial State Text box getting validate
but when the control comes with the Ajax Response Jquery wont validate it for Blank Entries
my Ajax Function:
function DataByPost(url,objId,postData,div_id){
var selId = objId.split('|');
var passData = postData;
var AJAX = null;
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX==null) {
alert("Your browser doesn't supportAJAX.");
return false
} else {
AJAX.open("POST",url,true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.onreadystatechange = function() {
if (AJAX.readyState==4 || AJAX.readyState=="complete"){
alert(AJAX.responseText);
var msg=AJAX.responseText;
var idary = new Array();
document.getElementById(selId).value = msg;
document.getElementById(selId).innerHTML = msg;
}
}
AJAX.send(passData);
}
}
//First Function
function showContent(url,arg,opr,sel_id,div_id)
{
var postData='';
var formVal=arg.split('|');
if(document.getElementById(div_id))
document.getElementById(div_id).style.display='';
if(document.getElementById(sel_id))
document.getElementById(sel_id).style.display='';
for(i=1;i<=formVal.length;i++)
var postData =postData + 'value'+i+'='+escape(formVal[i-1])+'&';
postData=postData + 'opr='+opr;
DataByPost(url,sel_id,postData,div_id);
}
I don't know exactly what is going on here without seeing the actual page, but a few things you might try:
Use jQuery to do your ajax since you're already using it. It is bug-free and cross platform, and that way you can be sure there are no bugs in the ajax part.
I would move the lines "var state = $("#state"); var stateInfo = $("#stateInfo");" inside of the function then declare the function outside of your document.ready block. That way you can be sure that every time the function gets called, it has access to the variables.
If your ajax call is replacing the input you're validating, you'll need to re-bind the events each time your ajax call finishes. With jQuery you can do this using the callback parameter.
I'm assuming number 3 is your problem, so try it first.
Related
My checkboxes are empty when page refreshes after submit. I would like to keep them checked. How can I do that in jquery?
Here is my jquery code.
$(document).ready(function () {
$(':checkbox.selectall').on('click', function () {
$(':checkbox[id="' + $(this).data('checkbox-name') + '"]').prop("checked", $(this).prop("checked"));
$( "#frm1" ).submit();
});
$(':checkbox.checkme').on('click', function () {
var _selectall = $(this).prop("checked");
if (_selectall) {
$(':checkbox[name="' + $(this).attr('name') + '"]').each(function (i) {
_selectall = $(this).prop("checked");
return _selectall;
});
}
$(':checkbox[name="' + $(this).data('select-all') + '"]').prop("checked", _selectall);
$( "#frm1" ).submit();
});
});
My html is as follows...
<input type='checkbox' id='selectall' name='sa_subcatinput[]' value='$row[id]'
data-checkbox-name='$row[id]' class='selectall'/></label></a></li>
<input type='checkbox' name='subcatinput[]' value='$test[id]' id='$test[category]'
class='checkme' data-select-all='sa_subcatinput[]'/>
You cannot do this unless you send a value back to your page which indicates the checkbox to be checked.Since you said the page refreshes, a server communication is happened. So you may use ajax to keep the check box checked
Pass a querystring parameter of the id or number or value or whatever of the checked checkbox.
request the parameter using server side code or a client-side javascript using a get parameter function (there on many on this site).
rechecked the box using your custom function and the value returned.
$('#ckeckbox1').val(unescape(getParam(document.URL,'checkbox1')));
function getParam(url,name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if( results == null )
return "";
else
return results[1];
}
function removeParameter(url, parameter) {
var urlparts= url.split('?');
if (urlparts.length>=2) {
var urlBase=urlparts.shift(); //get first part, and remove from array
var queryString=urlparts.join("?"); //join it back up
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;) //reverse iteration as may be destructive
if (pars[i].lastIndexOf(prefix, 0)!==-1) //idiom for string.startsWith
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
}
return url;
}
I was able to get the code working with php. Here is the code I inserted in the input to make it work.
echo"<input type='checkbox' id='selectall' name='sa_subcatinput[]' value='$row[id]'
data-checkbox-name='$row[id]' class='selectall'";
if (isset($_POST['sa_subcatinput'])) {
if (in_array($row['id'], $_POST['sa_subcatinput'])) {
echo"checked='checked'";
}
}
echo"/>
echo"<input type='checkbox' name='subcatinput[]' value='$test[id]'
id='$test[category]' class='checkme' data-select-all='sa_subcatinput[]'";
if (isset($_POST['subcatinput'])) {
if (in_array($test['id'], $_POST['subcatinput'])) {
echo"checked='checked'";
}
}
echo"/>
I have a file input declared as follows:
<input id = "front_photo" type = "file" name = "front_photo" onchange = "send_photo()" />
The function it calls is declared as follows:
function send_photo ()
{
var fileInput = document.getElementById('front_photo');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('front_photo', file);
console.log("in");
var ajaxHandler = new XMLHttpRequest();
ajaxHandler.onreadystatechange = function ()
{
if(ajaxHandler.readyState == 4)
{
var picture_box = document.getElementById("polaroids_holder");
var adder = document.getElementById("add_polaroid");
var new_pic = document.createElement("div");
new_pic.className = "polaroid";
new_pic.style.backgroundImage = "url('/assets/img/temp_front/"+ajaxHandler.responseText+"')";
picture_box.insertBefore(new_pic, adder);
send_photo();
}
}
ajaxHandler.open('POST', 'upload_polaroid', true);
ajaxHandler.send(formData);
}
Selecting a file to upload once causes it to go into an endless loops. The "in" I have there at the top is piling up in the console log, so I'm sure it's the function itself being called repeatedly and not a server side redirect. Also, the images are being created on the server. Here's the PHP for that:
function upload_polaroid ()
{
if(isset($_FILES['front_photo']))
{
$format = explode(".", $_FILES["front_photo"]["name"]);
$format = $format[1];
$filename = md5(mt_rand().microtime(true)).".".$format;
$allowedTypes = array("image/tiff", "image/gif", "image/jpeg", "image/png", "image/x-bmp", "image/x-ms-bmp", ".bmp", ".dib", "image/vnd.microsoft.icon", "image/x-xbitmap", "image/x-xbm", ".xbm", ".cur");
if(in_array($_FILES["front_photo"]["type"], $allowedTypes))
{
if(file_exists(getcwd()."/assets/img/temp_front/".$filename))
{
chmod(getcwd()."/assets/img/temp_front/".$filename,0755);
unlink(getcwd()."/assets/img/temp_front/".$filename);
}
move_uploaded_file($_FILES["front_photo"]["tmp_name"], getcwd()."/assets/img/temp_front/".$filename);
$image_path = "/assets/img/temp_front/".$filename;
echo $image_path;
}
else
{
echo "File is not of a valid image type."; die;
}
}
else
die; //var_dump($_FILES);
}
What could be going wrong here?
When the ajax request is successful the code calls send_photo(); which fires another ajax request and calls the send_photo(); method again when successful. This is causing the code to be recursive.
function send_photo ()
{
var fileInput = document.getElementById('front_photo');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('front_photo', file);
console.log("in");
var ajaxHandler = new XMLHttpRequest();
ajaxHandler.onreadystatechange = function ()
{
if(ajaxHandler.readyState == 4)
{
var picture_box = document.getElementById("polaroids_holder");
var adder = document.getElementById("add_polaroid");
var new_pic = document.createElement("div");
new_pic.className = "polaroid";
new_pic.style.backgroundImage = "url('/assets/img/temp_front/"+ajaxHandler.responseText+"')";
picture_box.insertBefore(new_pic, adder);
/***********************************************/
send_photo(); //this is making the code recursive
}
}
ajaxHandler.open('POST', 'upload_polaroid', true);
ajaxHandler.send(formData);
}
You're calling the send_photo function right from the ajax callback, after you've shown the success via inserting new_pic in the document. That way, it will forever upload the selected file again and again.
how you doing, i've been working on this for 2 hours now and I can't seem to get my page to dynamically display information when I change it. Would appreciate if someone can tell me what went wrong.
This is my HTML
<h2>Feedbacks</h2>
<form>
<select onchange="viewFeedback(this.value);">
<option value="unread">View Unread</option>
<option value="all" >View All</option>
</select>
</form>
<div id="feedbackview"></div>
This is my ajax
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
function viewFeedback(condition) {
http.onreadystatechange = function() {
if(http.readyState == 4) {
document.getElementById('feedbackview').innerHTML=http.responseText;
}
http.open("GET",'viewfeedback.php?condition='+condition,true);
http.send(null);
}
}
and here is the php
$condition = $_GET['condition'];
$db = new db();
$query = $db->query("SELECT * FROM feedback");
$rows = $db->countRows($query);
if($rows != 0) {
$results = $db->getRows($query);
foreach($results as $result) {
extract($result);
echo $name;
}
}
The open() and send() calls should not be within the onreadystatechange event, move them outside. You can also move the event outside from the viewFeedback() too because there's no need to keep re-defining it every time your dropdown is changed.
var http = createObject();
http.onreadystatechange = function() {
if(http.readyState == 4) {
document.getElementById('feedbackview').innerHTML=http.responseText;
}
}
function viewFeedback(condition) {
http.open("GET",'viewfeedback.php?condition='+condition,true);
http.send(null);
}
Also note that you don't do anything with $_GET['condition'] on the PHP side, so the response will always be the same regardless of which dropdown item is selected.
First, I don't know if that Ajax creation function is so great. I would comment it out for now and add it back only if it is not working in a supported browser. Instead just do this:
var http = new XMLHttpRequest();
Next, try hitting the PHP web service directly in your browser. Is it working? If so, fix the issues in your Ajax request:
function viewFeedback(condition) {
http.open("GET", 'viewfeedback.php?condition=' + condition, true);
http.onreadystatechange = function() {
if (http.readyState == 4) {
if (http.status == 200) {
document.getElementById('feedbackview').innerHTML = http.responseText;
} else {
console.log(http.response);
}
}
}
http.send(null);
}
Let me know if this doesn't work.
I have a small form which contains a first name, last name and a date. On clicking to submit the form I want it to check the database for a duplicate entry (with Ajax), and if there is already 1+ entries, present a confirm window confirming another submission. The confirm shouldn't show if there aren't any entries.
For some reason it seems to be presenting the confirm without the result from the Ajax PHP page. If I introduce an alert after the xmlHttp.send(null) line, it gets the text from the PHP (as wanted), making me think I misunderstand the order the code is executed. Here is the code:
Javascript:
function check_duplicates() {
var first = document.getElementById('first_name').value;
var last = document.getElementById('last_name').value;
var date = document.getElementById('event_date').value;
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser does not support AJAX!");
return;
}
var result = "ERROR - Ajax did not load properly";
var url="check_duplicate.php";
url=url+"?first="+first;
url=url+"&last="+last;
url=url+"&date="+date;
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
result = xmlHttp.responseText;
alert("RESULT="+result);
if(result != "clean") {
var validate = confirm(result);
return validate;
}
}
}
xmlHttp.open("GET",url,true);
var test = xmlHttp.send(null);
}
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;
}
PHP:
// DATABASE CONNECTION INFORMATION REMOVED
$first = $_GET['first'];
$last = $_GET['last'];
$date = date('Y-m-d',strtotime($_GET['date']));
$sql = "SELECT COUNT(*) AS count FROM Table WHERE First='$first' AND ".
"Last='$last' AND Date='$date'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if($row['count'] > 0) {
if($row['count'] == 1) {
echo "There is already an entry for ".$first." ".$last." on ".
date('M jS',strtotime($date)).".\n".
"Are you sure you want to submit this entry?";
}
else { // plural version of the same message
echo "There are already ".$row['count']." entries for ".$first." ".
$last." on ".date('M jS',strtotime($date)).".\n".
"Are you sure you want to submit this entry?";
}
} else {
echo "clean";
}
Here is an answer using synchronous AJAX. This way, you don't have to overload the default form handling to get it to work. However, all javascript will be blocked while the confirmation request is running, which means your web page may appear to come to a screeching halt for however long the confirmation request lasts.
This function will return true if the record should be added, and false otherwise.
function check_duplicates() {
var first = document.getElementById('first_name').value;
var last = document.getElementById('last_name').value;
var date = document.getElementById('event_date').value;
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser does not support AJAX!");
return false;
}
var result = "ERROR - Ajax did not load properly";
var url="check_duplicate.php";
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);
xmlHttp.open("GET",url,false);
xmlHttp.send(null);
var validated = true;
var result = xmlHttp.responseText;
if (result != 'clean')
validated = confirm("RESULT="+result);
return validated;
}
This line of code return undefined.
var test = xmlHttp.send(null);
What you have to understand is that the send() call returns immediately and Javascript keeps running. Meanwhile, your AJAX request is running in the background. Also, your onreadystatechange handler is called once the request is done, whether it takes 10ms or 100s, and its return value is not received by the rest of your code.
I think what you wanted to submit the form AFTER the confirmation was finished. You only know when the request is finished from inside your onreadystatechange handler. The problem here is that, in order to wait for the AJAX request to finish you have to override the default behavior of the form.
You'll need to call preventDefault() on the form-submit event, and then submit the data manually after confirmation.
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
var confirmed = false;
var result = xmlHttp.responseText;
if (result == "clean")
confirmed = true;
else
confirmed = confirm("RESULT="+result);
if (confirmed) {
var url = "addData.php";
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);
window.location = url;
}
}
}
Also, when you're building your URL you should use encodeURIComponent.
url=url+"?first="+encodeURIComponent(first);
url=url+"&last="+encodeURIComponent(last);
url=url+"&date="+encodeURIComponent(date);
In Js file I've created a function which has to send an id and return boolean value to php file which returns false or true; but how can I do it?
JS function
function findDB(id)
{
}
PHP side
include_once("kutuphane/inc.php");
$id = $_POST['tipi'];
$sql= "select count(id) from bolge_db where parent_id=$id";
$faz2= $_SESSION["VT"]->doQuery($sql);
$flag=false;
if($faz2>0)
{
$flag= true;
}
else
{
$flag= false;
}
It's simple AJAX! Try out this code in js:
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
keep in mind that you have to echo something in php! eg: echo 1; echo 0;
Or using jQuery
var data = {
var1 : "string or another var"
};
$.post('url.php',data , function(data) {
var response = data;
//Do What Ever You Want
});