how to use if else in jquery ajax code - php

I need to fetch records on the bases of search data and if search data is empty than load
another page as i used the ajax code as below
function search_alumni()
{
$data = $('#search_alumni').val();
if($data.value!='')
{
$this = $(this);
$.ajax(
{
url: 'include/search.php',
type: 'post',
data:{data:$data},
datatype: 'html',
async:true,
success: function(data){
$('table >tbody').append(data);
$result_row = $('table >tbody >tr').length;
// display no result found row
if($result_row == 0) { $('#no_found_result').css('display','');}
else { $('#no_found_result').css('display','none'); }
}
});
}else
{
$this = $(this);
$.ajax(
{
url: 'view/alumni/alumni.php',
datatype: 'html',
async:true,
beforeSend : function(){
// $('#ajax_loader').show();
$('#content').hide();
},
success: function(data){
// $('#ajax_loader').hide();
$box = $('#content');
$box.after(data);
$box.remove();
}
});
}
}
$(document).on('keyup','#search_alumni',$(this),search_alumni);
There is any way for two load pages in php and ajax based on if else condition.

when you use val() dont need use value.
...
$data = $('#search_alumni').val();
if($data!='')
...

Related

Cancel form submitting after checking database

I would like to submit a form only after checking if some of the inputs are not already existing in the database.
I use beforeSend for checking if there are some fabrics to add, if so, I create a variable with all the fabrics name, and my php script "check_fabric.php" controls if the fabrics are not already in the database.
I would like to submit the form only if the fabrics name are new.
$("#addorder").validate({
submitHandler: function(form, event) {
event.preventDefault();
var form = $("#addorder");
var id_customer = $("#id_customer").val();
$.ajax({
type: 'POST',
dataType: 'html',
url: "process.php",
data: form.serialize()+"&id_customer="+id_customer,
beforeSend: function(xhr) {
$("#submit-btn").removeClass("effet add").addClass("sending").val('Adding....').attr('disabled',true);
var nbfabric = $("#nbfabric").val();
if(nbfabric>0) {
var arrayFabric = new Array();
for (var i=0;i<nbfabric;i++) {
arrayFabric.push($('input[name="fabric_'+i+'"]').val());
}
var jsonString = JSON.stringify(arrayFabric);
$.ajax({
type: "post",
url: "check_fabric.php",
data: {data : jsonString},
success: function (data) {
if (data === "ok") {
form.submit();
} else {
alert(data);//data lists all the fabrics name already existing in the database
$("#submit-btn").removeClass("sending").addClass("effet ajout").val('Ajouter').attr('disabled',false);
event.preventDefault();
return false;
}
}
});
}
},
success: function(data) {
form.fadeOut("normal", function(){
$("#return_message").html(data).fadeIn();
});
},
}
});
}
});
Any idea ?

How to utilize the Ajax call success return data to php code for running mysql query in same file

I am getting data from ajax call. But that data is coming in Jquery and I have saved it in a variable. Now I want that data to be utilized for running some php and mysql code. Can any one solve this?
$("#submit_bt").click(function () {
var name = $('#search-box').val();
var dataString = 'name=' + name;
if (name == "" ){
$('.alert').show().html('Please fill all information')
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "read_data.php",
data: dataString,
cache: false,
success: function (result) {
alert(result);
//$('.alert').show().html(result).delay(2000).fadeOut(3000);
setTimeout(function(){window.location.href = "index.php";},2000);
}
});
}
return result;
});
If what you want is to navigate to the index.php page on click of that button, then, do it this way:
$("#submit_bt").click(function () {
var name = $('#search-box').val();
var dataString = 'name=' + name;
if (name == "" ){
$('.alert').show().html('Please fill all information')
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "read_data.php",
data: dataString,
cache: false,
success: function (result) {
alert(result); //you may remove this. use console.log for debugging your js next time
setTimeout(function(){window.location.href = "index.php?result="+result;},2000); //why the timeout?
}
});
}
});
The easier and proper solution should be to re-use ajax to use this variable in another PHP file.
$("#submit_bt").click(function () {
var name = $('#search-box').val();
var dataString = 'name=' + name;
if (name == "" ){
$('.alert').show().html('Please fill all information')
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "read_data.php",
data: dataString,
cache: false,
success: function (result)
{
//AJAX code to execute your MySQL query
$.ajax({
type: "POST",
url: "read_data2.php",
data: result,
cache: false,
success: function (result)
{
//Manage your read_data2.php output
}
});
}
});
}

Magento Ajax Request - how to correctly pass data?

Since couple of weeks(two) started my adventure with Magento. So far I've learned a little but have a problem how to send data using Ajax (jQuery).
$(document).ready(function(){
var total = $(this).find(\"input[class=tramp]:checked\").length;
$(\".caret input[type='checkbox']\").change(function(){
if($(this).is(':checked')){
var value= true;
}else{
var value = false;
}
var brand = $(this).data('brand');
data = {brand: brand, value: value}
$.ajax({
data: data,
url: 'checkbox/ajax/index',
method: 'POST',
success: function(result){
console.log(data, total);
}});
});
});
This is my Ajax, so as you can see trying to send brand and value. AjaxController.php looks like this:
class Amber_Checkbox_AjaxController extends Mage_Core_Controller_Front_Action {
public function indexAction()
{
$brand = Mage::app()->getRequest()->getPost('brand', 'value');// not sure or I should use data?
if($brand )
{
....
$this->getResponse()->setBody($brand);
echo $brand;
...
}
}
}
remove \"
$(document).ready(function(){
var total = $(this).find("input[class=tramp]:checked").length;
$(".caret input[type='checkbox']").change(function(){
if($(this).is(':checked')){
var value= true;
}else{
var value = false;
}
var brand = $(this).data('brand');
data = {brand: brand, value: value}
$.ajax({
data: data,
url: 'checkbox/ajax/index',
method: 'POST',
success: function(result){
console.log(data, total);
}});
});
});
remove \", $ replace with jQuery and pass absolute URL Mage::getUrl('checkbox/ajax/index');
$.ajax({
data: data,
url: '<?php echo Mage::getUrl("checkbox/ajax/index"); ?>',
method: 'POST',
success: function(result){
console.log(data, total);
}});

jQuery and Ajax to Return different set of data rather than creating seperate ajax calls

I have the following jQuery setInterval function to reload data at 30 second intervals using ajax from a php file. I am running 3 different ajax calls in order to get 3 bits of information. Is there a way to consolidate the 3 seperate ajax calls into one call? 2 of the calls have the php file return back json data from session, and the other call just returns a number to display the quantity of unread messages.
Here is the jQuery code I currently have:
setInterval(function(){
jQuery.ajax({ url: '/ajax-msgs.php?check=1', type: 'POST', dataType: 'json', cache: 'false', success: function(data) {
var msghtml = '';
jQuery.each(data, function() {
msghtml += '<li>' + this.msg_subject + '</li>';
});
jQuery("#msg-menu").html(msghtml);
}
});
jQuery.ajax({ url: '/ajax-msgs.php?check=2', type: 'POST', dataType: 'json', cache: 'false', success: function(data) {
jQuery.each(data, function() {
jQuery.jGrowl(this.msg_title, { life: 12000});
});
}
});
jQuery.ajax({ url: '/ajax-msgs.php?check=3', type: 'POST', dataType: 'json', cache: 'false', success: function(data) {
jQuery("#msg-count").text('87');
}
});
}, 30000);
And here is what the php file does:
if ($_GET['check']==1){
iMapFunction();
print_r(json_encode($_SESSION['message_overviews']));
} elseif ($_GET['check']==2){
iMapFunction();
print_r(json_encode($_SESSION['messages_new_notifications']));
unset($_SESSION['auth_messages_new_notifications']);
} elseif ($_GET['check']==3){
iMapFunction();
echo $_SESSION['messages_unread_count'];
}
our PHP could return all the thata in one call like this:
<?php
iMapFunction();
$response = array(
'message_overviews' => $_SESSION['message_overviews'],
'messages_new_notifications' => $_SESSION['messages_new_notifications'],
'messages_unread_count' => $_SESSION['messages_unread_count']
);
print_r(json_encode($response));
?>
And you can iterate on each data the same way you did before like this:
setInterval(function(){
jQuery.ajax({ url: '/ajax-msgs.php', dataType: 'json', cache: 'false', success: function(data) {
var message_overviews = data.message_overviews;
var messages_new_notifications = data.messages_new_notifications;
var messages_unread_count = data.messages_unread_count;
var msghtml = '';
jQuery.each(message_overviews, function() {
msghtml += '<li>' + this.msg_subject + '</li>';
});
jQuery("#msg-menu").html(msghtml);
jQuery.each(messages_new_notifications, function() {
jQuery.jGrowl(this.msg_title, { life: 12000});
});
jQuery("#msg-count").text(messages_unread_count);
}});
}, 30000);
Just make an endpoint that does all the actions in one call:
I don't know php but create an associative array and assign your data to that.
x = {};
x['message_overviews'] = $_SESSION['message_overviews'];
x['auth_messages'] = $_SESSION['auth_messages_new_notifications'];
x['messages_unread_count'] = $_SESSION['messages_unread_count'];
print_r(json_encode(x));
Then in your jquery response function you can access your data and do your actions:
function(data){
console.log(data.message_overviews);
console.log(data.auth_messages);
console.log(data.messages_unread_count);
}

Access Data from Database with Ajax

I have tried just about every solution and I know my database returns values if i hard code in the php so the issues is returning the values or determining if it is actually sent as post. It gets to the success function and alerts Worked but I am getting undefined for Item ID.
$(document).ready(function() {
$('.check').click(function(){
alert("Step1");
var thisID = $(this).attr('id');
alert(thisID);
$.ajax({
type: "GET",
url: "XXX.PHP",
data: { "ID": thisID},
cache: false,
async:true,
datatype: "json",
success: function(data)
{
alert("WORKED");
alert(data.ItemID);
}
});
});
});
Here is the PHP
if(isset($_POST['ID']))
{
$ID = $_POST['ID'];
function retrieve($ID)
{
$stmt = $mysqli->query("SELECT * FROM database1.menu WHERE ItemID = $ID");
if($stmt->num_rows) //if there is an ID of this name
{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
You could try something like this. Not sure if this is what you need.
$(".check").click(function(event){
event.preventDefault();
var $this = $(this);
var thisID = $this.attr('id');
$.ajax({
type: "POST",
url: base_url + "url.php",
data: {
id: thisID
},
dataType: "text",
cache:false,
success:
function(data){
alert(data);
}
});
return false;
});

Categories