jQuery.validator.addMethod("uniquerheading", function(value, element) {
var data = false;
$action_name = 'checkunquieannoucementheading';
var url = '<?php echo "$module_name/$controller_name/checkunquieannoucementheading"; ?>';
$.ajax({
url: url,
type: 'get',
data: {
"txt_heading":value
},
success: function(data) {
// Display list on the page by replacing the content on existing, get from the controller-action
return data;
}
});
}, "Annoucement heading already used");
Working Code...Just use async: false
jQuery.validator.addMethod("uniquerheading", function(value, element) {
$action_name = 'checkunquieannoucementheading';
var response = false;
var url = '<?php echo "$module_name/$controller_name/checkunquieannoucementheading"; ?>';
$.ajax({
url: url,
type: 'get',
data: {
"txt_heading":value
},
success: function(data) {
// Display list on the page by replacing the content on existing, get from the controller-action
response = data;
},
async: false
})
return response;
}, "Annoucement heading already used");
Related
I want the html value of AJAX in outside of AJAX Call or in the $('#username').blur(function() function.. Is this possible ?
<script>
$(document).ready(function() {
$('#username').blur(function() {
var username = $(this).val();
availibilityCheck(username);
})
function availibilityCheck(username) {
var result = "";
$.ajax({
url: "action.php",
method: "POST",
data: {
action: "availibilityCheck",
data: username
},
dataType: "text",
success: function(html) {
$('#usernameresponse').html(html);
}
})
}
});
</script>
<script>
$(document).ready(function() {
$('#username').blur(function() {
var username = $(this).val();
availibilityCheck(username);
var return_first;
function callback(response) {
return_first = response;
//use return_first variable here
}
})
function availibilityCheck(username) {
var result = "";
$.ajax({
url: "action.php",
method: "POST",
data: {
action: "availibilityCheck",
data: username
},
dataType: "text",
success: function(html) {
callback(html);
$('#usernameresponse').html(html);
}
})
}
});
</script>
I want to retrieve the session value and pass that value as required parameter for the api. My session is $_SESSION['name']. And these are my codes
var uniqueName = **Here I want to retrieve session value**;
if(**Then I want to check if uniqueName is null or undefined**) {
$.ajax({
url: 'http://api/check.php',
type: 'GET',
crossDomain: true,
dataType:'json',
data: {
name: uniqueName
},
success: function(result) {
alert("Success");
},
error: function(result) {
alert("Error");
}
});
}
return false;
});
You can put PHP directly into your JS, like
var uniqueName = '<?php echo isset($_SESSION['name']) ? $_SESSION['name'] : '' ?>';
In JS will be name or empty string.
If you haven't this JS in PHP file, you can pass a session using AJAX call, or assign to any HTML element.
<input type="hidden" id="session_var" value="<?php echo isset($_SESSION['name']) ? $_SESSION['name'] : '' ?>">
And in JS file then:
var name = document.getElementById('session_var'); // name from session or empty string.
var uniqueName = "<?php echo $_SESSION['name'] ?>";
if(uniqueName) {
$.ajax({
url: 'http://api/check.php',
type: 'GET',
crossDomain: true,
dataType:'json',
data: {
name: uniqueName
},
success: function(result) {
alert("Success");
},
error: function(result) {
alert("Error");
}
});
}
return false;
});
References:
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
http://www.dyn-web.com/tutorials/php-js/scalar.php
$("#home").on("pageload", function() {
console.log("test2");
var url = window.location.search;
var split = url.split('=');
var vendorID = split[1];
$.ajax({
type: "POST",
url: "vendorpull.php",
data: 'id=' + vendorID,
cache: false,
success: function(data)
{
document.getElementById('vendor-data').innerHTML = data;
}
});
});
This code does not seem to be firing unless the page is physically refreshed. I've tried pageshow, pagebeforeshow and others and it doesn't change. The test console.log does not even fire. This event should be trigged as soon as vendor.html?id=1 is loaded, that is the page that is navigated to containing the above AJAX code. Any suggestions?
$("#home").ready(function() { //You can also use $(document).ready(function() {
console.log("test2");
var url = window.location.search;
var split = url.split('=');
var vendorID = split[1];
$.ajax({
type: "POST",
url: "vendorpull.php",
data: 'id=' + vendorID,
cache: false,
success: function(data)
{
document.getElementById('vendor-data').innerHTML = data;
}
});
});
This code for jQuery Mobile 1.4.5 will reload data for every page visit:
$(document).on("pagecontainerbeforeshow", function(e, ui) {
var pageId = $(":mobile-pagecontainer").pagecontainer("getActivePage").prop("id");
/* JQM NAVIGATE #2 */
if (typeof ui.toPage == "object") {
/* manipulate page navigating to */
switch (pageId) {
case "home":
var url = window.location.search;
var split = url.split('=');
var vendorID = split[1];
$.ajax({
type: "POST",
url: "vendorpull.php",
data: 'id=' + vendorID,
beforeSend: function() {
$.mobile.loading("show");
},
cache: false,
success: function(data) {
$("#vendor-data").html(data);
$("#home .ui-content").trigger("updatelayout");
},
complete: function() {
$.mobile.loading("hide");
},
error: function() {
$.mobile.loading("hide");
}
});
break;
default:;
}
}
});
Okay, below I have attached my chatroom script, What I'm trying to implement is a script which replaces specific words like :wow with an image <img src="wow.gif"></img> I previously used the following to achieve this;
var newdata = data.replace(/:wow/g,"<img src=\"wow.gif\"></img>");
however where I've recently redone my chatroom javascript I don't know where to place this or if this would even work with my updated script. Below is the JavaScript that loads my chatroom. Thankyou for any help.
var instanse = false;
var state;
var mes;
var file;
function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}
//gets the state of the chat
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/_account/_pages/chat_room_scripts/process.php?room=<? echo $room; ?>",
data: {
'function': 'getState',
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/_account/_pages/chat_room_scripts/process.php?room=<? echo $room; ?>",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
$('#chat-area').append($("<p>"+ data.text[i] +"</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
//send the message
function sendChat(message, nickname)
{
updateChat();
$.ajax({
type: "POST",
url: "/_account/_pages/chat_room_scripts/process.php?room=<? echo $room; ?>",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
updateChat();
},
});
}
It appears your update is referencing the chat content within an array of string data, in which case you'll reference data.text[i] within the for loop. Try this:
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/_account/_pages/chat_room_scripts/process.php?room=<? echo $room; ?>",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
// UPDATE HERE
$('#chat-area').append($("<p>"+ data.text[i].replace(/:(wow|hi)/g,"<img src=\"$1.gif\"></img>")+"</p>"));
// UPDATE HERE
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
General Purpose Replacement
You can customize your emoticons by just adding them to the capture group separated by pipes:
replace(/:(wow|hi|fish|tiger|dog|elephant|bird)/g,"<img src=\"$1.gif\"></img>")
option 1:
if you want the code in the javascript, then in updateChat() where you are appending the html to #chat-area you could apply the same code. eg:
var newdata = data.replace(/:wow/g,"<img src=\"wow.gif\"></img>");
$('#chat-area').append($("<p>"+ newdata +"</p>"));
option 2:
do the replacement in the server side AJAX code. This way you don't have to keep updating javascript to add new image translations.
And don't hardcode them, store the translations in a db table or file so you can easily add new ones.
Hello guys I have a problem in getting the response from my ajax. If I display it in the console. I can view it. But How do I assign it in a variable?
Here's what I have.
In my PHP code I have this
public function checkPassword($password){
$username = $this->session->userdata('username');
$validate = $this->members_model->checkPassword($password,$username);
echo $validate;
}
In my jquery I have this
$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
var g = response;
if(g == 1){
$('#existing_info').html('Password is VALID'); //Doesn't display the VALID if the response is 1. Why?
}else{
$('#existing_info').html('Password is INVALID!');
}
}
});
});
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
var k=response;
if(k.indexOf("1") != -1)
$('#existing_info').html('Password is VALID');
else
$('#existing_info').html('Password is INVALID!');
}
});
response is in response variable of success function.
indexof returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex,
returns -1 if the value is not found.
try something like this
<script>
var k = null;
$(function(){
$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
if(response == 1){
k = response;
}
}
});
});
})
</script>
In your success response you will get what you are set to output in php.
If you want to get an array or data set you can encode it in json in your php script like
echo json_encode($validate);
Then in your jquery you can use this response like this
var responseData = jQuery.parseJSON(response);
console.log(responseData);
console.log will print json object in browser console.
You can use this json object like this
responseData.some_data
Ajax is asynch so you will have access to it after the ajax method returns:
$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json'
}).then(function(response){
var k;
if(response == 1){
k = response;
//call another function that needs k here
}
});
});
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
k=response;
}
});
var k = null;
$('#existing').on('keyup', function() {
var id = '<?php echo $this->session->userdata("user_id"); ?>',
password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type : 'POST',
url : password_url,
success : function(data) {
if(data === '1') {
k = data;
}
}
});
});
response parameter itself contain data so just assign that to variable and use it.
$.ajax({
type: 'POST',
url: password_url,
success: function(response){
if(parseInt(response) == 1){
var k = response;
}
}
});
Your response data is in response variable of success function. Since the response type is json you can assign it directly to javaScript variable.
Also you comparison is wrong try if(g == '1') instead if(g == 1). You are getting a string as response and your checking equality with a numeric type which won't be equal at any point.
ie:-
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
contentType:"application/json",// Add Content type too
success: function(response){
k=response;
}
});
if your json response is as shown below
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
you can access menuitem array as
success: function(response){
k=response.menu.popup.menuitem;
}
File Name votepost.php
<?php
include("domain.php");
$csid=$_POST['CSID'];
$voteid=$_POST['VOTEID'];
$myid=$_POST['MYID'];
$usertype=$_POST['USERTYPE'];
$myurl =URL."putvote.php?csid=".$csid."&voterid=".$myid."&voteid=".$voteid."&usertype=".$usertype;
$myurl=str_replace(" ","%20",$myurl);
$jsondata = file_get_contents($myurl);
$data = json_decode($jsondata);
if($data->response=="true")
{
echo 'true';
}
else
{
echo 'false';
}
?>
ajax reponse use $.trim for IF ELSE
$.post("votepost.php", {CSID:csid,VOTEID:voteid,MYID:myid,USERTYPE:usertype}, function (data) {
if($.trim(data)=='true')
{
alert('ok');
}
else
{
alert('error');
}
});
I hope you will solve your problem
You can create the js blank array and assign it to the same array.
var resp = [];
jQuery.ajax({
dataType: "json",
method: 'post',
url: 'ajax.php',
async: false,
data: {postData: 'postData'},
success: function(data){
resp.push(data);
}
});