Submit URL via AJAX / PHP set variable without refreshing page, load variable - javascript

I'm having an issue with some script to perform a function via AJAX without refreshing my page. I have a field for a user to enter an external URL, and when they click submit it pops up a modal window, with some information generated through a separate PHP page (images.php currently). I have the script working when the form is actually submitted, the page reloads, and images.php is able to see index.php?url=whatever, but I'm trying to update the page without having to refresh. Do I need to re-render the DIV after defining the variable? I think this may be where I'm having problems.
JS
<script type="text/javascript">
$(function() {
$("#newNote").submit(function() {
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $('#noteUrl).val();
$.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl},
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
HTML
<form id="newNote">
<input type="text" class="form-control" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
PHP (aside from form being submitted to this, this is also included in the modal, which opens, but returns NULL on var_dump($postUrl))
$postUrl = $_REQUEST['noteUrl'];
echo $postUrl;
I could definitely be missing something glaring here, but honestly I've tried every combination of AJAX example I could find on here. Am I missing a huge step about having PHP get the variable? Do I need to refresh a DIV somewhere?
Please help.

Here is a bit neater version of the same code, with the missing quote corrected.
$(function() {
$("#newNote").submit(function() {
$('#notePreview').empty();
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $(this).find('#noteUrl').val();
var request = $.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl}
});
request.done(function(data) {
$('#notePreview').append(data);
});
return false; // avoid to execute the actual submit of the form.
});
});

Add the attribute name="noteUrl" to your input
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
You can also do var_dump($_REQUEST); to see what request variables are being sent.

You might have missed the noteUrl as name. Try giving the name as below and get it using the same name. In your case it is noteUrl
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>

Shouldn't this
var noteUrl = $('#noteUrl).val();
be
var noteUrl = $('#noteUrl').val();
^^^

Related

Issue with AJAX form submit

Required the form to be submitted via an ajax call and you will intercept the result and update your page. You never leave the index page.
I'm having trouble having the ajax call working
<form action="/cart" method="post" id="addProduct">
Quantity: <input type="number" name="quantity">
<button type="submit">Add to Cart</button>
<input type="hidden" name="productid" value="{{id}}">
<input type="hidden" name="update" value="0">
</form>
var form = $('#addProduct');
form.submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/cart",
data: form,
dataType: "json",
success: function(e) {
window.location.href = "/";
}
});
})
you can use
JavaScript
new FormData(document.querySelector('form'))
form-serialize (https://code.google.com/archive/p/form-serialize/)
serialize(document.forms[0]);
jQuery
$("form").serializeArray()
You are changing the whole meaning of the ajax call. Ajax call is used for updating something without page refresh. In your case on success, you are changing the URL which is not right. Remove window.location.href = "/"; from your code and try to append messages or alert something like alert('Product is added to cart');
Your ajax call is not sending data to the server. Use formdata object or serialize() to get form input values then send it to the server.
Use
var form = new FormData($('#addProduct')[0]);
OR
var form = $("'#addProduct").serialize();
Instead of
var form = $('#addProduct');
And on success, send response from server and update your DOM in success function. Don't use window.location.href = "/";
To update your document after success you can use append(e) to update your DOM
<form method="post" id="addProduct">
Quantity: <input type="number" name="quantity">
<button type="submit">Add to Cart</button>
<input type="hidden" name="productid" value="2">
<input type="hidden" name="update" value="0">
</form>
<div id="display">
</div>
$(function(){
$("#addProduct").submit(function(e){
e.preventDefault();
var quantity = $(this).children("input[name=quantity]").val();
var productid = $(this).children("input[name=productid]").val();
var update = $(this).children("input[name=update]").val();
$.ajax({
type:"post",
url:"/cart.php",
data:{update:update,quantity:quantity,productid:productid},
success: function(feedback){
$("#display").html(feedback);
},
error: function(err){
alert("error");
}
});
});
});
I update my answer and i use the div with id display to show my data return from ajax success

Refresh a specific class after post ajax Javascript

So after lot of researchs, I come here to request your help, there is my problem :
I have a comment system with multiple forms on a same page (I use FOSCommentBundle on Symfony). And I want to be able to post comments with Ajax (this part work, no problems) and refresh the comment section after the post is submitted (And i'm stuck on this part).
There is an example of code :
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(){
$(".comments").load(window.location.href + " .comments");
}
});
});
<form method="POST" class="postAjax" action="./comment/post/1">
<input type="textarea" name="comment">
<input type="hidden" name="identifier" value="1">
<input type="submit">
</form>
<div class="comments">
<!-- Comments refreshed after post here -->
</div>
<form method="POST" class="postAjax" action="./comment/post/2">
<input type="textarea" name="comment">
<input type="hidden" name="identifier" value="2">
<input type="submit">
</form>
<div class="comments">
<!-- Comments refreshed after post here -->
</div>
<!-- ... -->
I have tried lot of things, the function ".load" of JQuery but it load all the "comments" class and duplicate the comments in each class.
If someone have a solution... Thank you
First of all, in the provided code, your <form> tag lack an action attribute for your code to work properly.
Then, to answer your question, modify your controller action (the one saving your new comment) so that it return the informations of the submitted comment (json format is better). Then, transform the returned json into html code, and append the result to your comments <div>, for example :
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
var element = $(this);
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(newCommentData){
/* do some process here to transform your newCommentData array into html code */
$(element).next(".comments").append(newCommentData);
}
});
});
Also, if you want it to be cleaner, you could have an hidden 'div', with the same model as a comment div, but with each content replaced by patterns ( ex : %commentTitle%, %commentBody% ). Then each time you post a new comment, you could get that hidden div, and replace patterns with your comment data. That way, if you change comment section structure later, the JS script will still work the same way, without adjustments needed.
Try this
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
var $comment = $(this).next(".comments");
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(){
$comment.append("<div />");
$comment.last("div").load(window.location.href + " .comments");
}
});
});

aJax update a specific row in sqlite and php using a button

I've got a table that lists values inputted by a user, with 2 buttons on the side to remove or to mark completed. On the page the table is visable, there are 3 tabs, we will call these Tab1, Tab2, and Tab3
Each tab has a table (As described above) with information about a specific type of entry.
These buttons are simple <a href> links, so when clicked they reload the page. This is a problem because the users view is refreshed and it takes the tabs back to the default tab, and is also an inconvenience when trying to mark several entries.
I would like to make these buttons send Ajax requests to another page to process the data. The only problem is, I am not really sure how to make the ajax call.
This is what I have right now
My buttons
echo "<td class='td-actions'>";
echo " <a href='?complete=".$row['uniqueID']."' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'> </i>
</a>
<a href='?remove=".$row['uniqueID']."' class='btn btn-danger btn-small'>
<i class='btn-fa fa-only fa fa-remove'> </i>
</a>";
echo "</td>";
There is one called Complete, and one called Remove.
When either of these are pressed, it currently reloads the page which triggers a few php if statements.
if(isSet($_GET['remove'])) {
$sql = "DELETE from rl_logged where uniqueID='".$_GET['remove']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
if(isSet($_GET['complete'])) {
$sql = "UPDATE rl_logged set complete=1 where uniqueID='".$_GET['complete']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
These are relatively simple functions. My problem is that I do not know javascript very well.
Any help would be much appreciated.
the javascript that I have come up with is this
$(document).ready(function() {
$('#markComplete').click(function() {
var input = input = $(this).text()
$.ajax({ // create an AJAX call...
data: {
onionID: input,
},
type: 'POST', // GET or POST from the form
url: 'pages/ajax/markCompleteRL.php', // the file to call from the form
success: function(response) { // on success..
refreshAllTabsWithFade();
}
});
});
});
using this button
<div name='markComplete' id='markComplete' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'></i>".$row['uniqueID']."
</div>
But, while inspecting with firebug, this seemed to work ONCE, but now the button doesn't do anything.
I tried again this morning, the button presses and the first time it sends this post, then the button doesn't do it again - even on page reload.
I was able to get it to work with the following:
javascript:
$('.markComplete').submit( function( event ) {
event.preventDefault();
event.stopImmediatePropagation();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // serialize the form
type: "POST", // GET or POST from the form
url: "pages/ajax/repairlogMarks.php", // the file to call from the form
success: function(response) { // on success..
refreshAllTabs();
}
});
return false;
});
button:
<form class="markComplete">
<input type="text" style="display:none;" class="form-control" name="uniqueid" value='<?=$row['uniqueID'];?>'>
<input type="text" style="display:none;" class="form-control" name="markcomp" value='1'>
<button type="submit" class="btn btn-success">
<i class="btn-fa fa-only fa fa-check"></i>
</button>
</form>
Basically, I made the button into a form which I knew how to create an ajax request for.
--
Update to make it work for multiple buttons that do the same function for different unique ID's.
Well for since you're sending the ajax call using "POST", it seems to me that if(isSet($_GET['complete'])) would evaluate to false. Also if your button is generated dynamically using php then change your click handler to the following:
$('document').on('click', '#markComplete', function (){
// Your code here
})
If you have more than one "Mark Complete" button; you need to use classes rather than ID to bind the event.
<button id="test">
Test 1
</button>
<button id="test">
Test 2
</button>
<script>
$('#test').click(function (e) {
console.log('test', e.target);
});
</script>
In this example, only the first button works. jQuery will only return the first element when you specify an ID.
If you use classes to bind the event; both buttons will work:
<button class="test">
Test 1
</button>
<button class="test">
Test 2
</button>
<script>
$('.test').click(function (e) {
console.log('test', e.target);
});
</script>
i think you have an error in your javascript at this line...
var input = input = $(this).text()
try to replace by this..
var input = $(this).text();

Ajax, just sending value not showing page

I have two files with php and html. This is the basic info inside my A.php file
<div class="col-md-8">
<input type="email" class="form-control" placeholder="Ingresar Número de Nota" id="idnote" name="idnote">
</div>
<button type="button" class="btn btn-primary" id="notes">Enviar</button>
When the user click in the button, it calls a function inside a js.
$(document).ready(function() {
var formData = {
'id' : $('input[name=idnote]').val()
};
$.ajax({
type : 'POST',
url : '../consults/findnote.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//Going to findnote.php and keeping formData
//This findnote.php contains a completely different design but I need the first value to make some changes for the user.
})
});
});
The problem is that after the ajax, my webpage is not going to findnote.php is just sending the value, And I need to show findnote.php
I know if i use
event.preventDefault();
Ajax will prevent the reload, but I'm not using it.
There is a way to do it?
How Do I keep values after making a window.location? (Because if I call the file after the successful call I lose the value)
Should I try with only php? (Its an option)
Why don't do pure HTML ?
<form action="../consults/findnote.php" method="POST">
<div class="col-md-8">
<input type="email" class="form-control" placeholder="Ingresar Número de Nota" id="idnote" name="id">
</div>
<button type="submit" class="btn btn-primary" id="notes">Enviar</button>
</form>
Just added the form tag and edited the name of the input for it complies with your function result.
"The problem is that after the ajax, my webpage is not going to findnote.php is just sending the value"
This is basically what ajax is made for :)
With ajax, you can, if you want, append the result to the current page (you didn't in your code. Just sent datas).
The other solution with form tag, the one above, load the result as a new page, like a classic link.
you need to create a form and pass a function on submit that will run before form submit and redirect
<form action="../consults/findnote.php" method="POST" onsubmit="myfunction()">
<input type="email" class="form-control" placeholder="Ingresar Número de Nota" id="idnote" name="idnote">
</div>
<button type="submit" class="btn btn-primary" id="notes">Enviar</button>
</form>
then in your jquery you can do
function myfunction() {
var formData = {
'id' : $('input[name=idnote]').val()
};
$.ajax({
type : 'POST',
url : '../consults/findnote.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
//Going to findnote.php and keeping formData
//This findnote.php contains a completely different design but I need the first value to make some changes for the user.
})
});
}

onClick and action html

I am using purecss as a base for a simple project. What I am currently having trouble with is I have a submit button where I will pull some info from the fields, and when clicked I want to run some javascript, as well as take the user to another page. This is what I am trying with no luck:
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onClick="saveInfo(this.form)" action="confirm.html">Submit</button>
<button type="submit" class="pure-button pure-button-primary">Search</button>
</div>
Give your buttons IDs for simplicity, and take out that nasty inline JS.
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
And then with your script:
var el = document.getElementById("button1"); //cache the save button
el.addEventListener("click", function() {
document.forms[0].submit(); //submit the form or save it etc
window.location.href = "confirm.html";
}, false); //event handler
Send your form data into the function, and then use a simple redirect since only form elements have action properties. Then just add the click event, save your form however you want (submission, ajax call, doesn't matter), then either in a callback or how it is, redirect the client with window.location.href
You could have a Javascript event handler for a button press which might look something like:
document.getElementById('buttonID').onclick=function(){
//Do whatever processing you need
document.getElementById('formID').submit();
};
Alternatively, you could have an event handler in jQuery which would look something like:
$('#buttonID').on('click',function(){
// Do whatever processing you need
$('#formID').submit();
});
You can make the code inside saveInfo() redirect the user to confirm.html after you're done saving the info.
window.location = "confirm.html"
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
<script>
$(document).ready(function() {
$('#button1').click(function(){
var form = $(this).parents('form');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: form.serialize(),
dataType: 'json',
success: function(response) {
window.location.href = "http://www.page-2.com";
}
});
return false;
});
});
</script>
Your form could as well do without a type submit..
Type can be a mere button.. On click, you could now do all your javascript stuff with onclick="javascript:somefunction()",
somefunction = function (){
Process javascript here
document.formname.submit();
location.href = "new.html"
}

Categories

Resources