I'm rather new to terminology and coding in general, but I've tried to trim down my code, though it may still have redundancies. Thanks in advance for your understanding.
I'm using an ajax and php script to write some data to a file on the server called data.json. The script works fine, and opening the json file shows that it's indeed updated with the data. The json file simply contains an array of objects.
Here's the code that does this:
function writeData() {
$.ajax({
type : "POST",
url : "save.php",
async : true,
data : {
json : JSON.stringify(dataToWrite)
}
});
document.getElementById('success-box').innerHTML = "Data successfully written.";
};
...and the PHP:
<?php
$json = $_POST['json'];
$file = fopen('data.json','w+');
fwrite($file, $json);
fclose($file);
?>
The problem I'm having is this: The user can navigate to a separate HTML page, and can click a button to view the data in the json file in a nicely-formated way. This is done via another ajax script that reads the data. This latter ajax script doesn't seem to be able to "see" the newly updated json file. It instead loads the old version of the file, before it was updated with the first ajax script. I'm sure that this second ajax script is run after the above writeData() is finished, because it's actually on a separate HTML page entirely, which is loaded later, after the user clicks a button.
Here's the second ajax script that reads the data from the data.json file (it's on another, separate HTML page):
$.ajax({
type : "GET",
url : "http://eslquiz.net/ell_errors/data.json",
async : true,
dataType : 'json',
success : function(response) {
data = response;
document.getElementById('main').innerHTML = `
<div id='top-stuff'>
<button onClick='viewData()'>Reset Filter</button>
<button onclick="print2()">Print Worksheet</button>
</div>
<br>
<div id='left-column' class='column'></div>
<div id='right-column' class='column'></div>
`;
leftColumn = document.getElementById('left-column');
rightColumn = document.getElementById('right-column');
leftColumn.innerHTML = "<b>Sentences:</b> <br><br>";
rightColumn.innerHTML = "<b>Errors:</b> <br><br>";
//add the sentences and their errorTypes:
for (i=0; i<data.length; i++) {
var senBox = document.createElement('div');
senBox.className = 'box';
senBox.setAttribute('id', 'sen' + i)
senBox.innerHTML += data[i].text;
var errBox = document.createElement('div');
errBox.className = 'box';
errBox.setAttribute('id', 'err' + i)
errBox.innerHTML += data[i].errorType;
leftColumn.appendChild(senBox);
rightColumn.appendChild(errBox);
}
}
});
All of these files are hosted in the same directory on One.com.
The strange thing is that when I manually open the data.json file and edit its contents in any way (by deleting everything, for example), the next time the ajax call is made, it reads the version I just manually updated. This makes me think it might be something to do with the One.com server refreshing itself?
I tried adjusting the ajax between synchronous/asynchronous, and using cache: false, but these don't seem to affect anything.
I've searched around, and can't seem to find out what's going on here. Thanks for any guidance you could provide.
Thanks. I ended up using the following:
jQuery.ajaxSetup({
cache: false
});
I tried using this before, but for some reason it didn't work, not sure why. But it's working now! Thanks.
first, GET method can be cached by the browser.
second, Make sure the response is a json type
$.ajax({
type : "GET",
url : "http://eslquiz.net/ell_errors/data.json?rand_v=" + Matn.random(), // add a random try again
async : true,
dataType : 'json',
success : function(response) {
// Make sure the response is a json type
// console.log(typeof(response));
// console.log(typeof(JSON.parse(response)));
data = response;
// ...
Related
I'm trying to change the value on an input using javascript file called from Ajax, obviously, it's NOT Working :/
I have a page where I have:
<input type="text" id="hello">
$.ajax({
url : 'index.php',
type : 'GET',
data: "value=test",
success : function (result) {
},
error : function () {
}
});
in the index.php, I have:
echo "
<script>
parent.document.getElementById('hello').value = 'Please work';
</script>
";
I even tried "window.parent.docu....", still no luck.
Any way there's a way to do it via the PHP file? Thanks a bunch!!
Please note, I do NOT want to this in the callback because i don't want users to see the handling of all the variables etc etc I want all that info to be done in PHP and then when it's complete fill out the variables on the main page.
This sort of thing trips up a lot of PHP coders. PHP rendering happens on the server. By the time the page has been delivered to the user, it's just HTML and javascript; further attempts to modify the page via PHP will not work; echoing a new line of js will not append it to the document and execute it the way you're expecting it to.
Instead, you need to have your PHP script return the text you want inserted, and use javascript in the rendered page to insert it:
$.ajax({
url : 'index.php',
type : 'GET',
data: "value=test",
success : function (result) {
document.getElementById('hello').value = result;
},
error : function () {
}
});
You really should not proceed with this design. Use callbacks correctly and properly decouple your interface from your backend instead.
However, if you want to cut corners here, you should be able to parse the resultant HTML string (provided its validity), then insert the parsed content into the DOM which should achieve what you seem to want:
$.ajax({
url : 'index.php',
type : 'GET',
data: "value=test",
success : function (result) {
document.appendChild(new DOMParser(result, "text/html").getRootNode().body);
},
error : function () {
}
});
Seeing your comment about not wanting to us JavaScript because users can then see the code, and preferring it in the PHP (server side)... you can skip Ajax altogether and just put something like...
<input type="text" id="hello" value="<?php echo $variableWithData; ?>" />
... into the PHP page, and the HTML the gets sent to the client will just have something like...
<input type="text" id="hello" value="please work" />
I use the following code to select data to show the user without having to move to another page.
<script type="text/javascript">
$(document).ready(function() {
$('#testform input[name=date]').datepicker({
autoHide: true
});
$('#testform').submit(send);
});
function send() {
const data = $(this).serialize();
$('#output').text("FormData: " + data);
$.ajax({
type: "POST",
url: "receiving_file.php",
data,
success: function(data) {
document.getElementById("PrintData").outerHTML = data;
document.getElementById("PrintImg").src = data;
}
});
return false;
}
</script>
To display the output without going to another page, I write in the code:
<p id="PrintData">
The code in the file receiving_file.php looks like this:
<?php
$date = $_POST['date'];
print $date;
?>
The problem is that I want to use JavaScript within the data that comes and it does not work. However, when I try to view the source code in the browser I can't see the data.
Does anyone have an idea how to solve the problem?
Thanks
You need to prevent the default submission behaviour otherwise your form will continue to submit as normal and you won't see the ajax part complete.
function send(e) {
e.preventDefault(); // prevent native submission
// ... rest of your code as before
}
I've amended your example a little to get it working in this jsFiddle. You won't need all these changes but when simulating Ajax requests in jsFiddle you have to POST the html you want to see in the response.
If I understood your question correctly the problem should be that you are trying to modify the outerHTML of an element instead of the innerHTML:
document.getElementById("PrintData").outerHTML = data;
whereas it should be:
document.getElementById("PrintData").innerHTML = data;
The outerHTML modifies the HTML tag itself, not its content.
I have a front-page.php template which lists the 5 latest posts along with some custom post types in between. When one clicks on the more button at the bottom it needs to ajax load more posts.
So I created a loop-home.php file according to this tutorial
I couldn't use this code by default because I have a nested loop on the first load of homepage and this script messes it up.
So I wrote a new query to ajax OLDER posts only. I collected the post ids of the posts already present when the page loads and stored it in an array.
I now need to use this array in the query of loop-home.php
I am using this method because offset does not work with pagination and I need to pass these IDs to post__not_in parameter in the query.
Method 1:
I tried (in loop-home.php)
$exempt = $_REQUEST['exemptArray'];
But it returns NULL.
Method 2:(Using Ajax)
I tried (in front-page.php)-
<script>
var exemptArray = '<?php echo json_encode($exemptions); ?>';
</script>
Then I went to script.js and added-
//create json object from the var array
var jsonArray = JSON.stringify(exemptArray);
var dataToPost = { 'jsonArray':jsonArray };
//send POST data to PHP and handle response
$.ajax({
type: 'POST',
url: loopHome, //stored path in variable. working.
data: dataToPost,
success: function (data) {
console.log('I have already sent it.'); //I am getting this log. Working.
}
});
Then in loop-home.php-
$exempt = json_decode($_POST['jsonArray']);
Still getting NULL on var_dump($exempt)
What am I doing wrong?
Try this
You JS:
$.ajax({
type:'POST',
url:'foo.php',
data:{myArr:exemptArray},
dataType:'JSON',
success:function(result){
console.log(result);
},
error:function(data){
console.log(JSON.stringify(result));
}
});
Your php page:
$input=$_POST['myArr'];
$exempt=json_encode($input);
In your console you will get an array. [object object] is a reference to an associative array.So in the above code result is same as exemptArray.Try something like this you will be able to.I could not find your array composition anywhere so i used exemtarray itself.
So this is the hardest thing I've ever tried to do, I cannot find any answers after 1 day of searching. Note that I am using some custom jQuery API and will explain what it does.
The setup is a php page that contains a jQuery function. That jQuery function calls the API to return a result based on a row I clicked (it is jQgrid, basically looks like an online excel sheet). That works fine, but the objective is to get that result OUT of the jQuery function and store it in a PHP variable. I am just clueless......
Main PHP Page:
$getUnitID = <<<getUnitID //This is the jQuery function. It is stored in a php variable for use in other functions of the API
function(rowid, selected)
{
var selr= null;
if(rowid != null){
selr = jQuery('#grid').jqGrid('getGridParam','selrow'); //This will give ma a number result based on the row I selected. Works fine.
$.ajax({ // I believe I need to use AJAX so here is my attempt
type: "POST",
url: "getId.php", //This is another PHP page for the reuslt. See below
dataType: "json",
data: {selr:selr},
success: function(data) {
alert (data); // This will successfully show me the row number I chose as an alert. But I don't want an alert, I want it stored as a php variable in my main document to use elsewhere.
}
});
}
}
getUnitID; //End of the function
$grid->setGridEvent('onSelectRow',$getUnitID); //Just an event that calls the function upon clicking the row
$rowResult = ??????? //I need this variable to store the result of that AJAX call or that function call
getId.php
<?php
$rId = $_POST["selr"];
echo $rId;
?>
Essentially, I have no idea why I am using AJAX, because my result is still stuck inside the main jQuery function. How in God's name do I get it OUTSIDE that function?!?!?!?!?!?!?! Do I need to $_GET the 'selr' that I POSTed to getId.php ? If so, how?
Thank you, I love you all.
By the time you get that AJAX request sent out and response received, PHP has already gone to sleep. You cant give the data back to your same page's PHP code. Your jQuery starts executing on client computer long after PHP has already finished its work on your server.
It doesn't matter whether your JavaScript function is stored in a PHP variable. PHP will not get its output back. Only way you can do so is to launch another new request to that code and send value to it. but on the same very request on the same very page, its a no no.
Example of how you can send that data to another PHP page
//Your existing jQuery
success: function(data) {
// alert (data);
var result=data;
$.ajax({
type: "POST",
url: "anotherpage.php",
data: { data: result }
});
}
I have a simple problem, how can I delete the ajax request store into the memory. I'll try to explain what I'm will trying to get.
I have a form for edit a table into database.
All runs well the first time, but the problem is after trying again. If I don't refresh the page, it always sent the same data from the first request.
Example:
Into database I have
id
user
password
I have a form with the same parameters, and I called this form with ajax.
I edited a register from the database, and I sent the data edited, and run well, but into the browser memory, the request is stored.
I try to edit again the same register, but when I send again, the data is the same like the first time.
If the first time send:
user : 'userx'
password : 'usex1234'
When I try again to edit this register for example with:
user: 'userxx'
password : 'password1234'
at the end, the data send has these values
user : 'userx'
password : 'usex1234'
How can fix this? I suppose delete the first request, but I can't.
I want to clean the memory from browser without f5 or refreshing, because only with f5, running again well.
I tried:
request = new Request();
request = null; but not happens nothing
delete request; but is the same, nothing changes.
Who can help me please?
MY CODE:
function _update(id){
var n = Number(new Date());
var edit = new Request({
url: 'users/edit?'+new Date().getTime(),
noCache: true,
onRequest: function(){
$('dark').setStyle('display','block');
},
onSuccess: function(data){
$('dark').setStyle('display','none');
box_edit.close();
update();
},
onComplete: function(response){
console.log(response);
},
onFailure: function(){
Sexy.error("Ocurrio un error procesando su solicitud, intente más tarde.");
}
});
var box_edit = new LightFace.Request({
url: 'users/edit?'+new Date().getTime(),
draggable:true,
title: 'Editar usuario.',
request:{
method: 'post',
data: { isc_user_id: id }
},
buttons: [ { title: 'Editar', color:'blue', event: function(){
var id__ = $('isc_user_frm_id_'+id).get('value');
if (before_update(id__)){
if ( $('isc_password_'+id__).get('value')=='' && $('isc_re-password_'+id__).get('value')==''){
var data = 'userEdit=Ok&isc_user='+$('isc_user_'+id__).get('value')+'&isc_group='+$('isc_group_'+id__).getSelected().get('name')+'&isc_user_id='+ id;
}else{
var data = 'userEdit=Ok&isc_user='+$('isc_user_'+id__).get('value')+'&isc_password='+hex_md5($('isc_password_'+id__).get('value'))+'&isc_group='+$('isc_group_'+id__).getSelected().get('name')+'&isc_user_id='+ id;
}
edit.send(data);
}
}
},
{ title:'Cancelar', event:function(){ this.close(); } }]
});
box_edit.open();}
The simplest solution, as your server-side should be stateless, and the variables shouldn't be cached to send to the server, so the problem is probably with how you are getting the values.
The browser may cache when it requests information from the server, which is why it was suggested to turn off caching, but that is for data coming from the server.
So, I would suggest you use the Firebug extension on Firefox and you can put in breakpoints to see if the values are changing.
For every part of setting data you should put these in variables so you can check each value easily.
I didn't create all the variables, but I wanted to show an example to help you.
var val1 = $('isc_user_'+id__).get('value');
var val2 = $('isc_password_'+id__).get('value');
var data = 'userEdit=Ok&isc_user='+$('isc_user_'+id__).get('value')+'&isc_password='+hex_md5($('isc_password_'+id__).get('value'))+'&isc_group='+$('isc_group_'+id__).getSelected().get('name')+'&isc_user_id='+ id;
You will also want to look at the value of id as you may not be appropriately changing that value when the password is changed. I expect this will be your problem.
Append a string like e.g. a timestamp to the requested url, this prevents the browser from using the cached version of the requested ressource.
In mootools there is a noCache-option for Request, set it to true.(default is false, so the cache will be used there without setting the option)
The OP wrote:
FIX
Ok, after tring a lot of ways to fix, I found a solution, which consist of creating a dynamic form. I created a random variable and sent just before to get the form with ajax, after recovery this value into the server code, I put this value like a name of the form and I have a dynamic form. With this I fixed the problem.
Example
function rand(){
return Math.floor(Math.random()*1000);
}
function _update(id){
var form_rand = rand();
...
data: { isc_user_id: id , form_rand : form_rand }
...
To get the value now:
var id__ = $('isc_user_frm_id_'+id+form_rand).get('value');
Into the html I have and hidden input like this:
<input type="hidden" id="isc_user_frm_id_<?php echo $form_rand; ?>" value="<?php echo $r; ?>" ?>