Multiple Buttons calling for separate AJAX functions i n1 page - php

When I have many buttons 1 page, how do I identify different buttons that make different AJAX requests? See code/script below (button1 to switch_on.php, button2 to switch_off.php). How do I link the specific button to a specific function within 1 page?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Update MySQL</h2></div>
<button switch-ONid=“1” class="loadButton">Switch ON</button>
<button switch-OFFid=“0” class="loadButton">Switch OFF</button>
</body>
</html>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: "switch_on.php",
success: function(result){
$("#div1").html(result);
}
});
});
});
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: "switch_off.php",
success: function(result){
$("#div1").html(result);
}
});
});
});
</script>

You can simply set id for them :
<button id="btnOn" class="loadButton">Switch ON</button>
<button id="btnOff" class="loadButton">Switch OFF</button>
Your javascript :
<script>
$(document).ready(function(){
$("#btnOn").click(function(){
$.ajax({
url: "switch_on.php",
success: function(result){
$("#div1").html(result);
}
});
});
$("#btnOff").click(function(){
$.ajax({
url: "switch_off.php",
success: function(result){
$("#div1").html(result);
}
});
});
});
</script>

Related

using AJAX I want to show a message after submitting

I want to have a success message in the modal directly below, on the same page without redirecting to a new page.
so I did this but it does not work why?
HTML code
<html>
<head>
<meta charset="UTF-8">
<title>essai</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form form id="form1">
donnee1:<input type="text" name="donnee1"/>
<input type="submit" vatue="envoyer">
</form>
The result of the success message rendered inside this div
<div id="result"></div>
<script>
$(document).ready(function() {
$("#form1").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
var ajaxRequest= $.ajax({
url: "php.php",
type: "post",
data: values
});
ajaxRequest.done(function (response, textStatus, jqXHR){
$("#result").html('Submitted successfully');
});
ajaxRequest.fail(function (){
$("#result").html('There is error while submit');
});
});
</script>

AJAX - form submit, same page, PHP

EDIT: I have changed the AJAX code to what I am now using and I have also included JQuery in my code
I've read up on as much AJAX as I can and I am flat out failing!
My HTML form looks like this:
<form action="match_details.php" method="post" id="match_details">
....
<button type="submit" form="match_details" name="match_details" class="w3-button w3-block w3-mam w3-section" title="Update Match Postcode">Update</button>
</form>
From Stack I've managed to get this AJAX:
<script type="text/javascript">
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "match_details.php",
data: $("#match_details").serialize(),
beforeSend: function(){
$('#result');
},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
I've tried changing it from button to input and back again but nothing seems to change. The form still submits but it ignores the AJAX and the page refreshes.
You need to prevent the JS from submitting the form, and you're using the wrong form ID. Also, judging by the comments, you need to include jquery.
In the head of your HTML file, between <head> and </head> or just before the closing </body> tag, you can use the following:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
The following code may help you (though it's advised to not query the same page as your ajax request emits from):
<script type="text/javascript">
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "match_details.php",
data: $("#match_details").serialize(),
beforeSend: function(){
$('#result');
},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>

How to check id of button clicked in php

I have 2 buttons "removeD" and "updateRecord"(by id) and I have written same ajax for them as follows:
$.ajax({
url: 'DB/tableDisplay.php',
type: 'POST',
data: 'id='+uid,
dataType: 'html'
})
But in tableDisplay.php I want to have different functionality for both the buttons.How to check the id of the button clicked in php?
I've tried using :
if(isset($_POST['removeD'])){
}else{
}
But this is not working.
Try this:
$(document).ready(function(){
$('button').click(function(){
var id = $(this).attr('id');
$.ajax({
url: 'DB/tableDisplay.php',
type: 'POST',
data: {id: id},
dataType: 'html'
})
});
});
$('body').on('click','#id1',function(){
$.ajax({
url : 'url',
data : {variable:values},
type : 'html',
dataType : 'GET/POST',
success : function(data){
console.log('Message after Success');
},
error : function(){
console.log('Error Message')
}
});
});
In your url page you can find whether ajax request is posted or not
if(isset($_REQUEST['variable'])){
write your php code here........
}
Try the following code to detect the button clicked:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('.click-button').on('click',function () {
var button_id = $(this).attr('id');
if(button_id == 'removeD'){
alert('removeD button clicked');
}else if(button_id == 'updateRecord'){
alert('updateRecord button clicked');
}
});
});
</script>
</head>
<input type="button" class="click-button" id="removeD" value="removeD">
<input type="button" class="click-button" id="updateRecord" value="updateRecord">
You can use target it return which DOM element triggered the event. see below code its too easy and short to get id of clicked element.
$('button').click(function(e){
alert(e.target.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="remove">Remove</button><br>
<button id="update">Update</button><br>

How can I use jQuery´s $.ajax() function to run php script? [duplicate]

This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 7 years ago.
To make this understandable I made an sample code because my actual code is much bigger.
Basically what I want to accomplish is to run my PHP script that edits an XML file using ajax. This is because I need to do this inside a javascript in my real project.
This is what I have so far:
the .php file containing the ajax function:
<!DOCTYPE html>
<html>
<head>
<script>
function editXMLDoc()
{
$.ajax({
url: "sensors.php",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
});
}
</script>
</head>
<body>
<button type="button" onclick="editXMLDoc()">Endre XML</button>
</body>
</html>
And here is the php script writing to xml:
<?php
include 'sensor.php';
$b=new sensor();
$arr=$b->load('sensor.xml');
for($i=0,$ms=count($arr);$i<$ms;$i++)
{
if($arr[$i]['fields']['status']=='1')
{
$arr[$i]['fields']['status']='0';
}else{
$arr[$i]['fields']['status']='1';
}
}
echo "Completed<br/>";
//3. save array to xml
$b->save('sensor.xml',$arr);
?>
I know the script is working so I am pretty sure the prob is the connection between the ajax function and the php script.
Can anyone help me out?
Try this code... actually you did not attached jQuery library.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
var resp = $("#response");
$.ajax({
type: "POST", // Method type GET/POST
url: "sensors.php", //Ajax Action url
data: {},
// Before call ajax you can do activity like please wait message
beforeSend: function(xhr){
resp.html("Please wait...");
},
//Will call if method not exists or any error inside php file
error: function(qXHR, textStatus, errorThrow){
resp.html("There are an error");
},
success: function(data, textStatus, jqXHR){
resp.html(data);
}
});
});
</script>
</head>
<body>
<div id="response"></div>
</body>
</html>
Use AJAX like this:
<script type="text/javascript">
jQuery(document).ready(function($){
$('.rt11').click(function(){
$.ajax({
type: "POST", // Method type GET/POST
url: "sensors.php", //Ajax Action url
data: {yourKey: "yourValue", yourKey1: "another value"},
// Before call ajax you can do activity like please wait message
beforeSend: function(xhr){
console.log("Please wait...");
},
//Will call if method not exists or any error inside php file
error: function(qXHR, textStatus, errorThrow){
console.log("There are an error");
},
success: function(data, textStatus, jqXHR){
console.log(data);
}
});
});
});
</script>
I think there is no problem in code but sometime in large code the min.js file did not include properly. please try the below code. there is no need to change sensors.php file.
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
$('.rt11').click(function(){
$.ajax({
url: "sensors.php",
context: document.body
}).done(function(html) {
$( this ).addClass( "done" );
});
});
});
</script>
</head>
<body>
<button type="button" class="rt11">Endre XML</button>
</body>
</html>
HTML:
<button type="button" id="idButton">Endre XML</button>
JS:
$("#idButton").click(function(){
$.ajax({
url: 'sensors.php',
dataType: "xml", //if it returns a xml file
success: function (data) {
// everything is ok
alert(data)
},
error: function (xhr, status, error) {
// Something went wrong
if (xhr.status > 0) alert('Error: ' + status);
}
});
})
Try this i think you missed to include the jQuery library file.Get post data to your php file after ajax call.
<!DOCTYPE html>
<html>
<head>
//include the jQuery library file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function editXMLDoc()
{
var myvalue='123';
$.ajax({
url: "sensors.php",
context: document.body,
data: {myvalue:myvalue},
}).done(function() {
$( this ).addClass( "done" );
});
}
</script>
</head>
<body>
<button type="button" onclick="editXMLDoc()">Endre XML</button>
</body>
</html>

jquery, get data via ajax then submit form

I'm trying to get data via ajax then send it through a form. However it doesn't seem to be working. Any ideas what im doing wrong?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<form method="get" action="test.php">
<input id="myvar" type="hidden" name="albumid" />
<button type="submit" id="btnsubmit">Submit</button>
</form>
<script type="text/javascript">
$('form').submit(function() {
$.ajax({
url: "newAlbum.php",
success: function(data){
var album = data;
$('#myvar').val(album);
}
});
});
</script>
newAlbum.php
<?PHP echo '11'; ?>
test.php
<?php echo $_GET["albumid"]; ?>
Okay try adding as follows:
$('form').submit(function() {
$.ajax({
url: "newAlbum.php",
async:false,
success: function(data){
var album = data;
$('#myvar').val(album);
}
});
});
As someone else pointed out - you need to add the data parameter. But I would also use $(this).serialize(), since that will fetch all form input elements.
<script type="text/javascript">
$('form').submit(function() {
$.ajax({
url: "newAlbum.php",
data: $(this).serialize(),
success: function(data){
var album = data;
$('#myvar').val(album);
},
error : function(data) {
console.log(data);
}
});
});
</script>
Try receiving the data as JSON
$.getJSON()

Categories