I have a bootbox dialog with a button named save in a view called table_data.php and I would like to determine whether the Ajax post to database will be done based on a result obtained from the database.
I want the data only to be saved when the database query in home_model.php does not return any rows. However, when I do it, it does not work. It is a cms and I am using codeigniter framework.
My page is blank. And nothing appears. Please help me. I am new to web and have very little experience with JavaScript and php and just started on ajax. Your help will be much appreciated.
table_data.php (view)
bootbox.dialog({
message: '<div class="row"> ' +
'<div class="col-md-12"> ' +
'<form class="form-horizontal"> ' +
'<div class="form-group"> ' +
'<label class="col-md-4 control-label" for="awesomeness">Table ID: </label> ' +
'<div class="col-md-4">' +
'<input id="idtable" type="text" value="'+table_column_15+'"/>' +
'</div><br>' +
'</div>'+
'</form> </div> </div>',
title: "Form",
buttons: {
success: {
label: "Save",
className: "btn-success",
callback: function() {
console.log('save');
console.log($('#re_confirm')[0].checked);
var valueid = document.getElementById('idtable').value
if(valueid == 0)
myFunction();
var valueid2 = document.getElementById('idtable').value
if(valueid2==0)
return;
$.ajax({
url: "<?php echo base_url(); ?>index.php/home/check_occupied",
type: "post", // To protect sensitive data
data: {
"table_id" : valueid2
"session_id" : table_column_15
//and any other variables you want to pass via POST
},
success:function(response){
// Handle the response object
console.log(response);
var check = $(response);
}
});
if(check==0)
return;
$.ajax({
url : "<?php echo base_url(); ?>index.php/home/update_booking",
type: "post",
data: {
"table_id" : $('#idtable').val(),
},
success: function(response){
...
}
});
}
},
...
,
...
}
});
home_model.php (model)
public function check_occupied($tableid,$sessionid)
{
$sql = "SELECT * FROM booking WHERE table_id=$tableid and session=$sessionid;
$query = $this->db->query($sql);
if ($query->num_rows() > 0)
$imp = 1;
else
$imp = 0;
return $imp;
}
home.php(controller)
public function check_occupied()
{
$tableid = $_POST['table_id'];
$sessionid = $_POST['session_id'];
$imp = $this->home_model->check_occupied($tableid,$sessionid);
$this->load->view('table_data', $imp);
}
I found a few syntax minor errors but the biggest problem is where you are attempting to use the var check as in if(check==0).
Your condition evaluation if(check==0) is outside the success function of the ajax call to check_occupied. Therefore, if(check==0) will execute before the success function runs and sets a value for check. If you console.log(check); just before the if statement you will find the value to be 'undefined'. This console result will also be logged before the output of `console.log(response);' which will confirm the order of execution.
In other words, you need to decide on whether to run the next ajax call inside of the success function of the check_occupied ajax call.
Here's my version. It's untested but I think the concept is sound. This shows only the callback: for the "Save" button.
callback: function () {
console.log('save');
console.log($('#re_confirm')[0].checked);
var valueid = document.getElementById('idtable').value;
if (valueid === 0) {
myFunction();
}
var valueid2 = document.getElementById('idtable').value;
if (valueid2 === 0) {
return;
}
$.ajax({
url: "<?php echo base_url(); ?>index.php/home/check_occupied",
type: "post", // To protect sensitive data
data: {
"table_id": valueid2,
//??? where is table_column_15 declared and initialized? Some global var?
"session_id": table_column_15
//and any other variables you want to pass via POST
},
success: function (response) {
// Handle the response object
console.log('response='+response);
//if I read check_occupied() right, response should only be 1 or 0
//there is no need to assign it to another var, eg. var check = response
//there is no apparent need to turn it into a JQuery object with $(response) either
if (response > 0) {
$.ajax({
url: "<?php echo base_url(); ?>index.php/home/update_booking",
type: "post",
data: {
"table_id": $('#idtable').val()
},
success: function (response) {
}
});
}
}//end of success function callback for check_occupied() ajax
console.log('ajax to check_occupied is done.');
});
}
Related
I am creating one small program in which Ι use two tabs in single page and call one ajax call to do operations dynamic.
Below is my code:
HTML Code below
OffyApp Agents
ListHub Agents
<div id="Home" class="tabcontent">
// Some code
</div>
<div id="News" class="tabcontent">
// Some code
</div>
Script Code Below
function openPage(pageName,elmnt,color) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
}
document.getElementById(pageName).style.display = "block";
elmnt.style.backgroundColor = color;
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
AJax call Below
$.ajax({
url: "sendInvite.php",
type: "POST",
data: {list: inviteEmails},
dataType: "JSON",
beforeSend: function() {
$("#loading-image").show();
},
success: function (data) {
//alert(data);
if (data.status == 200) {
alert("Invite Sent Successfully.");
location.reload(true);
}
},
error: function (msg) {
alert(msg);
}
});
If ajax call give me success then i want to redirect to my second tab like #News
success: function (data) {
if (data.status == 200) {
alert("Invite Sent Successfully.");
location.reload(true);
}}
data.status only will give you an error bacause neither data is JSON nor data have key status
Hence, your if statement is always false. data is the actual response as the plain text from the requested file. Therefore data have no such key like status.(eg.data is the request.responseText)
jQuery Ajax function has three variables:
success: function (a,b,c){}
Where:
a is the actual responseText
b is the textStatus &
c is xhr
Hence, you have to write success function as:
success: function (data,stxt,xhr){
if(xhr.status==200){
alert("Invite sent successfully!");
window.location.reload();
}
}
You could write a function
function activateTab(tab){
$('.tab-pane a[href="#' + tab + '"]').tab('show');
};
Then upon success of your ajax call you can activateTab('news');
But as #Ritesh said, that function will not run because data does not contain a key called success on it, it will just contain the data you get from the server. You need to pass all the parameters into your success callback in order to access the response code.
I am validating a form with ajax and jquery in WordPress post comments textarea for regex. But there is an issue when i want to alert a error message with return false. Its working fine with invalid data and showing alert and is not submitting. But when i put valid data then form is not submit. May be issue with return false.
I tried making variable and store true & false and apply condition out the ajax success block but did not work for me.
Its working fine when i do it with core php, ajax, jquery but not working in WordPress .
Here is my ajax, jquery code.
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And i'm using wordpress wp_ajax hook.
And here is my php code.
<?php
function nmp_process_func (){
$comment = $_REQUEST['comment'];
preg_match_all("/(->|;|=|<|>|{|})/", $comment, $matches, PREG_SET_ORDER);
$count = 0;
foreach ($matches as $val) {
$count++;
}
echo $count;
wp_die();
}
?>
Thanks in advance.
Finally, I just figured it out by myself.
Just put async: false in ajax call. And now it is working fine. Plus create an empty variable and store Boolean values in it and then after ajax call return that variable.
Here is my previous code:
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And the issue that i resolved is,
New code
var returnval = false;
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
async: false, // Add this
data: 'action=nmp_process_ajax&comment=' + comment,
Why i use it
Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.
And Then simply store Boolean in variable like this ,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
returnval = false;
} else {
returnval = true;
}
}
});
// Prevent Default Submission Form
return returnval; });
That's it.
Thanks for the answers by the way.
Try doing a ajax call with a click event and if the fields are valid you submit the form:
jQuery(document).ready(function () {
jQuery("input[type=submit]").click(function (e) {
var form = $(this).closest('form');
e.preventDefault();
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {'action':'nmp_process_ajax','comment':comment},
success: function (res) {
var count = parseInt(res);
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
} else {
form.submit();
}
}
});
});
});
note : you call need to call that function in php and return only the count!
Instead of submitting the form bind the submit button to a click event.
jQuery("input[type=submit]").on("click",function(){
//ajax call here
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}else{
jQuery("form").submit();
}
}
});
return false;
})
Plus also its a good idea to put return type to you ajax request.
Let me know if this works.
I'm trying to upload files through Ajax call and jQuery. Each input[type="file"] is handled dynamically as you will see on the code below and are created on the change event for the Select2 element.
var tipoRecaudo = $('#tipoRecaudo'),
tipo_recaudo = tipoRecaudo.val(),
selectedIdsTipoRecaudo = [];
tipoRecaudo.select2({
ajax: {
dataType: 'json',
url: function () {
return Routing.generate('obtenerRecaudosTramite');
},
data: function (tipo_recaudo) {
return {
filtro: tipo_recaudo
}
},
results: function (data) {
var myResults = [];
$.each(data.entities, function (index, item) {
if (selectedIdsTipoRecaudo.indexOf(item.id.toString()) === -1) {
myResults.push({
'id': item.id,
'text': item.nombre
});
}
});
return {
results: myResults
};
}
},
formatAjaxError: function () {
return Translator.trans('mensajes.msgNoConexionServidor', {}, 'AppBundle');
}
}).change(function () {
var id = $(this).val(),
selectedData = tipoRecaudo.select2("data"),
htmlTpl = '<table class="table"><caption>'+ selectedData.text + '</caption><tbody><tr><td>';
htmlTpl += '<input type="hidden" name="tipoRecaudos[]" id="tipoRecaudo ' + id + '" value="' + selectedData.id + '" /><div class="row"><div class="col-xs-6"><div class="form-group"><input type="file" id="recaudosNombreArchivo' + id + '" name="recaudos[nombre_archivo][]" multiple="multiple" class="form-control" /></div></div></div></div>';
htmlTpl += '</td></tr></tbody></table>';
selectedIdsTipoRecaudo.push(id);
$('#recaudoContainer').append(htmlTpl);
});
$('#recaudoContainer').on('change', 'input[type=file]', function (event) {
$("input:file").filestyle({
buttonText: "Seleccionar archivo",
iconName: "fa fa-upload",
buttonName: "btn-primary"
});
});
$('#btnGuardarPasoSieteAgregarProducto').on("click", function (event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// Create a formdata object and add the files
var formData = $('#formRecaudosTramites').serialize();
$.each($('#formRecaudosTramites')[0].files, function (key, value) {
formData = formData + '&recaudos[]=' + value;
});
$.ajax({
url: Routing.generate('rpniSubirRecaudos'),
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
contentType: 'multipart/form-data',
processData: false, // Don't process the files
//contentType: false // Set content type to false as jQuery will tell the server its a query string request
}).done(function (data, textStatus, jqXHR) {
if (typeof data.error === 'undefined') {
console.log('SUCCESS: ' + data.success);
} else {
// do something with error
}
}).fail(function (jqXHR, textStatus, errorThrown) {
// do something with fail callback
// STOP LOADING SPINNER
});
});
What is happening is: no filenames exists on query string, no files are upload or send through the Ajax call, instead it's sending a [object Object], what I'm doing wrong? Can any give me some working code for this stuff?
EDIT:
After reads the post referenced by user I change my code as the one before and now the error turns on:
TypeError: a is undefined
...rCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e...
What is wrong there?
Note: Yes, I know there are tons of plugins for handle this like jQuery File Upload from Blueimp, Dropzone and some others but I leave them out since I start using jQuery File Uploader from inside OneupUploaderBundle on my Symfony2 project and spent 4 days without success so I move to the other side: made things by myself so I can learn something else and improve my knowledge
i think this will help you,
var fd = new FormData();
//name is the key on the page of php to access the file
fd.append('name', $('#aob_file')[0].files[0]);
pass this fd object to your data field in ajax,
I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);
In CI, I have setup a controller with a method of logsig(). Then in my index() method I'm calling a view called startpage. In my view I'm using JSON to make an asynchronous call between my view and my controller. How would I code the call. Below is the code I have:
Contoller:
function logsig() {
$this->load->view('startpage', $sync);
header('Content-type:application/json'); .............
View:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
// blink script
$('#notice').blink();
$("#action_button").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = '&username=' + username + '&password=' + password;
if(username=='' || password=='') {
$('#success').fadeOut(400).hide();
$('#error').fadeOut(400).show();
} else {
$.ajax({
type: "POST",
dataType: "JSON",
url: "processing/logsig.php",
data: dataString,
json: {session_state: true},
success: function(data){
if(data.session_state == true) { // true means user is logged in.
$("#main1").hide();
$('#main1').load('<?=$sync?>').fadeIn();
} else if(data.session_state == false) { // false means user is being registered.
$("#action_button").remove();
$('#success').load('<?=$sync?>');
// onLoad fadeIn
}
}
});
}
});
});
</script>
You can't have your controller load a view and return JSON at the same time. Break out the JSON portion to a separate function.
An oversimplified example could look like this:
// Your existing function, but only displaying the view
function logsig() {
$this->load->view('startpage', $sync);
}
// A new function whose sole purpose is to return JSON
// Also notice we're using CI's Output class, a handy way to return JSON.
// More info here: codeigniter.com/user_guide/libraries/output.html
function get_json() {
$this->output->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
}
Then, in your JavaScript, call get_json:
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?php echo site_url('processing/get_json.php'); ?>",
// ... truncated for brevity ...
});
If I read your question correctly, your JS postback code isn't working:
url: "processing/logsig.php",
Your CI url should be something like:
url: <?php echo site_url("processing/logsig"); ?>,
The site_url() function requires the URL helper. Load that in the beginning of your loadsig() function:
$this->load->helper('url');
Try This
Controller ---------
public function AjaxTest() {
$rollNumber = $this->input->post('rollNumber');
$query = $this->welcome_model->get_students_informationByRoll($rollNumber);
$array = array($query);
header('Content-Type: application/json', true);
echo json_encode($array);
}
View-----
<?php echo validation_errors(); ?>
<?php echo form_open('welcome/SearchStudents'); ?>
<input type="text" id="txtSearchRoll" name="roll" value="" />
<input type="submit" name="btnSubmit" value="Search Students" onclick="return CheckAjaxCall();"/>
<?php echo '</form>'; ?>
Scripts ----------
function CheckAjaxCall()
{
$.ajax({
type:'POST',
url:'<?php echo base_url(); ?>welcome/AjaxTest',
dataType:'json',
data:{rollNumber: $('#txtSearchRoll').val()},
cache:false,
success:function(aData){
//var a = aData[0];
//alert(a[0].roll);
$.map(aData, function (item) {
var stData = "<td>"+ item[0].roll +"</td>" +
" <td>"+item[0].Name+"</td>" +
"<td>"+item[0].Phone+"</td>" +
"<td> Edit </td>"+
"<td> Delete </td>";
$('#tblStudent').text("");
$('#tblStudent').append(stData);
//alert (item[0].roll + " " + item[0].Name);
});
//alert(aData);
},
error:function(){alert("Connection Is Not Available");}
});
return false;
}