how to pass data to php using ajax? - php

I want to display a message according to the className passed to server using AJAX . I'm new ajax , I have no idea about that..
myhtml code :
<div class="header">
<h2>Configuration</h2>
<p> Enable: </p> <i class="fas fa-toggle-off " id="enable-btn"></i>
<span id="demo">Dashboard Enabled</span>
</div>
myJS code :
function enableButtonClicked() {
$(document).ready(function () {
$('#enable-btn').click(function () {
$( ".dashboard, #demo" ).toggle();
$(this).toggleClass("fa-toggle-off fa-toggle-on");
});
});
}
ajax code :
function displayMessageAccordingToButtonState() {
var x = document.getElementById('enable-btn').className;
if( x == 'fas fa-toggle-off'){
var msg = "Button Disabled"
$('.header').load('request.php',{"displayMsg":msg});
}
else {
var msg = "Button Enabled"
$('.header').load('request.php',{"displayMsg":msg});
}
}
php code :
<?php
if( $_REQUEST["displayMsg"] ){
$msg = $_REQUEST['displayMsg'];
echo "".$msg ;
}
?>

this is working demo
just copy and try
i have added extra span and ajax file content is copy to that content
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="header">
<h2>Configuration</h2>
<p> Enable: </p> <i class="fas fa-toggle-off " id="enable-btn"></i>
<span id="demo">Dashboard Enabled</span>
</div>
<span id="demo2"></span>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<script>
$(document).ready(function () {
$('#enable-btn').click(function () {
$( ".dashboard, #demo" ).toggle();
$(this).toggleClass("fa-toggle-off fa-toggle-on");
});
});
$('#enable-btn').click(function () {
var x = document.getElementById('enable-btn').className;
if( x == 'fas fa-toggle-off'){
var msg = "Button Disabled"
$('#demo2').load('request.php',{"displayMsg":msg},function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
console.log("External content loaded successfully!"+responseTxt);
if(statusTxt == "error")
console.log("Error: " + xhr.status + ": " + xhr.statusText);
});
}
else {
var msg = "Button Enabled"
$('#demo2').load('request.php',{"displayMsg":msg},function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
console.log("External content loaded successfully!"+responseTxt);
if(statusTxt == "error")
console.log("Error: " + xhr.status + ": " + xhr.statusText);
});
}
});
</script>
</html>
this is my php file
if( $_REQUEST["displayMsg"] ){
$msg = $_REQUEST['displayMsg'];
echo "".$msg ;
}

in JS
var request = $.ajax({
async: false,
url: 'Php.file', / your php file path
type: "POST",
data: "Value1=your value";
datatype: 'html',
});
request.done(function(data) {
//data you will handle from php file
});
in PHP receive
$data = $_POST['data'];
//you can check like this
if(empty($data))
{
echo("none received");
}
else{
echo 'passed parameter '+$data;
//in here you will receive as data in js file
you will receive in data in js as 'passed parameter+ your value'
}

First of all is to create an HTML file with jQuery included.
Let's say you have a hidden input field.
<input type="hidden" id="mydata" value="sampledata">
You can now get the data from the hidden field using the script $("#mydata").val();
You can now write the ajax code as follows
$.ajax({
type: 'post',
url: '/path/to/ajax.php',
data: {
postvariable: $("#mydata").val()
},
success: function() {
alert('success');
}
});
In your ajax.php file, you can now receive the value as $_POST['postvariable']
You can now declare
$myphpvar = $_POST['postvariable'];
Where
echo $myphpvar; //will print 'sampledata' without quotes
To summarize, it is simply like submitting a form with the having the method post. Except when using ajax it does not require the page to reload.
You may read more about this in my tutorial:
https://www.davidangulo.xyz/website-development/how-to-pass-value-from-javascript-to-php/

Related

Ajax html input value appears empty

I am trying to submit a form via ajax post to php but the value of the input tag appears to empty.
I have cross-checked defined class and id and it seems ok. I don't where my mistake is coming from. Here is the code
index.html
<div class="modal">
<div class="first">
<p>Get notified when we go <br><span class="live">LIVE!</span></p>
<input type="text" class="input" id="phone" placeholder="Enter your email adress" />
<div class="arrow">
<div class="error" style="color:red"></div>
<div class="validator"></div>
</div>
<div class="send">
<span>Subscribe</span>
</div>
</div>
<div class="second">
<span>Thank you for<br />subscribing!</span>
</div>
</div>
<script src='jquery-3.3.1.min.js'></script>
<script src="script.js"></script>
script.js
$(document).ready(function(){
function validatePhone(phone) {
var re = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
return re.test(phone);
}
$('.input').on('keyup',function(){
var formInput = $('.input').val();
if(validatePhone(formInput)){
$('.validator').removeClass('hide');
$('.validator').addClass('valid');
$('.send').addClass('valid');
}
else{
$('.validator').removeClass('valid');
$('.validator').addClass('hide');
$('.send').removeClass('valid');
}
});
var phone = $('#phone').val();
var data =
'phone='+phone;
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
});
subscribe.php
```php
$phone = htmlentities($_POST['phone']);
if (!empty($phone)) {
echo 1;
}else{
echo "Phone number cannot be empty";
}
```
An empty results with the error code is all I get. Can any one help me out here with the mistakes I am making. Thanks
Change next
JS:
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
to
$('.send').click(function(){
var data = $('#phone').val();
$.ajax({
type:"POST",
url:"subscribe.php",
data: {phone: data},
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
});
});
If you send a POST request via ajax you need to format data as a JSON object, see my code below.
Replace this:
var data =
'phone='+phone;
with this:
var data = {phone: phone};

$.post() not able to pass data

I want to pass some data as a variable using jQuery $.post() method to a PHP file and then display the result in a div after clicking a button. But the data isn't getting retrieved in PHP file.
<script>
$(document).ready(function () {
$("button").click(function () {
$.post("add.php", {
fname: 'Billy'
}, function () {
$('#topic').load('add.php');
});
});
});
</script>
</head>
<body>
<br>
<div class="container">
<?php
echo "Welcome ".get('Name')." !";
?>
<div style="float: right">
<?php
echo "<a href='logout.php'> Log Out </a>";
?>
</div>
<br>
<button>Add Topic</button><br>
<div id='topic'></div>
//the PHP file:
<?php
session_start();
echo "".$_POST['fname']."";
//if(isset($_POST['fname']))
//{
//$fname=$_POST['fname'];
//echo " ".$fname." topic added!";
//}
?>
Notice: Undefined index: fname in C:\xampp\htdocs\forum\add.php on line 3
I'm not too familiar with the load function, but it seems to me that you're doubling down on fetching from the same resource.
You could do something like:
$.ajax({
type: "POST",
url: 'add.php',
data: {fname:"Billy"},
success: function(response){
$( "#topic" ).html(response);
// or .text or whichever replacement method you need/works best
},
});
add.php
if ( isset($_POST['fname'] ){
echo "Topic " . $_POST['fname'] . " added!";
} else {
echo "Could not find 'fname'!";
}
$.ajax({
type: "POST",
url: 'add.php',
data: {fname:"your data goes here"},
success: function(response){
// handle success
},
error: function(response){
// handle error
},
});

how to checked the checkbox after fetching the data from database using jquery and php

when user click on a button it displays the dynamic data fetched from the database along with the appropriate check box ..so user has select or check the checkbox of some data and submit the result then those data are stored in database.
again that user clicked the same button then again those data are displayed but this time the data which are selected buy the user previously should be checked. I am trying to do that but enable to write code for it in jquery.
below is my code...
javascript
$(document).ready( function() {
$('#location_choose').click(function(e){
branch();
document.getElementById('brn_light').style.display='block';
document.getElementById('fade').style.display='block';
});
function branch()
{
//alert(user_id);
$.ajax({
url: "<?php echo base_url(); ?>/login/branch",
data: {},
type: "post",
cache: false,
success: function (data)
{
//alert(data);
var obj = $.parseJSON(data);
var result = "";
<?php foreach($resultsb as $rows){?>
for ( var i = 0; i < obj.length; i++ )
{
result+="<table id='branchtable'><tr height='25px' ><td>&nbsp&nbsp</td><td ><input class='test' type='checkbox' name='branch_name' value="+obj[i].id+"<?php echo ($rows['branch_id']=="+obj[i].id+"? 'checked' : '');?>></td><td width='15px'></td><td width='630px'><b>"+obj[i].branch_name+
"</b></td></tr><tr><table id='branch_address' style='background-color:#EBF5FB'><tr><td>&nbsp&nbsp</td></tr><tr><td width='60px'></td><td width='440px'>"+obj[i].address+"</td><td width='40px'></td></tr><td>&nbsp</td></table></tr><tr></tr></table>";
}
<?php }?>
//alert(result);
document.getElementById("branch_table").innerHTML=result;
},
error: function (xhr, ajaxOptions, thrownError)
{
//alert(thrownError);
}
});
}
});
i tried using
<?php echo ($rows['branch_id']=="+obj[i].id+"? 'checked' : '');?>
in above code but still it doesnt checked the previous selected one.
Give The Same Class of Checkbox and Write Jquery Code
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$( document ).ready(function() {
$( '.select_all_text').click(function() {
var is_check = $(".select_type").prop('checked');
if(is_check == false)
{
$(".select_type").prop('checked', true);
$(''.select_all_text").text('De-select All');
}
else
{
$(".select_type").prop('checked', false);
$('.select_all_text").text('Select All');
}
});
});
</script>
</head>
<body>
<p style="position: sticky; z-index: 100; width: 50%;"><a id="select_all" onclick="check_uncheck" style="margin-right: 2%;" href="javascript:void(0)">Select all</a>
<?php
foreach($data_list as $data)
{
?>
<input type="checkbox" name="select_type[]" value="<?php echo $item_id; ?>" class="select_type" id="select_type"/>
<?php
}
?>
</body>
</html>

Load ajax var into bootstrap modal which is loading from another php page

I have multiple modals on one page, all of which have unique ids. When a user clicks a button it opens the unique modal.
<button id="<?php echo $removeslash; ?>" class="btn btn-primary open-modal" data-source="output.php"><span class="glyphicon glyphicon-new-window"></span> Open Modal</button>
As you can see the body of the modal is in output.php, this is because im running a script in output.php which creates unique data depending which button has been clicked. Im trying to pass id="<?php echo $removeslash; ?>" to output.php via ajax. Here is ajax below.
<script>
$(document).on("click", ".open-modal", function(e) {
e.preventDefault();
$("#modalResult .modal-body").load($(this).data("source"), function(response, status, xhr) {
if (status == "error") {
console.log("unable to load content : " + xhr.status);
} else {
$("#modalResult").modal("show");
}
});
var mehmeh = $(this).attr('id');
$.ajax({
type: "POST",
url: "output.php",
data: ({
'id': mehmeh
}),
success: function(msg) {
alert("Data Saved: " + msg);
}
});
});
The ajax code works okay I think because the success function displays with the button id in. But when the modal loads, it wont load. Here is the echo code in the output.php file.
<h1>FooBar: <?php echo $_REQUEST['id']; ?></h1>
Im sure it has something to do with the modal loading on index.php but ajax giving the data to output.php, but i cant figure it out.
Thanks
Ive managed to fix this problem, it might be pretty sloppy but here it is.
<script>
$(document).on("click", ".open-modal", function(e) {
var id = $(this).data('id');
e.preventDefault();
$("#modalResult .modal-body").load($(this).data("source"), function(response, status, xhr) {
if (status == "error") {
console.log("unable to load content : " + xhr.status);
} else {
$.post("output.php", {
id: id
})
.done(function(data) {
$("#modalResult").modal("show");
$('.modal-body').html(data);
})
}
});
});

jQuery AJAX POST to current page with attribute

This is an example of my own page.
<?php
$do = $_GET['do'];
switch($do){
case 'finalTask':
if(isset($_POST['url'])){
echo "It's Ok!";
}else{
echo "Problem!";
}
}
This is also written in the same page.
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script>
$(document).ready(function(e){
$('#send').click(function(){
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url:"index.php?do=finalTask",
cache:false,
data:dataStr,
type:"POST",
success:function(data){
$('#info').html(data);
}
});
});
});
</script>
When I try to input and press the send button. Nothing happened..... What's wrong with the code?
Make sure file name is index.php
You need to make sure that you check in the php code when to output the form and when the
Format of ajax post request is incorrect in your case.
You forgot to import JQuery JS script, without that you can not use JQuery. (at least at this point of time)
-
<?php
if (!isset($_GET['do'])) { // Make sure that you don't get the form twice after submitting the data
?>
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$('#send').click(function () {
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url: "index.php?do=finalTask",
cache: false,
data: {url: dataStr}, // you need to send as name:value format.
type: "POST",
success: function (data) {
$('#info').html(data);
}
});
});
});
</script>
<?php
} else {
error_reporting(E_ERROR); // Disable warning and enable only error reports.
$do = $_GET['do'];
switch ($do) {
case 'finalTask':
if (isset($_POST['url'])) {
echo "It's Ok!";
} else {
echo "Problem!";
}
}
}
?>
There seems to be no form in your page, just form elements. Can you wrap them in a form:
<form method="POST" onSubmit="return false;">
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
</form>

Categories