I want to validate groupname.
I am using ajax but it is not working
This is my view
<?php echo form_input(['name'=>'groupname','class'=>'form-control','placeholder'=>'Enter group name','value'=>'','ng-model'=>'myWelcome[0].groupname','onkeyup'=>'loadValid(this.value)']) ?>
Javascript function
<script type="text/javascript">
function loadValid(v) {
if(v)
{
var url= window.location.href;
var res = url.split("/");
var groupid = res[res.length-1];
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", site_url + "admin/Usergroup_controller/store_edit_group_name_ajax/" + groupid + "/" + v, true);
xhttp.send();
}
else
{
document.getElementById("demo").innerHTML = "Group name is required field.";
}
}
</script>
Controller function
public function store_edit_group_name_ajax($groupid,$groupname)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('groupname', 'Group name', 'trim|required|alpha|is_unique[group.groupname]|min_length[3]');
if( $this->form_validation->run() )
{
echo form_error('groupname','<p class="text-danger">','</p>');
}
}
Please help...
Make sure you are creating a response object first.
$response = new stdClass();
if ($this->form_validation->run() == false)
{
$response->status = 'failure';
$response->error = validation_errors('<p class="text-danger">', '</p>');
}
...
return $response;
In Javascript after getting response;
document.getElementById("demo").innerHTML = xhttp.responseText.error;
Just echo-ing ajax results is something you need to leave immediately. Please take it as a friendly advise.
Related
I am uploading a file using FormData as following
<script>
var form = document.forms.namedItem("excelForm");
form.addEventListener('submit', function(ev) {
oData = new FormData(form);
oData.append("CustomField", "This is some extra data");
var oReq = new XMLHttpRequest();
oReq.open("POST", "excel", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
$("#downloadButton").attr("style", "visibility: visible;")
alert(oReq.response)
} else {
alert(oReq.status)
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
</script>
and this will call a php function and that function will return a vlue so I want to capture that value I used oReq.response to capture that return value but it did not work
this is my php function
public function actionexcel()
{
//.........
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// re write the excel file
$fileName =$date. basename($_FILES["fileToUpload"]["name"]);
$newFile = $this->RewriteExcel($fileName);
return $fileName;
} else {
echo ini_get('upload_max_filesize');
echo "Sorry, there was an error uploading your file.";
}
}
return $data;
}
In your JavaScript:
var form = document.forms.namedItem("excelForm");
form.addEventListener('submit', function(ev){
oData = new FormData(this);
oData.append("CustomField", "This is some extra data");
var oReq = new XMLHttpRequest();
oReq.onreadystatechange= function(oEvent){
if(this.readyState == 4 && this.status == 200){
$("#downloadButton").attr("style", "visibility: visible;")
alert(this.responseText)
} else {
alert(this.status);
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
// ensure that your php file is in the correct directory and is using '.php'
oReq.open("POST", "./excel.php");
// don't forget to send
oReq.send();
In your PHP file:
// your class and method goes here
public function actionexcel(){ ... }
echo $class->actionexcel();
I am trying to create a user registration page within one of my wordpress page files. When making a call to ajax and using the admin-ajax.php file as the url, i am encountering a 400 error. The functions where the ajax calls are occurring are shown below:
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "<?php echo admin_url('admin-ajax.php'); ?>");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var fn = _("fname").value;
var ln = _("lname").value;
var m = _("major").value;
var phone = _("phone").value;
var blazeid = _("blazerid").value;
var status = _("status");
if(p1 != p2){
status.innerHTML = "Your password fields do not match";
}else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "<?php echo admin_url('admin-ajax.php'); ?>");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&fn="+fn+"&ln="+ln+"&m"+m+"&phone"+phone+"&blazeid"+blazeid);
}
}
This is located inside one of my page files within the theme directory. Is there anyone that can help me with this? Thank you.
You need to define Ajax function in this way
function checkusername(){
}
add_action( 'wp_ajax_checkusername', 'checkusername' );
add_action( 'wp_ajax_nopriv_checkusername', 'checkusername' );
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "index.php?dispatch=paysrk.paymod?amount="+str, true);
alert(+str);
xmlhttp.send();
}
}
</script>
i think problem is here.Amount is not geting .url is not working.
index.php?dispatch=paysrk.paymod?amount
Question updates:-
My requirements:
When i click the unsubscribe button status in the database change to "US" and change UNSUBSCRIBE button to SUBSCRIBE. A notification with unsubscription completed
If your request is done from CS-Cart environment please try:
<script>
function showHint(str){
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
$.ceAjax('request', fn_url('paysrk.paymod'), {
method: 'get',
caching: false,
hidden:true,
data: { 'amount': str },
callback: function(data){
alert(data);
}
});
}
}
</script>
i think your problem is in the url syntax.
the first parameter to pass to the url is after ? and all the other parameters should preceded with &
so your GET url should be like this
index.php?dispatch=paysrk.paymod&amount
xmlhttp.open("GET", "index.php?dispatch=paysrk.paymod&amount="+str, true);
you do exactly like this.
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "index.php?dispatch=paysrk.paymod?amount="+str, true));
alert(+str);
xmlhttp.send();
}
}
</script>
I want to know where is gsmarena.com put ajax url when they do a search. I tried to explore the source of it and I found this function:
function autocompleteLoadList() {
if (AUTOCOMPLETE_LIST !== null) return;
AUTOCOMPLETE_LIST = false;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP")
} catch (x) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
} catch (x) {
AUTOCOMPLETE_LIST = null
}
}
}
xhr.open("GET", AUTOCOMPLETE_LIST_URL, true);
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4)
if (xhr.status == 200) {
var data;
if (window.JSON) {
data = JSON.parse(xhr.responseText)
} else {
data = eval("(" + xhr.responseText + ")")
}
AUTOCOMPLETE_MAKERS = data[0];
AUTOCOMPLETE_LIST = data[1];
if (typeof AUTOCOMPLETE_CALLBACK != "undefined") AUTOCOMPLETE_CALLBACK()
} else {
AUTOCOMPLETE_LIST = null
}
};
xhr.send(null)
}
http://cdn2.gsmarena.com/w/js/autocomplete.js?ver=2
I do not know where they put the url to doing a search.
when I open the network tab in Google Chrome console there is also no url to POST or GET. how could they do it?
I want to make a php ajax post.(post value without refresh the page) here is my code. It can return the value and show in <div id="msg"></div>, But I also want to use this value.
In #benhowdle89 's help, I made $name= "<div id='msg'></div>". but when I use echo $name, in the source code, I can see <div id='msg'></div>(html tag), this is not a pure value, so I tried to use strip_tags, but the value lost. it seems the left the ajax pointed div tag, the value also gone. Still waiting for help...
index.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
</script>
</head>
<body>
<?php
echo $name="<div id='msg'></div>";
$name1=strip_tags($name);
$name2 = explode("|",$name1);
$namea=$name2[0];
$nameb=$name2[1];
?>
<form name="user_info" id="user_info" method="post">
<input name="user_name" type="hidden" value="abc|def" /><br />
<input type="button" value="abc|def" onClick="saveUserInfo()">
</form>
</body>
value.php
<?php
echo $_POST["user_name"];
?>
This is what I want. post value from index.php, then get the value by self without refresh the page. one botton with two values, I want explode them and finally get $namea and $nameb. I want use them in other php part.
You can put the ajax response into a javascript variable, then you can manipulate it from there:
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
alert( myPhpVariable );
Here is a working javascript example (full code):
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
The PHP file would look like:
$postVar = $_POST["user_name"];
$postVarArr = explode('|', $postVar);
// will show abc
//echo $postVarArr['0'];
// will show def
echo $postVarArr['1'];
by including $name= "<div id='msg'></div>" and calling echo $name, you're just telling the program to store "" in the $name variable and then print what is stored in that variable. That's why you're getting the unwanted output.
not sure if you're having problems posting the value or showing it in the value, but you need to echo the variable where the userName is stored, may need to send that from the ajax to the php and set it to $name.