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.
Related
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;
// ...
I've seen several questions here with the similar subject but I can't find anything which is relevant to my situation. I am trying to build jQuery code that is able to build a list of items to save it in an inventory database and I am using .post() those to a additems.php that will add them to that database (after sensitization), as well as the current path name so the .php can send the user back to the same page.
The behavior I am getting is nothing whatsoever with no console error (except the 'this works' alert when I leave that in.) The behavior I am looking for is, the page should redirect to additems.php as an html form action would, execute the code there and redirect back to this page.
Here is my piece of code:
$(document).ready(function(){
$("#button").click(function(){
alert("this works");
var itemsarray = ['itemname'];
var itemattributesarray = ['itemattribute'];
var quantitiesarray = ['1'];
$.post('additems.php', {
items:{items: itemsarray},
itemattributes:{itemattributes: itemattributesarray},
quantities:{quantities: quantitiesarray},
returnpath: window.pathname
});
});
});
Thank you for your time and any suggestions. I've never used this site so please let me know how I can improve my question as well, if you have the time.
An alternative way is,
$.ajax({
'url':'additems.php',
'method' : 'POST',
'data':{
'items':itemsarray,
'itemattributes':itemattributesarray,
'quantities' : quantitiesarray
},
success: function(data){
//here you will get ajax response
console.log(data);
}
});
So I've got a form that has the action of 'create_topic_parse.php', it sends the input values to that from 'create_topic.php', then they are inserted into the database. I am able to send any errors from the 'create_topic_parse.php' file to the 'message' div in my 'create_topic.php' page using the following code:
$("#submit").click( function() {
// I've tried e.preventDefault(); here ^ but it's giving the same result.
$.post( $("#topic_form").attr("action"),
$("#topic_form :input").serializeArray(),
function(info) {
$("#message").empty();
$("#message").html(info).css('color','#be4343');
});
$("#topic_form").submit( function() {
return false; // Not working
});
});
When the form is CORRECTLY input, and no errors are to be passed from the PHP file, the PHP script is supposed to redirect the user to 'view_topic.php?cid=".$cid."&tid=".$new_topic_id."&page=1'. If I don't include the jQuery above, this works fine.
Problem: If I include the jQuery script, it returns the entire 'view_topic.php/etcetc' page into '', which is bad.
So the question is, does anyone know how to prevent the entire page from being posted into this div, and actually redirect the user to 'view_topic.php' page when the form is correctly submitted?
Note: I've tried window.location, however I've then the issue of the concatonated variables from my PHP file that are input into the 'view_topic.php/etcetc' url. I am trying to get it to work with header('location:...'), like it does when the jQuery file isn't included.
Thanks in advance,
Richie
Solution:
jQuery + Ajax to PHP:
if($('#topic_title').val() == ''){
$('#message').html("You need to give your topic a title.");
}
Using this code I was able to check whether each data entry existed, when all of the data values were existing I'd run the AJAX script within the same file passing each value into a variable like so:
var submit = $('#submit').val();
var topic_title = $('#topic_title').val();
$.ajax({
type: "POST",
url: "create_topic_parse.php",
data: {submit:submit, topic_title:topic_title),
etc etc.
Try this one. It'll work
when form is correctly submitted then only send some string like "correct", and in jquery let you check the ouput string. if it's "correct" then redirect it to view topic via javascript.
if you want to redirect the user to an specific page sent from server, then send from server something like this in json format.
write code on server something like this.
if ($condition==true) {
$ajax_return = array(
'message' => 'correct',
'url' => 'your_redirect_url'
);
}
else
{
$ajax_return = array(
'message' => 'your user defined error message',
'url' => 'leave it blank'
);
}
$ajax_return = json_encode($ajax_return);
echo $ajax_return;
and now jquery on create_topic.php page
$("#topic_form").submit( function(e) {
e.preventDefault();
$.post(
$("#topic_form").attr("action"),
$("#topic_form :input").serializeArray(),
function(info) {
info= JSON.parse(info);
if(info.message="correct"){
window.location=info.url;
}
else{
$("#message").html('');
$("#message").html(info).css('color','#be4343');
}
});
});
I'm sure now it'll work. If not, let me know.
As a novice js and jqplot programmer, I need guidance on passing an array of value from php to an external javascript for plotting (using jqplot). I am confused about the order and how html, php & external js, jqplot is called. A short sample code structure will be very helpful to follow. We may use the following sample codes as guide. Thanks
$(document).ready(function(){
var plot1 = $.jqplot ('chart1',[[3,7,9,1,4,6,8,2,5]],{title: 'Plot'});
});
Instead of the fixed data points above, I want them to dynamically loaded via an array from the following php script.
<?php
$Start_Value = $_POST['Start'];
$End_Value = $_POST['End'];
for($i=$Start_Value;$i<=$End_Value;$i+++)
$Plot_Val[$i] = $i + 2;
json_encode($Plot_Val);
?>
You have several options. Here are the 2 easiest:
Just 'paste' the array from PHP as a JavaScript global variable.
Add <script>var myData = <%= json_encode($Plot_Val); %>;</script> at the top of your page and then use myData in place of the data array.
Even better option is to use Ajax to call the PHP page from JavaScript and get the results , separating front-end and back-end code.
Best way is to use AJAX, something like this in JS:
$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
console.log(response) // check what kind of stuff you got back :)
var values = JSON.parse(response);
// do stuff with this data
}
});
Update: To get your values from a form, you cannot put form action to js, but rather use js to get the values from a form. So the form itself shouldn't do a POST request, but rather the js should take the values from a form and send the POST.
Something like this:
<form>
<input type="text" id="start">
<input type="text" id="end">
<button id="submitButton">Submit Me!</button>
</form>
JS, we will wrap the above AJAX code into a function:
function submitValues(startValue, endValue) {
$.ajax({
type:'POST',
url:'path/to/your.php',
data: {start: startValue, end: endValue}, //passing params to php
success: function (response) {
console.log(response) // check what kind of stuff you got back :)
var values = JSON.parse(response);
// do stuff with this data
}
});
}
$(document).on('click', '#submitButton', function(){
var start = Number($('#start').val());
var end = Number($('#end').val());
//I guess you need numbers instead of text, that's why they are wrapped inside Number()
submitValues(start, end);
});
This should work.
Keep in mind that I have no idea what your form looks like, this is just a dummy example, but it should be similar enough. You get the form values with the jQuery's .val() method and then give those values to the ajax function.
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")