Please help,
I have a dynamically generated set of button-incremented inputs. First i store id's and values into localstorage, and everything goes fine and i can see all the id-value pairs, but i cannot send the data using AJAX call.
Here's what it looks like:
The AJAX is assigned on button click:
<script>
$("#send_order").click(function (e) {
if (localStorage) {
if (localStorage.length) {
for (var i = 0; i < localStorage.length; i++) {
var pid = localStorage.key(i);
var value = localStorage.getItem(localStorage.key(i));
$.ajax({
url: "update.php?pid="+pid+"&qty="+value,
success: function(){
alert( "Прибыли данные: ");
}
});
}
} else {
output += 'Нет сохраненных данных.';
}
} else {
output += 'Ваш браузер не поддерживает локальное хранилище.';
}
)};
</script>
But nothing happens when the button is clicked.
What i do wrong?
While your code looks fine it is little inefficient to send your localstorage data one by one in a loop. It makes more sense to convert your localstorage to a json string and send everything at the same time. You can json_decode the json string in your php update script. Also I included a function to test if localStorage is available by trying to write in it. This is more reliable then if(localStorage)
$("#send_order").on("click", function () {
var output='';
if(localStorageTest() === true){
console.log('localStorage is available');
if(localStorage.length){
var data=JSON.stringify(localStorage);
$.ajax({
type: "GET",
url: "update.php?data="+data,
success: function(){
alert( "your data is send correctly!");
}
});
}else{
output += 'localStorage is empty\n';
}
}else{
output += 'localStorage is not available\n';
}
})
function localStorageTest(){
var test = "test";
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
Related
I have a PHP process which updates files, and writes a status report with each file.
While that is happening, I was hoping to update the user's browser until the final response.
Unless there is a better way, I simply wanted some advice on how to loop infinitely refreshing getJSON() results until the ajax response comes.
What is the best way to do this?
This ended up being the solution I used:
$(document).on('click', "#ss_batch_edit_processing", function (e) {
var ids = get_selected();
var status_location = '<?php echo symbiostock_TMPDIR . '/report.txt' ?>';
if(ids == 0){
return;
}
$('.' + loading_icon_small).show();
var data = {
action: 'ss_professional_ajax',
security: '<?php echo $ajax_nonce; ?>',
reprocessing_action: $('input:radio[name=ss_reprocessing_action]:checked').val(),
ids: ids,
};
var completed = 0;
$.post(ajaxurl, data, function (response) {
$('.' + loading_icon_small).hide();
completed = 1;
});
var get_update = function(){
$.getJSON(status_location, function (data) {
var update = '<ul><li><strong>'+data['title']+'</strong></li><li><strong>Count:</strong> '+data['count']+' / '+data['total']+'</li><li><strong>Last processed</strong>: Image # '+data['last_id']+'</li></ul>';
$('#ss-reprocessing-results').html(update).delay(1000);
});
if(completed == 1){
clearInterval(timed_requests)
return false;
}
};
var interval = 1000; // every 1 second
var timed_requests = setInterval(get_update, interval);
});
My ajax call goes and enters a record into a database (it's the first part of a form recording data) so I need it to return the id from the database entry.
Problem is, it's firing twice, so it's making 2 database entries each time.
I tried using a $count and while($count>0) in my php code to make sure that wasn't looping - and I didn't think it was, so the problem lies in my jQuery.
I tried putting the preventDefault on my submit button click function and that didn't work either.
Here's my code:
$(document).ready(function(){
$('#wpgstep1').one('click',function(){
// validate form fields are all filled in
var budget=$('#budget').val();
if(budget=='')
{
$('#budgeterror').show();
}
var yellowpages=$('#ads-yellowpages').val();
var flyers=$('#ads-flyers').val();
var brochures=$('#ads-brochures').val();
var radiotv=$('#ads-radiotv').val();
var none=$('#ads-none').val();
var other=$('ads-other').val();
var otherstatement=$('ads-other-statement').val();
var cust_id=$('#cust_id').val();
if(other !='')
{
if(otherstatement==='')
{
$('#adsothererror').show();
}
}
else
{
otherin='0';
}
if(yellowpages==="on")
{
yellowpagesin='1';
}
else{
yellowpagesin='0';
}
if(flyers==="on")
{
flyersin='1';
}
else
{
flyersin='0';
}
if(brochures==="on")
{
brochuresin='1'
}
else
{
brochuresin='0';
}
if(radiotv==="on")
{
radiotvin='1';
}
else
{
radiotvin='0';
}
if(none==="on")
{
nonein='1'
}
else
{
nonein='0';
}
var dataString='cust_id=' + cust_id + '&step=1&budget=' + budget + '&yellowpages='+yellowpagesin + '&flyers=' + flyersin + '&brochures=' + brochuresin + '&radiotv='+ radiotvin + '&none='+ nonein + '&other=' + otherstatement;
$.ajax({
type: "POST",
url: "submitwpg.php",
data: dataString,
dataType:'json',
success: function(data)
{
alert(data);
var i="";
var p=eval (data);
for (i in p)
{
$('#wpgpart2').append('<input type=hidden name=wpgid value=' + p[i] + '>');
}
$('#wpgform1').hide();
$('#wpgform2').show();
}
});
return false;
});
});
Make a global var
var form_submitting = false;
Above your ajax call
if(form_submitting == false){
form_submitting = true;
//your ajax call
}
In your success function of your ajax call
form_submitting = false;
if your submit button is inside of a form, it may be possible that your ajax function is executing and then your form is posting regularly. You could try turning your
<input type='submit' />
into
<button type='button' onclick='validateAndAjaxFunction(); return false;'></button>
Im trying to send some data to the server through AJAX with the value i get from a JS variable.
Code:
<script type="text/javascript">
var url;
function aplicarFoto(_src) {
url = _src;
var fotosel = document.getElementById("fotosel");
fotosel.src = 'fotos/'+_src;
}
function guardarCambios() {
$.post("guardarCambios.php",
{url: url},
function(response) {
alert(response);
if (response == "NoUsuario") {
window.location = "../login.php";
} else {
alert("correcto");
}
}
alert(url);
}
</script>
The idea is update the user picture with the url i get from aplicarFoto(_src) with the variable url .
The first function (aplicarFoto(_src)) alone works correctly, but when i put the another function (guardarCambios()), the first function doesnt work, therefore the second neither! I dont know why, but it just happens when using ajax functions because i did a test with an alert(url) (sunrrounding the rest of code with comments) in the second function and both work correctly!
Some guess? Thank you!
Your script alone has syntax errors.
<script type="text/javascript">
var url;
function aplicarFoto(_src) {
url = _src;
var fotosel = document.getElementById("fotosel");
fotosel.src = 'fotos/' + _src;
}
function guardarCambios() {
$.post("guardarCambios.php", {
url: url
}, function (response) {
alert(response);
if (response == "NoUsuario") {
window.location = "../login.php";
} else {
alert("correcto");
}
alert(url);
}
);
}
</script>
I have a little bit of a problem, I have a JavaScript with jQuery where I work with an Array I got from PHP, in the script I add some data to two new arrays and here comes my problem, how can I work with those two arrays in my PHP file? I need to save the data from the two new arrays in a database. In the PHP I have a form where I enter some data about a User. Does someone knows a easy way to send my data back to the PHP?
Some information about the script: I have a table with the names of schools, and a checkbox with the id of the school as a value. when i check or uncheck one of the checkboxes the script checks if it is a school already saved in the database for this specific user or if it's a new user.
<script>
var schools = [];
var oldschools = [];
var uncheckedschools = [];
oldschools = <?php echo json_encode($oldschoolids); ?>;
$(".checkbox").change(function() {
if(this.checked) {
var additem = $(this).val();
for (var i=0; i<oldschools.length; i++) {
if (additem == oldschools[i]) {
uncheckedschools = jQuery.grep(uncheckedschools, function(value) {
return value != additem;
});
}
}
schools.push(additem);
} else {
var removeitem = $(this).val();
for (var i=0; i<oldschools.length; i++) {
if (removeitem == oldschools[i]) {
uncheckedschools.push(removeitem);
}
}
schools = jQuery.grep(schools, function(value) {
return value != removeitem;
});
}
});
</script>
I hope someone can help me with this problem!
You'll need to use AJAX to send your updates back to your server. Using jQuery's ajax() method, it would looks something like this:
$.ajax({
url: 'path/to/serverside/file.php',
dataType: 'json',
data: {schools: schools},
success: function(dataFromServer) {
//after the save is successful, you can do something here
},
error: function(dataFromServer) {
//if there was an error handle it here
}
});
EDIT: As mentioned by a few commentors, you'll need to use json_decode on the server-side to decode the JSON Object you're sending back: http://php.net/manual/en/function.json-decode.php
I have this
"fsField" is the class of all elements in the form. So whenever the user blurs to another field it submits the form using the function autosave() - given below. It saves data when the user blurs but when the user clicks the button with class "save_secL" to go to next page it does not save.
$('.fsField').bind('blur', function()
{
autosave();
}
});
but when i use this code
$('.save_secL').click(function()
{
var buttonid = this.id;
{
var answer = confirm("You have left some questions unanswered. Click OK if you are sure to leave this section? \\n Click CANCEL if you want stay in this section. ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="unanswered" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="answered all" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
});
**autosave_secL.php is the php source thats saving the data in the database. I ran it independently and it does save data okay. **
function autosave()
{
var secL_partA_ques_1_select = $('[name="secL_partA_ques_1_select"]').val();
var secL_partA_ques_1 = $('[name="secL_partA_ques_1"]:checked').val();
var secL_partA_ques_2_select = $('[name="secL_partA_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partA_ques_1_select=" + secL_partA_ques_1_select + "&secL_partA_ques_1=" + secL_partA_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
}
});
}
**
valid() is a validation function that checks if any field is empty and returns a value if there is an empty field.**
function valid()
{
var items = '';
$('.fsField').each(function()
{
var thisname = $(this).attr('name')
if($(this).is('select'))
{
if($(this).val()=='')
{
var thisid = $(this).attr('id')
items += "#\"+thisid+\",";
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '#B5EAAA');
}
}
else
{
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '');
}
});
return items;
}
Can anyone please help? i am stuck for a day now. Can't understand why it saves when the user goes field to field but does not save when button is clicked with validation.
Tested with Firefox. this line appears in red with a Cross sign beside when the button(save_secL class) is clicked. I am using a ssl connection.
POST https://example.com/files/autosave_secL.php x
Here is the modified code trying to implement the solution
$('#submit_survey_secL').click(function()
{
if(valid() !='')
{
var answer = confirm("You have left some questions unanswered. Are you sure you want to Submit and go to Section B? ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=4"
});
}
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=6"
});
}
});
function autosave(callback)
{
var secL_partL_ques_1_select = $('[name="secL_partL_ques_1_select"]').val();
var secL_partL_ques_1 = $('[name="secL_partL_ques_1"]:checked').val();
var secL_partL_ques_2_select = $('[name="secL_partL_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partL_ques_1_select=" + secL_partL_ques_1_select + "&secL_partL_ques_1=" + secL_partL_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
{
callback();
}
}
});
}
I don't understand why this doesn't work as callback should totally work. Firebug does not show POST https://example.com/files/autosave_secL.php in red any more but it shows that it has posted but I think the callback is not triggering for some reason
$('.save_secL').click(function() {
//...
//start autosave. Note: Async, returns immediately
autosave();
//and now, before the POST request has been completed, we change location...
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
//....and the POST request gets aborted :(
Solution:
function autosave(callback)
{
//...
$.ajax(
{
//...
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
callback();
}
});
}
//and
autosave(function(){
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
});
By the way, your autosave function is pretty hard for your server. Did you consider using localStorage + a final POST request containing all data?
I got the solution.
It might be one of the several. scr4ve's solution definitely helped. So here are the points for which I think its working now.
Moved "cache: false, " and removed "async:false" before url: in the ajax autosave function. Before I was putting it after "data: "
Added a random variable after autosave_secL.php/?"+Match.random()
Added scr4ve's solution so that POST is completed before redirect