hello I have a function where I am using ajax to try to do get some value and then submit a php form which looks like this.
/* form-horizontal */
$attributes = array("class" => "form-horizontal", "id" => "register_form");
if (isset($_SESSION['login']))
{
if ($_SESSION['login'] == 'DoBusinessPerformed' || $_SESSION['login'] == 'NormalPerformed') {
echo form_open('myprofile/ManageProcessNew/'.$pathName, $attributes);
} else {
echo form_open('myprofile/RegisterProcessNew/'.$pathName, $attributes);
}
}
else
{
echo form_open('myprofile/RegisterProcessNew/'.$pathName, $attributes);
}
As you can see i have a .$pathname which is the parameter which contains the value 'borrow' and here is the ajax function which I am calling to send this form.
self.checkMangoPayId = function(){
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/checkMangoPayID/' + auth,
contentType: 'application/json; charset=utf-8',
})
.done(function(data) {
console.log(data);
if(data.mangopay_id == null){
alert("going to save page for mango id");
// here is where I submit the form
$("#register_form").submit();
}else{
self.mangoPayIdCheck(true);
self.showModalAddId();
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error code thrown: " + errorThrown);
})
.always(function(data){
});
}
what I want to do is in the .submit function add a way to change the value of .$path name and put borrowed instead of borrow.
I tried a lot of ways like .submit(borrowed), but non of those ways work, so basically all I want to send a different value inside pathname to my controller which receives this parameter.
just before your submit you can add a attribute like this
$("#register_form").attr('action',BASEURL + "index.php/bla/bla/borrowed");
and then when you submit it will attach it at the back as parameter.
Related
I made a form from many tables from a database, like holiday, service and etc.. tables. Holiday is a datepicker and adds dates with jquery and saves when I click the update button. But deleting is not working like this.
I want to delete some holidays with ajax and check some services and then update all of the form with one "update" button. I want to delete using jquery and send the ID of holiday not from the database, then I click on the update button to delete from the database and update all data.
How do I send the ID of the holiday to the server?
My php code for deleting holiday:
if (isset($_POST["holiday_id"])) {
var_dump($_POST);
$holiday_id = $_POST['holiday_id'];
$userid_office = $_POST['userid_office'];
$deleted_holiday = $db->query("delete from holiday where id='$holiday_id' and
$userid_office='$userid_office' ");
var_dump($deleted_holiday);
if ($deleted_holiday == true) {
echo json_encode(['message' => 'successfully deleted', 'status' => 'success']);
die();
} else {
echo json_encode(['message' => 'can not delete', 'status' => 'error']);
die();
}
}
My ajax code for deleting and updating the form:
$(".delete").on('click', function (e) {
e.preventDefault()
var holiday_id=$(this).data("holiday_id");
$('#holiday_'+holiday_id ).remove()
console.log(holiday_id)
return false;
})
$("#scheduleForm").on("submit", function (e) {
e.preventDefault();
var form_data = $(this).serialize();
var url = window.location.pathname + "?mod=schedule&action=schedule_added&ajax=true";
console.log(form_data)
$.ajax({
url: url,
method: "POST",
data: form_data,
success: function (data) {
data = JSON.parse(data)// important because without it show just string
// console.log(typeof data);
if (data.message != null) {
alert(data.message)
} else {
location.reload();
alert("تغییرات باموفقیت انجام شد.")
}
},
error: function (err, err1, err3) {
console.log(err3);
console.log(err1);
}
})
})
I am trying to send a group of form parameters over to a PHP script for processing.
I've previously done something like this using $.post, but now I'm trying to get it done strictly by using $.ajax.
Here is the jQuery click event that is supposed to send all of the variables to the PHP script:
$('.searchSubmit').on('click', function()
{
var searchCriteria = {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: searchCriteria, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
});
Here is the PHP script, called railmbs.php:
<?php
if(isset($_POST['searchCriteria']))
{
$value = $_POST['searchCriteria'];
$_SESSION['where'] = "";
$import_bill = mysqli_real_escape_string($dbc, trim($value['import_bill']));
$import_ramp = mysqli_real_escape_string($dbc, trim($value['import_ramp']));
$import_delivery = mysqli_real_escape_string($dbc, trim($value['import_delivery']));
echo $import_bill; // just trying to echo anything at this point
}
?>
Not sure what I am doing wrong. If I echo hello before the IF above, the console will output accordingly. But I cannot seem to get anything to echo from inside the IF.
Does anyone see my error?
You are not setting the "searchCriteria" variable.
Change this:
$('.searchSubmit').on('click', function()
{
var searchCriteria = {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: searchCriteria, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
});
to:
$('.searchSubmit').on('click', function()
{
var data = {
searchCriteria: {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
}
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: data, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
First of all. Why not to use $("form").serialize()? It would be much cleaner.
Secondary, you transfer data in root object, so to get you values, check $_POST array.
Instead of $value = $_POST['searchCriteria'] use $value = $_POST;.
This PHP code should work:
<?php
if(isset($_POST))
{
$_SESSION['where'] = "";
$import_bill = mysqli_real_escape_string($dbc, trim($_POST['import_bill']));
$import_ramp = mysqli_real_escape_string($dbc, trim($_POST['import_ramp']));
$import_delivery = mysqli_real_escape_string($dbc, trim($_POST['import_delivery']));
echo $import_bill; // just trying to echo anything at this point
}
?>
Or modify your js to send data in searchCriteria object, like this:
var searchCriteria = {
searchCriteria: {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
}};
You should check if you actually send post data using your browser developer tools or typing var_dump($_POST); at the beginning of your PHP script.
As far as i can see, you never actually set searchCriteria as post variable.
Currently your $_POST variable should contain the field import_bill, import_ramp and so on. Either change your if statement or your JavaScript object to {searchCriteria: {/*Your data here*/}.
I have a memory game code, using javascript, php and css.
I would like to register somehow the event when the game is finished by php so that I can save the results in database.
In other words I would like to place php code inside <div id="player_won"> </div> and trigger that winning event properly.
css
#player_won{
display: none;
}
javascript
$(document).ready(function(){
$(document).bind("game_won", gameWon);
}
function gameWon(){
$.getJSON(document.location.href, {won: 1}, notifiedServerWin);
var $game_board = $("#game_board");
var $player_won = $("#player_won");
$game_board.hide();
$player_won.show();
$game_board = $player_won = null;
};
You'll want to create an ajax call that sends some information from the page and tells the php file below if the player has won or lost. After which you can deal with the logic needed for the player inside foo.php and send back Json to the success function inside the ajax call and update your page accordingly.
index
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#SomeId', function () {
//Get the information you wish to send here
var foo = "test";
$.ajax({
url: "/foo.php",
type: 'POST',
cache: false,
data: {Info: foo},
dataType: 'json',
success: function (output, text, error)
{
//here is where you'll receive the son if successfully sent
if(ouput.answer === "yes"){
$("#player_won").show();
} else {
// Do something else
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
});
foo.php
<?php
if(isset($_POST['Info'])){
//figure out if what was sent is correct here.
if($_POST['Info'] === "test"){
$data['answer'] = "yes";
echo json_encode($data);
exit;
} else {
// do something else
}
}
?>
i have made function where i can add a row after confirming. the problem is, after submit button, the tables dont reload and show error function alert.actually data success saved and i have to refresh the page so that the table can reload. here is my ajax jquery code:
function reloadPage()
{
window.location.reload()
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('activity/save')?>";
} else {
url = "<?php echo site_url('activity/update_activity')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form-input').serialize(),
dataType: "JSON",
success: function(data)
{
$('#myModal').modal('hide');
reloadPage();
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
<button id="btnSave" onclick="save()" class="btn green">
"fa fa-save"> save</button>
my controller:
public function save() {
$actype = $this->input->post('actype');
$activity_name = $this->input->post('activity_name');
$project = $this->input->post('project');
$portion = $this->input->post('portion');
$activity = $this->input->post('actid');
$data = array(
'activity_type_id'=>$actype,
'activity_name' =>$activity_name,
'project_id' =>$project,
'portion' =>$portion,
'activity_id' => $activity
);
$this->activity->insertactivity($data);
redirect("activity/input");
}
after i've clicked button save,alert('Error adding / update data'),but actually after reload page data has saved.
where is code error in my ajax code?
Force a reload from the server.
window.location.reload(true);
When you don't specify true the reload may be from the browser cache if available.
Also, in the controller, redirect("activity/input"); is not the appropriate response to an AJAX request. Try something like this instead.
$this->activity->insertactivity($data);
echo json_encode(array('result' => TRUE));
Your controller code could also be much more concise. Consider this
public function save()
{
$data = array(
'activity_type_id' => $this->input->post('actype'),
'activity_name' => $this->input->post('activity_name'),
'project_id' => $this->input->post('project'),
'portion' => $this->input->post('portion'),
'activity_id' => $this->input->post('actid')
);
//Assuming insertactivity returns TRUE if the insert works and FALSE if not
$results['result'] = $this->activity->insertactivity($data);
echo json_encode($results);
}
You can check the "result" in success function
success: function(data)
{
if(data.result === true)
{
$('#myModal').modal('hide');
reloadPage();
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
} else {
//do something to the DOM to tell about the problem
//which probably means you should add that to your controller's response.
}
},
When I click on the submit button of my form I'm redirected because of the PHP on the page "Form sent". How to stay in the same page with jQuery validate form plugin please ?
PHP FILE
<?php
// [I HAVE CUT THE CODE]
if(mail($to, $subject, $message, $headers)){
echo "Form sent";
} else {
echo "Form not sent";
}
?>
JQUERY FILE
$("#form-contact").validate({
submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
form.submit();
}
});
HTML FILE
<form id="form-contact" action="php/traitement.php" method="post"></form>
UPDATE 1
submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result){ console.log("success!", result);},
dataType: dataType
});
return false;
}
I'm always redirected on "Form sent" page. I know nothing about Ajax :-/
UPDATE 2
http://jsfiddle.net/Xroad/2pLS2/25/
jQuery .ajax() can be used to submit data to the server without a page refresh, but it's not exclusive to the jQuery Validate plugin.
However, here are your two options using the jQuery Validate plugin.
Standard form submit using the default action of the form element (as you've done)...
$("#form-contact").validate({
submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
form.submit(); // standard submit of the default form action
}
});
To stay on same page, use .ajax() in the submitHandler callback...
$("#form-contact").validate({
submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
$.ajax({ // submit form using ajax
// your ajax options here
});
return false; // block default form action
}
});
See the jQuery .ajax() documentation for the options.
This is your own jsFiddle, which shows everything is working. I cannot test the ajax but the form is not refreshing the page as you claim.
If I understand correctly what you want, one way would be to try to submit from jQuery. In the submitHandler have something like:
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result){ console.log("success!", result);},
dataType: dataType
});
The tricky part would be to get all the information into the data object before calling this.
The success function would have the data from the server after posting.
More info: https://api.jquery.com/jQuery.post/
If you make it work without validate plugin and more organised validation process then I would like you to have a look my code:
jQuery(document).ready(function($) {
$('#MyForm').on('submit', function(){
var form = this;
if(validateForm(form)) {
var values = $(form).serialize();
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
event.preventDefault(); //changed to allow the tag manager to notice that the form was submitted
}
else{
event.preventDefault();
return false;
}
});
// validate Form
function validateForm(form) {
valid = true;
$(form).find('input[type=text], input[type=email]').each(function(i, val){
if(validateField(val, true) == false) { valid = false; }
});
return valid;
}
// validate all form fields
function validateField(field, submit) {
var val = $(field).val();
if($(field).attr('aria-required') == 'true' && submit){
if(val == '') {
$(field).parent().removeClass('valid');
$(field).parent().addClass('error');
return false;
}else {
$(field).parent().removeClass('error');
$(field).parent().addClass('valid');
return true;
}
// you can more specific
if($(field).attr('type') == 'text') {
$(field).parent().addClass('error');
return false; }
else {
$(field).parent().removeClass('error');
$(field).parent().addClass('valid');
return true;
}
// you can more specific
if($(field).attr('type') == 'email') {
$(field).parent().addClass('error');
return false; }
else {
$(field).parent().removeClass('error');
$(field).parent().addClass('valid');
return true;
}
}
}
// Run validation before Submit the form
$('input[type=text], input[type=email]').on('change', function(){
if($(this).val() != ''){
$(this).parent().removeClass('error valid');
validateField(this, false);
}
});
});