Jquery AJAX appended data reset - php

I've this script:
<script>
$(document).ready(function() {
$('#signUpForm').submit(function() {
$.ajax({
type: 'POST',
url: "process.php",
data: $("#signUpForm").serialize(),
success: function(data)
{
$('#errors').show();
$('#errors').append(data);
}
});
return false;
});
});
</script>
It displays errors from php script. And right now every time I click submit button, new errors are added to old ones. I wonder, is it possible to reset old errors and show just new, after I click submit button?

Use $('#errors').html(data); instead of $('#errors').append(data);, When you use .append(), you add to the content you already had. .html() replaces the content.
Another alternative might be to empty first and then append. Like $('#errors').empty().append(data);
I wonder why do you have $('#errors').show();? If it was hidden first, maybe better to put .show() after the .html() / .append()`

Use $('#errors').empty().append(data);

Related

script inside bootstrap modal

Something weird - I have the script inside the bootstrap modal.
sometimes the script is loaded and works and sometimes it doesn't.
here is a URL for example:
https://ns6.clubweb.co.il/~israelig/sites/followmyroutes/test_sec.php
Click on the button and see the modal, then close the modal and open it again. After the couple of times, the scripts inside the modal stops working (scripts like form validation [when you submit it], image browser)
How can I fix it so all the script will work every time?
The way you populate the html is right or not suggested to be advised by coders. Check again from where you got the documentation.
your existing code from backend call
$(document).on('ready', function() {
$("#input-8").fileinput({
});
});
Try changing like
$(document).on('ready', function() {
setImageUploader();
});
function setImageUploader(){
$(document).find("#input-8").fileinput({
});
}
And also
$.ajax({
cache: false,
type: 'GET',
url: 'itinPage-secManage.view.php',
data: info,
success: function(data) {
$modal.find('.modal-body').html(data);
setTimeout(function(){ //added this line.
setImageUploader()
})
}
});
i think the problem in the syncronisation of the request, you can use Ajax reque
It looks like your common libraries like jquery bootstrap-datepicker, fileinput theme etc are being get every time the modal is launched.
This may cause a sort of namespace corruption or some weird side effect of the kind you seem to see.
You could put all the common libraries outside of the modal to prevent this from happening.
the problem in the ajax request, I means you maste waite while the request it's done.
var request = $.ajax({
cache: false,
type: 'GET',
url: 'itinPage-secManage.view.php',
data: info
});
request.done(function(data) {
$modal.find('.modal-body').html(data);
});

jQuery AJAX post to PHP for PDO INSERT not working with variables $('#id').val()

I am showing 3 code-snippets.
Approach 1 and 2 do NOT work
The 3rd code IS WORKING.
********* not working1 start **************
<script>
$(document).ready(function() {
$('#sending').click(function(){
// just 4 testing:
//var txtBoxVal = $('#TextBox1').val();
// alert(txtBoxVal); ==> ok: showing the value I want to send & INSERT into database via PDOinsertpost.php
$.ajax({
type: "POST",
url: "./PDOinsertpost.php",
data: 'postVal1=' + $('#TextBox1').val(),
success: function(msg){
$('#reshow').html(msg);
}
}); // end Ajax Call
// now trigger a reload via the click-function:
window.location.reload();
}); //end event handler .click function
}); //end document.ready
</script>
********* not working1 end **************
now the approach with the variable inside the $.ajax (not working as well):
********* not working2 start **************
<script>
$(document).ready(function() {
$('#sending').click(function(){
var txtBoxVal = $('#TextBox1').val();
// an alert - just 4 testing:
// alert(txtBoxVal); // ok: showing the value I want to send & INSERT into database via PDOinsertpost.php
$.ajax({
type: "POST",
url: "./PDOinsertpost.php",
data: 'postVal1=' + txtBoxVal,
success: function(msg){
$('#reshow').html(msg);
}
}); // end Ajax Call
// now trigger a reload via the click-function:
window.location.reload();
}); //end event handler .click function
}); //end document.ready
</script>
********* not working2 end **************
and now the "hardcoded", working version (?courious for me, that this one is working - but the others do not...)
********* the working1 start **************
<script>
var txtBoxVal = "some hardcoded string for testing";
$(document).ready(function() {
$('#sending').click(function(){
$.ajax({
type: "POST",
url: "./PDOinsertpost.php",
data: 'postVal1=' + txtBoxVal,
success: function(msg){
$('#reshow').html(msg);
}
}); // end Ajax Call
// now trigger a reload via the click-function:
window.location.reload();
}); //end event handler .click function
}); //end document.ready
</script>
********* the working1 end **************
Additional Info.: in the meantime I figured out, that an empty value is working with the two "not-working" code-snippets with $('#id').val(),
this means: a blank value is inserted in the database.
Am I searching at the wrong place?
Do I need to do some htmlentities - stuff or something within the .php file with the PDO-INSERT?
I hope, some useful information can be gathered by this post - for me, as well as for others.
Thanks in advance,
-Flow.
I see 2 big problems here:
You are reloading the page (in all your examples...) while the ajax request has not yet finished. That is a very risky and buggy approach as you cannot be sure that your php script will finish correctly. And if you reload any way, you don't need ajax.
You are not escaping your value so user input can break the query string. The easiest solution for that is to use an object so that jQuery encodes it correctly automatically:
data: { 'postVal1': $('#TextBox1').val() },
I also don't see you cancelling the default form submit, but as the third example works, I assume that the button / #sending element is not a submit button. If not, you would need to take care of that as well.
Edit: As you are using a submit button, you need to prevent the regular form submit:
$('#sending').click(function(event){
// prevent the default form submit
event.preventDefault();
...
without the "window.location.reload();" it seems to work!
#jeroen had probably the right explanation: the reload disturbed the process!
(but it didn't on my virtual home-server ... (may be, because of other processing-times... ))

Auto reload a `DIV` after checkbox form change

I am trying to get a div to reload once a checkbox has been selected or unselected and the form has been submitted. I have used AJAX and can get the form to submit on change, which works no problem. However the page has to reload to display new data.
I have built the php in such a way that it doesn't need to refresh the page or fetch a new page. If the div and it's content refreshes that should be sufficient to display the new filtered data.
Below is what I have written so far
$(document).ready(function() {
$("input:checkbox").change( function() {
$.ajax({
type: "POST",
url: "index.php?action=resortFilter",
data: $("#locationFilter").serialize(),
success: function(data) {
$('.resorts').html(data);
}
});
})
});
What do I need to do to get the div to reload after the request has been made?
I use class methods to handle the processing which return only the array of data. The requests are made to the class from a php function.
What I'm trying to do isn't actually possible to because PHP is a server side language. The best bet is to create a new intermediate file that can handle the display of the data so that it can be brought in through a normal AJAX request and get the new display from it
Where is the Ajax request? You are submitting your form through HTML/Browser. You need to use the following code:
$(document).ready(function() {
$("input:checkbox").change( function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#locationFilter").serialize(), // serializes the form's elements.
success: function(data)
{
$('.resorts').html(data);
}
});
})
});
Source: jQuery AJAX submit form
this sample loading code maybe help you
<div id="loadhere"></div>
$('div#loadhere').load('ajaxdata.php',{datatosend:whatyouwantforexamplehelloworld});

ajax append causes javascript to be executed multiple times

I've created a dynamic table in PHP, where every image in a row has a specific url in the ID.
For example:
When a user clicks on this image, it executes an action. This works fine.
Afterwards, in the second ajax, it's supposed to reload the colorbox with the previous url. This also works, however, the javascript seems to be loaded again (with the new values though)?
$('#cboxLoadedContent img[alt="markmessage"]').live('click', function(){
var returnurl = "<?php echo $_SESSION['returnpage']; ?>";
var markurl = $(this).attr('id');
alert(markurl);
// Do the action
$.ajax({
method:'GET',
url: markurl,
cache:false
});
// Reload colorbox again with previous contenturl.
$.ajax({
type: 'GET',
url: returnurl,
dataType: 'html',
cache: true,
beforeSend: function() {
$('#cboxLoadedContent').empty();
$('#cboxLoadingGraphic').show();
},
complete: function() {
$('#cboxLoadingGraphic').hide();
},
success: function(data) {
$('#cboxLoadedContent').empty();
$('#cboxLoadedContent').append(data);
}
});
});
</script>
Is there any way to PREVENT the javascript from being re-appended to the colorbox? I've tried a few methods (like removing it with DOM), but nothing seems to work...
The javascript may NOT be disabled, it's supposed to process a new url afterwards...
Try to replace live to one in first line:
$('#cboxLoadedContent img[alt="markmessage"]').one('click', function(){
Try the simple click event binding. Here you only bind it to the selected elements, not to new appended elements. If you want the event to be fired only once, use one.
I'm not sure which version of jQuery you are using, but live() is deprecated as of 1.7, you might want to try using on().

Ajax jquery returns blank page

I have this JavaScript code:
$(document).ready(function(){
$('#sel').change(function(){
$.ajax({
type: "POST",
url: "modules.php?name=TransProject_Management&file=index",
data: "&op=index_stat&stat="+$(this).val(),
cache: false,
success: function(data) {
//alert(data);
$("#ajax_results").html(data);
}
});
});
});
On status change i need to refresh a div without page reload. But it returns blank page. If i try alert the result on success, i get the response, also i checked with inspect element, its ok. The problem is that it returns blank page.
The file i'm working on, is the same( modules.php?name=TransProject_Management&file=index ) i called in ajax.
the html:
<body>
//...
<div id="ajax_results">
//.....
//somewhere here is the select option <select id="sel">......</select>
//.....
</div>
</body>
Any help, would be very appreciated.
use the following code to return your response html:
echo json_encode(array($your_response));
Then in your javascript, you will need to reference the data as:
success: function(data) {
$("#ajax_results").html(data[0]);
}
since it is now an array.
this in your ajax function refers to the jQuery XHR object, NOT the $('#sel') object. Just assign it to a variable before the ajax function like var sel = $(this) then use it later inside the function. Try this:
$('#sel').change(function(){
var sel = $(this);
$.ajax({
type: "POST",
url: "modules.php?name=TransProject_Management&file=index",
data: "&op=index_stat&stat="+sel.val(),
cache: false,
success: function(data) {
//alert(data);
$("#ajax_results").html(data);
}
});
});
});
Hmm, first glance the code looks good. Have you tried using Chrome debug tools? Hit F12 and check the Network tab, this will show you what is being returned. You can also debug without using an alert so you can step through to see what exactly the properties are.
Just thought, you might need to add 'd' to the data returned. Anyway, if you do what I suggested above, put a pause break on the line and run the code you will see what you need.
Based on your comments below the question, it seems that you are using the same script to display your page and to call in the javascript. This script seems to return a complete html page, starting with the <html> tag.
A page can only have one <html> tag and when you try to dump a complete html page inside an element in another page, that will lead to invalid html and unpredictable results.
The solution is to have your ajax script only return the necessary elements / html that needs to be inserted in #ajax_results, nothing more.

Categories