Saving form value along with form in Session - php

I am using jQuery & ajax to save a entire form in session which is being generated.
when I press the search button the
onclick="updateContentdata();
is called. which is doing following.
function updateContentdata() {
var updateSearchContent = $('#savelistdata').html();
var rowNumb = rowCount;
var inFileds = JSON.stringify(field_options);
// var inputValue = $('inptval_' + rowCount).val();
$.ajax({
type: "POST",
url: "<?= $HOMEPAGE_ROOT; ?>/ajax_listuser.php",
data: {
rowNum: rowNumb,
field_options: inFileds,
html: updateSearchContent
},
success: function (data) {
$('#searchusers').submit();
},
error: function (req, status, error) {
console.log(error)
}
});
}
ajax_listuser.php
<?php
session_start();
if(isset($_POST['html']) && isset($_POST['rowNum'])){
$_SESSION['searchContent'] = $_POST['html'] ;
$_SESSION['rowNumber'] = $_POST['rowNum'] ;
$_SESSION['field_options'] = $_POST['field_options'];
}
?>
Form is being saved in the session but I want to keep form values in the session. but it only keeping the form.
So basically I need
<input class="form-control" type="text" id="inptval_2" name="search_input_value[]" value="71347">
instead of
<input class="form-control" type="text" id="inptval_2" name="search_input_value[]">

Create this function first:-
function getHtml(div){
div.find("input, select, textarea").each(function () {
var $this = $(this);
if ($this.is("[type='radio']") || $this.is("[type='checkbox']")) {
if ($this.prop("checked")) {
$this.attr("checked", "checked");
}
} else {
if ($this.is("select")) {
$this.find(":selected").attr("selected", "selected");
} else {
$this.attr("value", $this.val());
}
}
});
return div.html();
}
and then modify your funciton:-
function updateContentdata() {
var updateSearchContent = getHtml($('#savelistdata'));
var rowNumb = rowCount;
var inFileds = JSON.stringify(field_options);
// var inputValue = $('inptval_' + rowCount).val();
$.ajax({
type: "POST",
url: "<?= $HOMEPAGE_ROOT; ?>/ajax_listuser.php",
data: {
rowNum: rowNumb,
field_options: inFileds,
html: updateSearchContent
},
success: function (data) {
$('#searchusers').submit();
},
error: function (req, status, error) {
console.log(error)
}
});
}

You will probably have to put those values back in the form, since the value="123" is not part of the html when someone fills the form. Iterate over the values you have and find the corresponding form-element, and set its value

Related

how to login after get key google recaptchaV3

I´m traying to do logging in my web with ajax. But i need generated google key when i do click in login, and before to do login. I have this function:
$('#main-login-form').on('submit', function(e){
renewKeyRecaptcha();
//e.preventDefault();
let key = $("#recaptchaResponse").val();
console.log(key);
if(key != null || key != ""){
var $this = $(this);
$(this).find('input').removeClass('is-invalid');
$(this).find('.error').html('');
var data = $this.serializeArray();
data.push({name: 'currentName', value: config.url.currentName});
$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: data,
dataType: $this.data('type'),
success: function (response) {
if(response.success) {
$(location).attr('href', response.redirect);
}
console.log(response);
},
error: function (jqXHR) {
var response = JSON.parse(jqXHR.responseText);
if (response.errors.password) {
$($this).find('input[name="password"]').addClass('is-invalid');
$($this).find('.password-error').html(response.errors.password);
} else if (response.errors.email) {
$($this).find('input[name="email"]').addClass('is-invalid');
$($this).find('.email-error').html(response.errors.email);
} else if (response.errors.gRecaptchaResponse) {
$($this).find('input[name="g-recaptcha-response"]').addClass('is-invalid');
$($this).find('.g-recaptcha-response-error').html(response.errors.gRecaptchaResponse);
}
}
});
}
});
this function call to renewKeyRecaptcha(); that generated key, but i need to do click login twice and before i´m login... i need to do once click in login and generate key and login... But i can´t. I don´t know if i´m doing well or i would do to another way.
My function that generate key:
function renewKeyRecaptcha(){
// add key google to input
var key = config.url.recaptchaGoogle;
grecaptcha.ready(function() {
grecaptcha.execute(key, {action: 'login'}).then(function(token) {
$("#recaptchaResponse").val(token);
$("#recaptchaResponseRegister").val(token);
});
});
}
this function run ok.
Thanks for help.
I resolve my question with:
$("#submitLogin").on("click", function(e){
renewKeyRecaptcha();
e.preventDefault();
setTimeout(function(){
$(this).find('input').removeClass('is-invalid');
$(this).find('.error').html('');
$this = $('#main-login-form');
var data = $this.serializeArray();
data.push({name: 'currentName', value: config.url.currentName});
$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: data,
dataType: $this.data('type'),
success: function (response) {
if(response.success) {
$(location).attr('href', response.redirect);
}
console.log(response);
},
error: function (jqXHR) {
var response = JSON.parse(jqXHR.responseText);
if (response.errors.password) {
$($this).find('input[name="password"]').addClass('is-invalid');
$($this).find('.password-error').html(response.errors.password);
} else if (response.errors.email) {
$($this).find('input[name="email"]').addClass('is-invalid');
$($this).find('.email-error').html(response.errors.email);
} else if (response.errors.gRecaptchaResponse) {
$($this).find('input[name="g-recaptcha-response"]').addClass('is-invalid');
$($this).find('.g-recaptcha-response-error').html(response.errors.gRecaptchaResponse);
}
}
});
}, 3000);

Passing Variable Value from PHP to Ajax and Changing Attribute Value in HTML

My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}

jQuery use ajax and json to switch page with button

Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }

sending data via ajax in Cakephp

i am new to cakephp and trying to send data from ajax to my controller action..
i have a popup model in which there is a input box ..i want to grab that value and send to controller without page refresh
here is my code ..
<a class="button anthracite-gradient" onclick="openPrompt()">submit </a>
my javascript
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
url:"/cakephp/controller/action/",
success : function(data) {
alert(value); //value right now is in this variable ... i want to send this variable value to the controller
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
myController
public function action(){
if( $this->request->is('ajax') ) {
$new = $this->request->data;
echo "ok"
return;
}
}
i want to first get the value here and then send the response to may ajax request
Its simple post the value to the controller and do what you want , in ajax request bind the value in data:{value_to_send:value} and get in controller
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
data:{value_to_send:value},
url:"/cakephp/controller/action/",
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
public function action(){
if( $this->request->is('ajax') ) {
// echo $_POST['value_to_send'];
echo $value = $this->request->data('value_to_send');
//or debug($this->request->data);
echo "ok"
die();
}
}
For more see accessing-post-data
I will give you some example. In my case, list out book list as a smart search while typing on text box.
$( ".selectBook" ).each(function(){
$(this).keyup(function( event ) {
var tri = $(this).val();
var oPrnt = $(this).parents('.smartsearch');
var str = '';
if(tri.length > 2){
$.ajax({
type: "POST",
url: "/utility/getbooks/",
data: JSON.stringify({string: tri, activeonly:false}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function(key, val) {
str += '<li id="a'+key+'" term="'+val+'" data-did="'+key+'">'+val+'</li>';
});
oPrnt.find("ul.result").html(str);
},
error: function (errormessage) {
oPrnt.find("ul.result").html('<li><b>No Results</b></li>');
}
});
oPrnt.find("ul.result").slideDown(100);
}
});
});
And in the controller, action (getbooks Action in UtilityController in my case)
public function getbooks($string = '', $activeonly = true){
$this->autoRender = false;
if( $this->request->is('ajax') ) {
$data = $this->request->input('json_decode');
$string = $data->string;
$activeonly = $data->activeonly;
}
$aReturn = array();
// ... fetch books data from DB goes here...
$aResult = $this->Book->fetch('list');
foreach($aResult as $r){
if(isset($r['bookname'])){
$aReturn[$r['id']] = $r['bookname'];
}
}
return json_encode($aReturn);
}

Jquery ajax is not sending data

For some reason ajax is not sending data.
On the PHP I have this code:
if (isset($_POST['submit'])) {
echo "submit";
} else {
echo "not submit";
}
And I get not submit.
This is JS code:
$(function () {
$('#submit').click(function () {
var length = $('#number').val();
var small = $('#small').val();
var big = $('#big').val();
var number = $('#numero').val();
var special = $('#special').val();
var submit = 'submit';
var url = 'public/php/codegenerator.php';
var data = "length=" + length + "&small=" + small + "&big=" + big +
"&number=" + number + "&special=" + special + "&submit=" + submit;
$.ajax({
type: "POST",
url: url,
data: data,
success: function () {
$('#code').load(url, function () {
$(this).fadeIn(1000)
});
}
});
return false;
});
});
You can try this approach
$(function(){
$('#submit').click(function(){
//YOUR CODE
var param = {
length:length,
small:small,
big:big,
number:number,
special:special,
submit:submit
}
$.ajax({
type: "POST",
url: url,
data: param,
//EDITED LINE
success: function (data) {
$('#code').hide().html(data).fadeIn(1000);
}
});
return false;
});
});
// REVISED ANSWER
// IN YOUR PHP FILE
if (isset ($_POST['submit'])) {
echo json_encode(array('result'=>"submit"));
}
else {
echo json_encode(array('result'=>"not submit"));
}
//IN YOUR JQUERY CODE
$.ajax({
type: "post",
url: url,
data: param,
dataType:'json';
//EDITED LINE
success: function (data) {
// alert(data.result);
$('#code').hide().html(data.result).fadeIn(1000);
}
});
You are getting Not submit, because it comes from the .load() call and not from .ajax - and in the load call you just load the URL without passing any POST data. So why you are running .load inside the success callback of .ajax with the same url?

Categories