In my page i want to send a jQuery request to another PHP script, without reloading the whole page.
When clicking a button, the request needs to be sent to another PHP script, through POST.
I just can't get it to work. My code so far:
Javascript:
<script>
$(function(){
$('#pause').on('click', function(e){
e.preventDefault(); // preventing default click action
$.ajax({
url: '/cura/includes/pause_agent.inc.php',
type: 'post',
data: $pausedata,
success: function(){
// ajax callback
}, error: function(){
alert('ajax failed');
},
})
})
})
</script>
PHP code of button & URL to be sent:
if($member['Paused']==0){
$pausedata = '?action=agentpause&agent='.$member['Location'].'&paused=true';
echo('<td><button id="pause" class="btn btn-warning btn-sm">Pause      </button></td>');
}
else{
$pausedata = '?action=agentpause&agent='.$member['Location'].'&paused=false';
echo('<td><button id="pause" class="btn btn-success btn-sm">Unpause</button></td>');
}
Any suggestions/ideas?
There are a couple of things to note here, first of all you need to make sure your document is ready before doing your jQuery, to do this you can either put your script at the bottom of the page or put all of your script inside a
$(document).ready(function(e) {}
event.
To post data there is a shortcut which is
$.post("path/to/php/script.php",
{postVariableOne:valueOne, postVariableTwo:valueTwo,...},
function(data){
//callback function
});
Note valueOne and valueTwo are javascript variables
Then, in the PHP script, you would access the sent data like this
$_POST['postVariableOne'];//this equals valueOne
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>
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
I am trying to run a PHP script as soon as Submit button is clicked. I wanted to do an AJAX call as i dint want to refresh the page after the button is clicked. But the below code is not responding upon click.
I have saved the login.php in the same location as my project. Any help or input is appreciated!
<input type="button" class="button" value="submit" />
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$.ajax({
type: "GET",
url: "C:\wamp\www\ElitePass\login.php"
})
alert("done successully")
});
});
</script>
The issue is that you are not targeting your button correctly.
$("button") this selector is looking for an element of type "button". Naturally there is none. To target elements by their class names, append dot to selector:
$(".button").click(....)
Having said that, your code will still not work as you expect it to. Browser security restrictions will prevent loading of files directly from your file system. You need to load stuff via web server. Especially PHP files.
You can call success like :
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$.ajax({
type: "GET",
url: "C:\wamp\www\ElitePass\login.php",
success: function() {
alert("done successully");
}
})
});
});
</script>
I have a jquery tab set:
<div id="tabs">
<ul>
<li>Mileage Log</li>
<li>Trips</li>
</ul>
<div id="tabs-1">something</div>
<div-id="tabs-2">something</div>
</div>
My content on my tabs fires some javascript code that posts form data (I included that code). The problem is that I would like the tab element to refresh so any new content can be shown. Is there a built-in way to refresh the tabs using the "success:" option. I am currently using "location.reload();" but it just refreshes the whole page. Not ideal.
Thanks.
My Javascript
<script>
$(document).ready(function () {
//Submit form to add record.
$('#addmileage').submit(function (e)
{
e.preventDefault();
$.ajax({
data: $('#addmileage').serialize(),
type:'POST',
url:'actionpages/add_trip.cfm?ticketid=<cfoutput>#url.ticketid#</cfoutput>',
success: function(){
$('.success').fadeIn(200).show();
location.reload();
$('.error').fadeOut(200).hide();
}
});
});
$('.deleteMileageForm').submit(function (e)
{
e.preventDefault();
$.ajax({
data: $(this).serialize(), // **** modified this line ****
type:'POST',
url:'actionpages/delete_trip.cfm',
success: function () {
$('.successTab2').fadeIn(200).show();
location.reload();
$('.errorTab2', $row).fadeOut(200).hide();
}
});
});
});
</script>
The only way I think you could achieve this, is to have the server-side functions you're calling in AJAX, return a block of HTML which you could inject into the of the tab you want to reload. And if you're going to do that, you'll need to put the functions in a CFC instead of the CFM page you're calling now.
So, you would generate the way you're doing now to build the initial page, but save the generated HTML as a string and then return it to the jQuery AJAX call.
As just a really bare-bones example:
$('.deleteMileageForm').submit(function (e)
{
e.preventDefault();
$.ajax({
data: $(this).serialize(), // **** modified this line ****
type:'post',
dataType: 'json',
url:'actionpages/actions.cfc?method=deleteTrip&returnformat=json',
success: function (result) {
$('.successTab2').fadeIn(200).show();
$('.errorTab2', $row).fadeOut(200).hide();
$('#tab2').html(result);
}
});
Then on the server you'll need an actions.cfc with remotely accessible functions:
<component>
<cffunction name="deleteTrip" access="remote">
<cfset newHTML = "<h1>This is new HTML!</h1>">
<cfreturn newHTML>
</cffunction>
</component>
I've put everything into JSON format, just because I always use JSON. :)
Not sure how familiar you are with CFCs, returnformats, etc. But hopefully this is a push in the right direction.
You need to refresh the tabs in the success function using DOM Manipulation. It may be the case, that your scripts like actionpages/delete_trip.cfm have to return new information which you need to refresh the tabs (for example in the JSON format).
Some notes:
The function location.reload(); may reload the page from the browser cache. Use location.reload(true); if you do not want this behavior.
$('.successTab2').fadeIn(200) should be enough (.show() is not needed). You also do not need the .hide() function.
I'm a bit new to JavaScript and I have a really silly question: How can I call a function I have in a Coffeescript file from HTML?
I want the users to be able to select the language they see my site, but don't want my html to be reloaded for that.
I am using i18next to make the translations and now what I need is to add some buttons to select the language.
The function will reload just a section of the page is in my coffee file.
So, how can I call this function from my html file?
PS: If you can show me some examples it'll be great!
Simply use these code with jquery :)
var data = {
'value': $("#myb option:selected").val(),
'link': 'kapil'
}
$.post("your_file",data, function(response) {
alert(response);
});
If your HTML code contains have button like
<button type="button" name="submit" id="submit" onclick="change();" >Submit</button>
Write a script to send ajax request:
function change(){
$.ajax({
url:"add url here",
type:"POST",
data:{"dataval":add} //add is a variable that contains value,
success:function(response){
alert(response);
},
error:function(r,e,s){ }
});
}
You can create html(for response) in success function and replace contents of div by response