EDIT: The question has more to do with altering the variable (valueA) than anything. I am already getting the desired load result using the script below. I am trying to attach something to the script that will ultimately alter valueA once clicked.
I am designing multiple pages that will load into a main content div on click using .load
index.php
//Setting default value
$valueA = 5;
//Created separate div to allow me to monitor the variable and changes
<div><?php echo $valueA; ?></div>
//Loading first page into div
<div id=main_content>
<?php include 'page1.php'; ?>
</div>
Included in page1.php is a button that will load the page assigned to it.
page1.php
<button id="button1">Click Me!</button>
<script>
$(document).ready(function(){
$('#button1').click(function(){
$('#main_content').load('page2.php').hide().fadeIn('slow');
$.ajax({
type: 'POST',
url: 'index.php',
success: $valueA += 5,
});
});
})
Upon clicking, page2.php will load, but the value will remain 5. I am trying to figure out how to add the 5 using the ajax script to the valueA. Ultimately, the new page would load, and the value would increase to 10.
The incrementing of your php variable has to be done in a php script, not javascript. Javascript inherently knows nothing about your php, and vis-versa.
The other thing to mention is that the success property on the $.ajax object is a function, so you should define it as such. See jQuery Documentation for full details on $.ajax
$.ajax({
...
...
success: function () { ... }
});
Edit
After clarification, here is an updated, more thorough example.
HTML
<div id="valueAContainer"><?php echo $valueA; ?></div>
jQuery
$.ajax({
url: "yourphpscript.php",
method: "GET" (or post, whatever is applicable),
data: { valueA: $("#valueAContainer").text() },
success: function (data) {
$("#valueAContainer").text(data);
}
});
PHP
// get valueA variable from request
$oldValue = $_GET['valueA'];
// Do whatever you want to it - increment, save to DB, etc.
$updatedValue = $oldValue + 5;
// Return updatedValue to javascript
echo $updatedValue
Related
I have a page where there's a table with a button and when I click the button I store the value in a JS variable in order to send it to another page using post.
I get the values on the other page but after that the page does not load.
this is the button code to send the variable:
<script>
function ObtenerDatosFila(oButton)
{
var dgvVerGrupos = document.getElementById('dtBasicExample');
$.ajax({
url: 'FormularioAMGrupo.php',
type: 'post',
data:
{
Modificar:'Modificar',
IDGrupo:dgvVerGrupos.rows[oButton.parentNode.parentNode.rowIndex].cells[0].innerHTML,
},
dataType: 'json',
success:function(){}
});
return false;
}
</script>
</script>
Is there another easier a way to do this other than using post method?
You could make a one page site, no need to send the data around.
You'll have to change your structure a bit and change your ajax functions to a generic 'ShowPage(id)' function to achieve this.
If you are interested and need any help just say so.
button's page:
<script>
function ObtenerDatosFila(oButton)
{
var dgvVerGrupos = document.getElementById('dtBasicExample');
localStorage.setItem("CodigoGrupo",dgvVerGrupos.rows[oButton.parentNode.parentNode.rowIndex].cells[0].innerHTML);
localStorage.setItem("Modificar",'Modificar');
location.href ="FormularioAMGrupo.php";
}
</script>
2nd page:
<script type="text/javascript">
window.onload = alert(localStorage.getItem("CodigoGrupo"));
</script>
I have a page that pulls order statuses from a backend system and then shows the status updates on the page. I need to make the page dynamic to load, since now the page takes too long to update at once.
I got my code working so that the HTML page loads up first and then a single status update is loaded on the page.
Components:
index.php -page - basic page w. jQuery code that requests orders_updatestatus.php.
orders_updatestatus.php -page. Pulls info from a backend system and displays info. Receives what order to update via GET.
HTML (index.php - this works)
<div id="updateref"></div>
jQuery: (part of index.php - this works)
<script type="text/javascript">
// Update order status
$(function () {
$.ajax({
url: 'orders_updatestatus.php?reference=100000025',
success: function (data) {
$('#updateref').html(data);
}
});
});
</script>
UPDATED CODE
What I was thinking was that that I need to create a div for every single order so that they could then be updated individually.
$results = $mysqli->query("SELECT reference FROM orders;");
while($row = $results->fetch_assoc()) {
print '<div id="updateref'.$row['reference'].'"></div>';
}
So, with the code above I'll something like this:
<div id="updateref20000"></div>
<div id="updateref20001"></div>
<div id="updateref20002"></div>
<div id="updateref20003"></div>
<div id="updateref20004"></div>
etc..
Everything works great until this point. Now I need your help on building the corresponding jQuery code so that it would update every 'updaterefXX' -div that it sees.
My question is: How to update the following code so that it every updateref -div is updated on the page:
<script type="text/javascript">
// Update order status
$(function () {
$.ajax({
url: 'orders_updatestatus.php?reference=100000025',
success: function (data) {
$('#updateref').html(data);
}
});
});
</script>
Update/clarification: What I need is for the script to pull the orders_updatestatus.php with a GET variable for every div.
Example:
With <div id="updateref1000"> the script requests orders_updatestatus.php?reference=1000 and displays it in <div id="updateref1000"> when ready
With <div id="updateref1001"> the script requests orders_updatestatus.php?reference=1001 and displays it in <div id="updateref1001"> when ready
etc. Thank you!
You can use attribute begins with selector and .each() to iterate all elements having id beginning with "updateref", .replace() to replace portion of id that are not digits to set at query string, set .innerHTML the current element within success callback of $.ajax() call
$("[id^=updateref]").each(function(index, element) {
$.ajax({
url: "orders_updatestatus.php?reference=" + element.id.replace(/\D/g, ""),
success: function(data) {
element.innerHTML = data;
}
});
})
To give you the most basic view of my question, I'm trying to create a page that is very similar to how facebook and twitter's dashboards and comment systems work. You have one page that will continuously create form elements (posts) from database rows in a loop as the user scrolls down. Users will then be able to comment on each of these posts. I want to be able to use ajax to submit comments on each post individually without reloading the page.
I run into a problem where when I try to submit a comment on any form other than the first one that is loaded on the page. In addition the ajax only posts the first form elements on submit (due to each form and elements having the same name I'm guessing).
Below is my comment loading script: [forgive the old php, I know I need to update it to mysqli or PDO]
php
<?php ...
$query = mysql_query("SELECT * FROM `posts`");
while ($row = mysql_fetch_array($query)) {
echo "
<div name='comment_body'>
<form name='comment_form'>
<td>User: ".$row['user']."</td>
<td>Post: ".$row['post']."</td>
<textarea name='comment'></textarea>
<p name='post_id' style='display:none;'>".$row['post_id']."</p>
<input type='submit' name='submit'>
</form>
";
$query2 = mysql_query("SELECT * FROM `comments` WHERE `post_id` = $row['post_id']");
while ($row2 = mysql_fetch_array($query2)) {
echo "
<td>User: ".$row2['user']."</td>
<td>Comment: ".$row2['comment']."</td>
</div>
";
}
... ?>
jscript
<script>
$('.comment_form').on('submit', function (e) {
e.preventDefault();
$.ajax ({
type: 'post',
url: 'submit_comment.php',
data: {comment : $('#comment').val(), post_id : $('#post_id').text()}
success: function() {
$("#comment_body").load("load_comments.php #comment_body");
}
});
});
</script>
The script works to a point because when I comment on the first post, it works as expected. I just can't seem to figure out how to target the forms further down the page individually. Here's an example:
The very top post has a post_id value of 40. If I comment on post_id = 38, ajax will submit the empty comment field and post_id = 40 into the database.
Any help with the script form targeting would be great. If I need to rebuild my php query to give each echoed form element an individual name, that's fine as well. Thanks in advance!
The data you're trying to send to in the ajax call is using:
$('#comment').val(), post_id : $('#post_id').text()
But your HTML doesn't have anything with an ID="comment" and ID="post_id". (the '#' in your selector means getElementById.) So you aren't sending any data to your php page. You need to use the correct selectors to get that data. (see below)
Get rid of the 'form' tags you don't need them. Change your
<input type="submit">
to a:
<input type="button" class="comment-submit">
Then your script can be:
<script>
$('.comment-submit').on('click', function (e) {
e.preventDefault();
// get a referenct to this particular comment_body div
var $commentbody = $(this).closest('.comment_body');
// find the textarea within this particular comment_body
var commenttext = $commentbody.find('textarea[name="comment"]').val();
// find the post_id paragraph within this particular comment_body
var postId = $commentbody.find('p[name="post_id"]').text();
$.ajax ({
type: 'post',
url: 'submit_comment.php',
data: {comment : commenttext , post_id : postId}
success: function() {
$comment_body.load("load_comments.php #comment_body");
}
});
});
</script>
Frankly I'm not sure what your success function is trying to do. But I think you need to work on it too. Normally an ajax call will return data so your success function should have a return value and that would be used to populate some part of your screen. The jQuery 'load()' function is another ajax call inside the success callback of an ajax call. I really don't think you want or need to do this.
You cannot select a unique form by class because your class is identical across all forms. Add an "id" field to the form element like this:
"<form name='comment_form' id='"+ .$row['id'] +"'>"
Then select a given form using that unique ID, and add your event handler. This must be in the same scope as you define your form. Like this:
$('#'+ .$row["id"]).on('submit', function (e) {
//Handle the event
})
What am I trying to accomplish is to display a text message on a web page after I click a text. The new text should replace the text that I clicked. The new text should be the value of the id attribute. The hyperlink is meant to go away after the first click (and become unclickable).
Here is one of my attempts:
Apasa textul 1
<script type="text/javascript">
$("#id").on('click', function() {
document.getElementById("Ana").innerHTML = "<span> Ana </span>";
});
</script>
The tag that should be used to replace the <a> tag is <span>.
I expect to display Ana after I click Apasa textul 1
Any help will be appreciated, thanks.
There will be quite a few different ways to do this, but if you want to employ an inline function call, you could declare a custom function called swapTag() (or whatever you like) which will generate a new <span> tag, then fill it with the original tags id value, then replace the original dom element with the newly generated element.
function swapTag(el) {
let newEl = document.createElement('span');
newEl.innerHTML = el.id;
el.parentNode.replaceChild(newEl, el);
}
Apasa texul 1
Although you have stated that you wish to replace the <a> tag with a <span> tag, if you want to replace the <a> with pure text, this will work too:
Apasa texul 1
There isn't a great deal of context to the question, so I don't know how much utility your project actually requires. Inline function calls may be an ugly choice -- using a listener may be a cleaner way.
I'll add an alternative that will use Jquery and an event listener (so that you you aren't muddying up your dom with inline function calls ...again, it is hard to give you a "perfect" answer because we don't know much about your application).
$(document).ready(function() {
$('a[href="#"][id]').click(function(){
let oldEl = this,
newEl = document.createElement('span');
newEl.innerHTML = oldEl.id;
oldEl.parentNode.replaceChild(newEl, oldEl);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Apasa texul 1
Apasa texul 1
Apasa texul 1
And again, if you want to just swap the <a> tag for text, this is the jquery-listener version (listening for the click of an <a> tag with an href value of # and an id attribute containing anything):
$(document).ready(function() {
$('a[href="#"][id]').click(function(){
this.outerHTML = this.id;
});
});
On you PHP you must do this (put this code in the top of the page):
<?php
if(isset($_POST['name']))
{
echo $_POST['name'];
exit;
}
?>
On JS:
$('#Ana').click(function()
{
var name = $(this).attr('id');
$.ajax(
{
type: "POST",
url: "index.php",
cache: false,
data: {'name':name},
dataType: 'text',
success:function(result)
{
alert(result);
}
}
)
});
The alert will show you the echoed value by PHP. From there do as you please... something like $('p').html(result);
Because you are doing an ajax call, you cannot rely on that inline code you wrote, since the page is not being entirely refreshed. That code executes when you first load the page, but because when that happens you are not passing parameters via POST (normally) in the initial statements "else" is always executed.
When calling ajax if you do not perform "exit;" in my code above, you would receive the entire page in the result. That's why the code must be at the top of the page, and an exit must be called after.
You don't need all those stuff.
If i understand the whole, you want, when the link is clicked, to:
perform an AJAX call
replace the whole link by its ID property, no matter the call does
Apasa texul 1
is the fastest way, considering your AJAX call would be in performAjaxCall() .
Apasa texul 1
<p><?php if(isset($_POST['name']))echo $_POST['name'];else echo 'rusu';?></p> /** 2nd line **/
The 2nd line isn't meant to be executed after an AJAX request, it only gets executed when the entire page is requested normally.
To have the wanted results you may :
In the JavaScript part, when attaching the click handler you'll need to prevent the default behavior of the a element (redirects to wathever the href attribute is, if it's # the page gets scrolled to the top in most cases). Also, to distinguish that the request is an AJAx request you may use a POST variable, set to 1 for example, to check it in the server side.
In the PHP part, check if the $_POST['isajax'] (the variable that should tell us we have an AJAX request) and $_POST['name'] are set and $_POST['isajax'] equals 1 then echo the $_POST['name'] and halt the script. Also, these checks are likely to be the put in the top of the PHP file.
The JavaScript part may look like :
$('#Ana').click(function(e) {
e.preventDefault(); /** prevents the link's default behavior **/
var name = $(this).attr('id');
$.ajax({
type: "POST",
url: "index.php",
data: {
isajax: 1, /** means we have an ajax request, it's not that **/
name: name
},
success: function(response) {
alert(response)
}
})
});
and the PHP part (top of index.php page) ould look like :
if(isset($_POST['isajax'], $_POST['name']) && $_POST['isajax'] == 1) {
echo $_POST['name'];
exit; /** no further lines are executed **/
}
I have a php page which includes jQuery and a script.js file. When I put the following function inside my php file, the function gets executed and works as intended:
<script>
$('#scoreboard-overview').load('getusers.php?q=<?php echo $NewString; ?>').fadeIn("slow");
</script>
What does it do? Wel it reloads the div with id scoreboard-overview in my php file with data from an external php file called getusers.php
This all works great.
Now in the script.js file (which is loaded at the end of the php page, right before </body>), I also want to reload this div when the updatescore.php file is done updating the database via a form. I have this code for it:
$.ajax({
type: "POST",
data: $("#form").serialize(),
cache: false,
url: "updatescore.php",
success: function() { //reload overview
$('#scoreboard-overview').load('getusers.php?q=' + document.getElementById('str') + '').fadeIn("slow");
}
});
So after success it should execute the jQuery function:
function () { //reload overview
$('#scoreboard-overview').load('getusers.php?q='+document.getElementById('str')+'').fadeIn("slow");
}
I verified the code. The database gets updated using updatescore.php but after this (so after success), the div isn't refreshed. So this success part of code isn't working. What am I doing wrong?
ps: '+document.getElementById('str')+' should give me the same result as echo $NewString; only taken from the div with id str (since php doesn't work inside a js file?)
document.getElementById('str') is going to return the HTML element with the 'str' id, not the text within the element. I'm not sure what this element actually looks like, but you might do something like document.getElementById('str').textContent.