Dom Value After Ajax Call - php

I have a table where one field is titled a secure password. In this field, there is an input button that calls an AJAX function. The AJAX function on return updates the password in the secured password field. This updates the DOM value for that field.
On this same page I have another function which uses Javascript to parse all the elements in the table into an array. The problem is the Javascript function is writing what was originally in the secure password field rather than what the AJAX function has updated it to.
It seems as though Javascript does not pull the current DOM value but the DOM value when the page was loaded. Is this the default nature of Javascript and if so how can I get around this so I can get the current values for all fields in the table, not just the page load values.
This script is written in PHP/Javascript, thanks in advance for the assistance.

Your Javascript function that parse all elements in the table into an array uses
the document.ready function or is loaded only once when the Page is loaded.
In Vanilla JS
document.addEventListener('DOMContentLoaded', (event) => {
//Where you wrote your function
})
Jquery
$(document).ready(function() {
// where you have your function if you are using Jquery
});
And AJAX calls do not reload the page. That means your Javascript function does not get executed so it does not update the array with the new data from the calls.
You need your Javascript as a callback function to the success or complete property of the AJAX call.
jQuery.ajax({
type: 'POST',
url: ajaxurl,
success: function() {
parsingFunction();
},
error: function() {
alert(errorThrown);
}
});

Did you try using a hidden input field for storing the data instead of updating the text input? Or may be you can try using the data-xxx attributes
bests,

Related

JQuery: Select an id generated by PHP

I generate through PHP an HTML input (id="newItem") and a HTML paragraph (id="newDesc") in the already existing HTML table (id=detailedTable). After trying to fire off a function by using $("#newItem").change(function()..., I found out that since it was generated dynamically I had to refer to it using the Jquery .on(). Now this part works.
My issue is on the return of the Ajax call, I try to change the #newDesc value, but it is not working. I suspect for the same reason that this ID was dynamically generated.
$("#detailedTable").on('change','#newItem',function(){
var value=$(this).val();
value=value.replace(/\,/,'.');
value="value="+value;
$.ajax({
url:'z-getDesc.php',
type:'POST',
dataType:'json',
data:(value),
success:function(values){
values=values['descriptionA'];
$("#newDesc").val(values);
},
fail: function(xhr, textStatus, errorThrown){
alert('Please try again later');
}
});
});
Up to that point everything works fine, the 'values' variable is returned, all is left is :
How can I refer to #newDesc id?
Thanks
Edit: To clear some things up:
1- The DOM is initially loaded, and users interact with it, bringing in some changes resulting in an array of data.
2- This arrays is loaded up in a table created via JQuery Datatables by an ajax call; in addition to populating the table with the array, I also generate a line for inline editing, line which contains the afore-mentioned #newItem and #newDesc.
You need to call $("#detailedTable").on after you generate the content. Javascript is executed when the page is loaded, so when the javascript executes, it can't find the chosen id and doesn't try again. Add some javascript to whatever user interaction that generates the content that calls .on and it should work.

Event.prevent() default ajax not sending data from form to php

I already checked around for this answer but all are different problems just same title (to prevent random duplicate marks).
Here is an ajax call to the click of the filter button that should send the data inserted in the form formmatcat to the php file formfilt.php and should load the result in a div with id resultins
<script>
$(function () {
$('#filter').on('click', function(event){
event.preventDefault();
$.ajax({
type: 'post',
url: 'formfilt.php',
data: $('#formmatcat').serialize(),
success: function () {
$("#resultins").load('formfilt.php');
}
});
});
});
</script>
I set the preventdefault to load only in the div without redirecting to the php file and this works but if I put the preventDefault it echoes the string I build by concatenating values sent from the form with those empty values. The strange thing is that if I remove preventDefault of course it redirects and loads the php file but with the correct values:
Moral of the story, data in the form with the ajax call goes correctly to the php file but looks like preventDefault don't let this. Thanks in advance
Here's the structure of the html part with the form
<form id="formmatcat" method="post" action="formfilt.php">
.
.
various textboxes
.
.
</form>
What you're doing is sending an AJAX request toformfilt.php, when this call happens and it returns a response it will be stored as a parameter within the success or $.done function as I'll mention later, that is where your echo'd content will be.
What you're doing here is when the call is successful, you simple send a GET request to the same page. Since that GET request differs from the AJAX POST request and has no POST parameters you'll not get the correct output.
By simply submitting the form and letting it go to the page rather than cancelling the request you're getting the right values as you're directly posting to the page with the correct values, when you call the load function you're doing a seperate AJAX get request.
What load actually is, is a rough equivelant to $.get which is shorthand for $.ajax.
Looking at jQuery AJAX docs
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.
Basically, a $.ajax() call returns a promise object that you can chain callbacks on when it is finished. Also note that data here will be the actual content within your PHP file, thus if you rewrite your AJAX call like so:
<script type="text/javascript">
$(function() {
$('#filter').on('click', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'formfilt.php',
data: $('#formmatcat').serialize()
}).done(function(data) {
$('#resultins').html(data);
});
});
});
</script>
It will then continue to load the output of formfilt.php into the div with ID resultins.
dont use form, use input without form, and use button tag use onclick to run function, if you use form, it will submit and redirect,
i'm not good with ajax on jQuery
but if i were to use javascript/XHR
var CB=document.getElementById("filter").value; //get input/filter value
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200)
document.getElementById('contain').innerHTML=xhttp.responseText;
};
var url="formfilt.php?filter="+CB;
xhttp.open("GET", url, true);
xhttp.send();
if you want to use post :
xhttp.open("POST", "formfilt.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('filter='+CB);
sorry, i'm also learning, and new to this, just learning a week ago,

How to populate a DIV after MySQL update with JQuery

I'm developing an AJAX project using jQuery. I'm thinking of creating a page that displays data from a table. On this page, I want to put a form to add another row to this table.
The problem is that I want to update the table on my page as soon as I have submitted the new data. Is that even possible? If so, how?
What you could do is bind an event to the submit button for the form.
$('#formbutton').click(submit);
Then load the values from the fields in the submit() function and then use $.ajax to submit the POST request and define a success call function to do a GET ajax request
function submit(){
var field1 = $('#field1').val();
var field2 = $('#field2').val();
$.ajax({
url: 'submitform.php',
type: "POST",
dataType: "text",
data {field1: field1, field2, field2},
success: function(data){
getData();
}
});
}
function getData(){
$.get("table.php",function(data){
$('#table').html(data);
});
}
You make the AJAX request to your script.
Your script does its work and returns the new data.
Your AJAX query's success handler function updates the page with the received data.AJ
Just look at the examples in the jquery documentation:
http://api.jquery.com/jQuery.ajax/
Use jQuery ajax to send the form results to a PHP script, get the PHP to update/insert to the mysql db, then get the PHP to echo out the table data to the jQuery success callback, in which you take received data and place it in a div/table!
To get you started:
http://blog.twostepmedia.co.uk/send-html-form-results-in-an-email-from-php-using-jquery-ajax/

Passing values from ajax page to calling page javascript function

One part of my page is being loaded via ajax using jquery. For example this initial page has a name first.php. It has a div with it's innerHTML generated from ajax called script (for example ajax is calling second.php). Is it possible to pass some values from ajax executed script (second.php) to original site. I need to access this value from original site (the one calling second script via ajax) javascript function, and I don't want to use hidden fields.
For example, my site has some captcha that is being displayed and processed through ajax. I don't want to write captcha result to some hidden field and access it with original site javascript function because of possible javascript injection attack...
Since you call your secound.php script via ajax, you surely could read the result.
$.ajax({
url: 'secound.php',
success: function(data) {
// now data contains the code returned by secound.php
}
});
Now the most common way to return data from your secound.php script is returning it in JSon format. Then you could do someting like:
var obj = jQuery.parseJSON(data);
alert(obj.name);
For this example your secound.php needs to return
{"name":"John"}

HTML Select selected value in php variable

I have a drop down in html.
When I change the value of the drop down I want to store the selected value in a php variable
How can i achieve this ?
Technically it is impossible. PHP is server side, HTML is client side. When a user calls up a URL the server runs the PHP which gets sent to the HTML, so you can not go backwards.
You can however use ajax to get the value of the select box and use it in some meaningful way. What are you wanting to do with this variable?
EDIT
Using jQuery I would send the value of the select box to an ajax file, and then have the ajax file create the text box if the value is what you want it to be. Here is an example.
$("#selectEle").change(function() {
$.ajax({
type: "POST",
url: "yourajaxpage.ajax.php",
data: {selectVal: $(this).val()},
success: function(response) {
$("#textBoxArea").html(response);
},
error: function() { alert("Ajax request failed."); }
}
});
You will grab the value in your ajax page using $_POST['selectVal']. Test that value there, and create an HTML textbox which gets sent back to the success function.
Without submitting the form, this can be done using an AJAX call (see libraries like Prototype and MooTools for easy methods) all off the onchange HTML attribute of your select tag.
yes, as suggested a javascript/ajax implementation would be a good fit here.
I use jQuery but I'm assuming it can be achieved in other libraries.
Anyway .change() in jQuery would work for this. When a user changes the selected index of the drop down it triggers the the .change() function and you would insert more javascript conde inside of this function to make the needed changes.
If you wanted you could find out the selected index or get the value of the selected index and put in logic based around that to load your textbox (also using javascript).
Something like
$('target').change(function() {
var value = $('target').val(); // gets the selected value
if(value == "what you want it to be")
{
// load data into a div from your php file.
$('#loading_div').load('ajax/test.html');
}
});
That should definitely get you started.

Categories