How can I add a timer function to clear out the search session created after user enters a search keyword. I can't seem to unset the search session. I've tried so many different ways to clear the search session and nothing works. I think the problem lies in this Ajax search function, its not clearing the results unless a user manually clears the search results.
So how can I add to this function a timer to "reset" and clear the search?
Thanks
if ($('#loaddata').attr("data-id") == '0') {
$("#HelloWord").on("keyup", function() {
var value = $(this).val().toLowerCase();
console.log(value);
if (value != '') {
$.ajax({
type: 'POST',
url: "<?php echo $siteurl;?>search.php",
data: {
valuejj: value,
},
success: function(data2) {
console.log(data2);
if (data2 == 'dataPushed') {
queryStringCategory2(pagevalue = 1);
}
}
});
}
if (value == '') {
$.ajax({
type: 'POST',
url: "<?php echo $siteurl;?>SearchValueDestroyFromSession.php",
data: {
id: 1
},
success: function(data2) {
if (data2 == 'done') {
queryStringCategory2(pagevalue = 1);
}
}
});
}
});
}
Related
when i try get and echo the variable on php, sending by ajax, i receive always var_dump null
the alert is ok, he shows the current slide id number when <a>(role=button) prev or next is clicked: 1 on slide 1, 2 on 2, 3 on 3;
<script>
$("#myCarousel").on('slide.bs.carousel', function(e) {
var value1 = $(this).find('.carousel-item.active').attr('id');
alert(value1);
var value = {
idCarrosselAtivo: $(this).find('.carousel-item.active').attr('id')
}
$.ajax({
type: "POST",
url: "teste.php",
data: value,
success: function(data) {
console.log(data);
}
});
})
</script>
<?php
if(isset($_POST['idCarrosselAtivo'])&& $_POST['idCarrosselAtivo'] === 'c1') {
echo $idCarrossel;
} else {
var_dump($idCarrossel);
}
?>
Consider this example.
jQuery
$("#myCarousel").on('slide.bs.carousel', function(e) {
console.log("Sending ", $(this).find('.carousel-item.active').attr('id'));
$.ajax({
type: "POST",
url: "teste.php",
data: {
idCarrosselAtivo: $(this).find('.carousel-item.active').attr('id')
},
success: function(data) {
console.log(data);
}
});
});
PHP
<?php
if(isset($_POST['idCarrosselAtivo'])){
$idCarrossel = $_POST['idCarrosselAtivo'];
if($idCarrossel === 'c1') {
echo $idCarrossel;
} else {
var_dump($_POST['idCarrosselAtivo']);
}
}
?>
It's not clear why you are sending back the ID when you just sent it to the script. This will send the ID and get some PHP back.
I check two values with ajax. And if both are correct then i want to make a submit (post-back).
But the post-back doesn't work.
Here is the code:
$('form').submit(function () {
var correctCaptcha = false;
var correctWebcode = false;
$.ajax({
url: '/Competition/CheckForm',
type: "POST",
data: $(this).serialize(),
success: function (data) {
if (data == true) {
$('#recaptcha_response_field').removeClass("captchaError");
correctCaptcha = true;
}
else {
Recaptcha.reload();
$('#recaptcha_response_field').addClass("captchaError");
}
}
});
$.ajax({
// like the code above (for webcode)
});
if (correctCaptcha == true && correctWebcode == true) {
document.forms['form'].submit();
}
else { return false; }
});
Use Async:false
$.ajax({
url: '/Competition/CheckForm',
type: "POST",
async:false,
data: $(this).serialize(),
success: function (data) {
if (data == true) {
$('#recaptcha_response_field').removeClass("captchaError");
correctCaptcha = true;
}
else {
Recaptcha.reload();
$('#recaptcha_response_field').addClass("captchaError");
}
}
});
This will cause the infinite loop:
if (correctCaptcha == true && correctWebcode == true) {
document.forms['form'].submit();
}
So use use like this here
if (correctCaptcha == true && correctWebcode == true) {
return true;
}
else {return false;}
Since ajax is async in nature you cannot expect those variables to be set right away when ajax call. You can either set async to false or submit the form inside success handler. Try this.
$('form').submit(function () {
$.ajax({
url: '/Competition/CheckForm',
type: "POST",
data: $(this).serialize(),
success: function (data) {
if (data == true) {
$('#recaptcha_response_field').removeClass("captchaError");
$('form')
.unbind('submit')//we dont need any handler to execute now
.submit();
}
else {
Recaptcha.reload();
$('#recaptcha_response_field').addClass("captchaError");
}
}
});
$.ajax({
// like the code above
});
return false;//To prevent the form from being submitted.
});
By default, $.ajax works asynchronously, your way won't submit the form, you should submit the form in the callback function.
I'm working on my first php/SQL database project and my goal is to store an array of checkbox values into a database.
On clicking the submit on the checkbox form, i am trying to post the array of checkbox values from my jquery doc to index.php
The success response is my index.php page, which i think is correct, so it all seems correct for me and i'm having a hard time figuring why
My array is generated from a series of .push() calls that update to determine when a box is checked it not and only submitted when i click my form submit, which should trigger the ajax post.
var checkArr =
[
{id: "CB1", val: "checked"},
{id: "CB3", val: ""},
{id: "CB5", val: ""},
{id: "CB4", val: "checked"},
{id: "CB2", val: ""}
];
//SUBMIT CHECKBOX VALUES TO PHP
$('#submitCheck').on('click', function(){
$.ajax({
url: 'index.php',
type: 'POST',
data: {checkArr:checkArr},
cache: false,
success: function(response){
alert("ok");
console.log(response);
}
});
});
Here however when i check to see if the post worked i only return 'is not set'.
if(isset($_POST['checkArr'])){
$arr = $_POST['checkArr'];
echo $arr;
} else {
echo 'Is not set';
}
I know there are many similar questions but i haven't found a solution in any of them unfortunately.
I found one thread that mentioned it might be redirecting me before the post can be processed so i removed the action from my form and nothing changed. I tried to stringify my output as json and still the same problem (even if stringify is redundant because of jquery).
Edit: Full code snippet
var checkArr = [];
//COLOUR ITEMS ON PAGE LOAD
$(document).ready(function(){
var box = $(':checkbox');
if(box.is(':checked')){
box.parents("li").removeClass('incomplete');
box.parents("li").addClass('complete');
} else {
box.parents("li").removeClass('complete');
box.parents("li").addClass('incomplete');
}
});
//DELETE ITEM
$(document).on('click','.delete', function(){
console.log('DELETED');
var id = $(this).attr('id')//get target ID
var item = $(this).closest('li');//targets the li element
//AJAX
$.ajax({
url: 'delete.php',
type: 'POST',
data: { 'id':id },
success: function(response){
if(response == 'ok') {
item.slideUp(500,function(){
item.remove();
});
} else if(response == 'error') {
console.log("error couldn't delete");
} else {
console.log(response);
}
}
});
});
//CREATE ARRAY OF CHECKBOX VALUES
$('#checkform').on('click','.boxcheck', function(){
var check = $(this).prop("checked");
var val = "";
var tempId = $(this).attr('id');
if(check === true){
val = "checked";
console.log(val);
var tempArr = {
"id": tempId,
"val": val
};
checkArr.push(tempArr);
} else if (check === false){
val = "";
console.log(val);
for (var i = checkArr.length - 1; i >= 0; --i) {
if (checkArr[i].id == tempId) {
checkArr[i].id = tempId;
checkArr[i].val = val;
}
}
}
console.log(checkArr);
});
//CHANGE COLOUR OF ITEMS
$(':checkbox').change(function(){
var current = $(this);
if(current.is(':checked')){
current.parents("li").removeClass('incomplete');
current.parents("li").addClass('complete');
} else {
current.parents("li").removeClass('complete');
current.parents("li").addClass('incomplete');
}
});
//SUBMIT CHECKBOX VALUES TO PHP
$('#submitCheck').on('click', function(e){
e.preventDefault();
console.log(checkArr);
$.ajax({
url: 'index.php',
type: 'POST',
data: {checkArr:checkArr},
cache: false,
success: function(response){
alert("ok");
}
});
});
I tried your code and it's working perfectly for me.
Now the only thing I can think of is your url in your ajax request. make sure you are really submitting to index.php.
You can use JSON.stringify() to submit the array from ajax to php
Posting here to update just in case anyone has a similar problem, the code itself was correct(sort of), after a lot of digging and asking around, it turns out the local server i was using, XAMPP, had too small a POST upload limit hence the empty array on the php side, increasing the php.ini upload limit from 2mb to 10mb finally fixed it!
I'm having a problem with my ajax code. Its supposed to check a returned value from php, but it's always returning undefined or some other irrelevant value. As i'm quite new to ajax methodologies i can't seem to find a headway around this. I've searched numerous link on stackoverflow and other relevant forums regarding the solution but none helped. The problem remains the same
Here is the ajax code::
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
dataType: 'json',
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
});
return false;
})
});
The problem lies with outputting the value of data. The php code returns 1 if the value is successfully entered in the database and 0 otherwise. And the ajax snippet is supposed to check the return value and print the appropriate message. But its not doing such.
Here is the php code::
<?php
require './fileAdd.php';
$dir_path = $_POST['path'];
$insVal = new fileAdd($dir_path);
$ret = $insVal->parseDir();
if ($ret ==1 ) {
echo '1';
} else {
echo '0';
}
?>
I can't find a way to solve it. Please help;
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
//dataType: 'json', Just comment it out and you will see your data
OR
dataType: 'text',
Because closing } brackets not matching try this
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path},
type: 'POST',
dataType: 'text', //<-- the server is returning text, not json
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
} //<-- you forgot to close the 'success' function
});
return false;
});
});
updated my question below
I made a script where a user can import large amounts of data. After the form is submitted and the data validated I add 2 background tasks: 1 is a script that imports all the data. This script also lets the databases know how many in total and how many he has done. The second is a script that reads how much is done from the database and displays it in a nice progress bar.
Code:
$.ajax({
type: "GET",
url: "import-process.php",
success: function(data) {}
});
var process = 0;
var checkPercentage = function() {
$.ajax({
type: "GET",
url: "get-process-status.php",
data: "importcode=123456",
success: function(data) {
if (!data.indexOf("ERROR") !== -1) {
process = data;
$("#process_balk").css('width', process + '%');
}
}
});
if (process != 100) {
setTimeout(checkPercentage, 1000);
} else {
window.location.href = "import-finished.php";
}
}
checkPercentage();
Both scripts, work fine. Except that the second script (getting the status of the process) isn't started after the first (importing the data) is finished. Which makes the complete thing kinda useless.
Any ideas how to solve this?
update:
I found out that the background process gets called only once. That's the problem. I'm just not sure how to fix it..
var checkPercentage = function() {
alert("Is this function getting called every second?");
$.ajax({
type: "GET",
async: true,
url: "required/get-process-status.php",
data: "importcode=123456",
success: function(data) {
alert(data);
}
});
setTimeout(checkPercentage, 1000);
}
The code above alerts "Is this function getting called every second?" every second. Like it should. However, the value 'data' is called only once. That's not what I expected.. Any ideas?
You mean like this?:
$.ajax({
type: "GET",
url: "import-process.php",
success: function(data) {
checkPercentage();
}
});
var process = 0;
var checkPercentage = function() {
$.ajax({
type: "GET",
url: "get-process-status.php",
data: "importcode=123456",
success: function(data) {
if (!data.indexOf("ERROR") !== -1) {
process = data;
$("#process_balk").css('width', process + '%');
}
}
});
if (process != 100) {
setTimeout(checkPercentage, 1000);
} else {
window.location.href = "import-finished.php";
}
}
I just moved checkPercantage function call from end of script to success function of first ajax. You can also move it to complete function if you wish to run it despite of errors.
Set your callback function to be:
success: function(data) {
if (!data.indexOf("ERROR") !== -1) {
process = data;
$("#process_balk").css('width', process + '%');
if (process != 100) {
setInterval(checkPercentage, 1000);
} else {
window.location.href = "import-finished.php";
}
}
}
Firstly, the if statement has to be in a callback function to work the way you want it. Secondly, you should use setInterval() instead of setTimeout() because it will recheck it every interval time.
Also, yabol is right saying that the top of your code should look like this:
$.ajax({
type: "GET",
url: "import-process.php",
success: function(data) {
checkPercentage();
}
});