Change value of an INPUT on main page from javascript file - javascript

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" />

Related

Ajax not getting most recent version of JSON file

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;
// ...

Updating webpage with real-time database value using AJAX+PHP response

I’m creating a Javascript game and I’m currently trying to write some code that will show the player’s “Gold Balance” in real time on a html webpage.
The Gold amount is contained in my SQL database, so I’m using setInterval with a Javascript function that contains an AJAX call which calls a PHP script that grabs the current balance amount for the player and sends it back as “response”.
I’m able to have this amount appear as a Javascript alert, however I need to have the response appear as text on the webpage inside a <div> instead.
This is my current code:
<script>
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
alert(response);
}});
};
</script>
I have this in my html source code, I would like to place the function in a separate file and call it from there, but when I tried this I wasn't able to send the response back to the html page correctly.
I was wondering if anyone knows how to have this response appear as text on the page inside <div> </div>?
Also, I was wondering if this method will really update the div in real time (ie, will it auto-refresh the div part of the webpage, showing an up to date value (every 5000 milliseconds)?
Thanks in advance!
Since you are using jQuery, you can use text() to alter the contents of an existing div (which id is "yourDiv"):
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
$('div#yourDiv').text(response);
}
});
};
You have two questions here, so I will try to address both
1) How to append to the DOM using jQuery, instead of an alert:
in the success callback function, instead of alerting the response, you can simply call
$('body').append("<div>"+response+"</div>")
2) "Real time" Gold Balance
You should use websockets. Racthet is a good websocket PHP library to help you with this: http://socketo.me/

Return result to a PHP variable from AJAX in a jQuery function

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 }
});
}

How to pass an argument from javascript to a Servlet through JSP

I'd like to do something like that
function(){
<% ExampleClass sample = new ExampleClass(); %>
var ID = 4;
var something = <%= sample.getSomethingById(ID) %>
}
How can I pass this ID to the jsp expression?
Thanks for any suggestion, and sorry id the question is not so well formulated.
you can also use more advanced methods and tools, like Ajax and JQuery:
function submitToJsp(){
$.ajax({
type: 'POST',
url: 'mypage.jsp',
data: {
id: '123',
comment:$('#comment').val()
},
beforeSend:function(){
// this is where we append usually a loading image
},
success:function(data){
// successful request; do something with the data
$('#output').html(data);
},
error:function(){
// failed request; give feedback to user
}
});
}
In short, by calling the function submitToJsp(); we send an asynchronous (ajax) request to the mypage.jsp jsp with 2 parameters.
use hidden variable and then put the id into that variable.You can not pass using the code above.
<input type="hidden" name="test" value="your id" />
Then you can access like request parameter.
Your javascript code is not executed until after the JSP page has been rendered. So any java variables you want to access in your script needs to be pre-rendered as a javscript variable. After the page has been rendered, you can't execute java code in your javascript. You can't "share" variables between java code and javascript like that. Your example is probably simplified, but in this case, you could just do
var something = <%= sample.getSomethingById(4) %>
You should use hidden field :-
<input type="hidden" name="hdtest" id="idtest" value="<%=sample.getSomethingById(ID) %>" />
Now inside javascript try to access the value.
Try this code in java script :
var something = document.getElementById('idtest').value;
Hope it will help you.

how to use JSON for an error class

Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")

Categories