I am newbie in php and javascript.
I want to know about the working of this function.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
echo ('I am in Send Push Nottification');
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
Q) My question is how this fuction sending the data php file
Like(http://uitdevelopers.site40.net/ClientServer/?name=qasim)
EDIT
Here is send_message.php
<?php
if (isset($_GET["regId"]) && isset($_GET["message"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
include_once 'gcm.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
?>
This is my php file and i want to execute it but i cannot understand this function
Edit
This is my index.html. Where i want to call this function
But it cannot working.
It is working staticaly but when I send data dynamically can't work
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
echo ('I am in Send Push Nottification');
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
</head>
<body>
<?php
require_once('db_functions.php');
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post"
onsubmit="return sendPushNotification( $row["id"])">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message"
placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send"
onclick="sendPushNotification( $row["id"])"/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
$.ajax means, call method ajax from the object $
this method will use http GET method, this means that array data will be appended to URL send_message.php after question mark ?
as soon as url does not start with / or protocol (like http://), current protocol, hostname and path will be used, so final string will be PROTOCOL://HOST[:PORT]/PATH/send_message.php?form_field_name=form_field_value&form_field_name2=form_field_value2
after forming full URL, this method will use browser-dependent method (for example XMLHTTPRequest) to call this url and call your JS function success with result
It gathers the data from your form in client side by using $('selector').serialize(); of jquery and get's all the data inside your php then if your server side has no errors it throws back to your client side to show all data's by using success if it is success or error if it fails. Ajax is for querying your result without reloading your page.
Related
I have an problem, I have multiple button generate with while, with different names (button[$nostation]).
Now, I want to update MySQL database (table: smt, column: no) with the same id ($nostation).
How I can generate AJAX function for that?
This is my code:
<?php
$query1 = mysqli_query($connect,"SELECT * FROM smt WHERE no <= 15");
while ( $data=mysqli_fetch_array($query1)){
$nostation = $data['no'];
$namastation = $data['name'];
echo "
<div class='col-xs-2-2'>
<form action='coba.php' method='post'>
<button name='button[$nostation]' value='2' style='background-color:#02780d; width:140px; height:75px; margin : 2px; border-radius:10%;'>
<center>
<b style='font-size:15px; color: #fff; font-family:Calibri;'>$namastation</b>
</center>
</button>
</form>
</div>
";}?>
And this is my code for update database with PHP:
<?php
include 'connect.php';
$array=$_POST['button'];
foreach ($array as $nostation => $value) {
$updch=mysqli_query($connect,"UPDATE smt SET status='$value' WHERE no='$nostation'");
}?>
How I can update with AJAX without refreshing the page?
View Part :-
<?php
$query1 = mysqli_query($connect,"SELECT * FROM smt WHERE no <= 15");
while ( $data=mysqli_fetch_array($query1)){
$nostation = $data['no'];
$namastation = $data['name'];
?>
<div class='col-xs-2-2'>
<form method='post'>
<input type="hidden" value="<?php echo $nostation;?>" id="name_<?=$nostation;?>" name="name">
<button type="submit" id="button_<?=$nostation;?>" data-id="<?=$nostation;?>">SAVE</button>
<center>
<b style='font-size:15px; color: #fff; font-family:Calibri;'>$namastation</b>
</center>
</button>
</form>
</div>
<?php } ?>
jQuery / AJAX Part:-
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){ //when DOM is Ready.
$("[id^=button_]").click(function () { //when Button is Clicked.
var id = $(this).data('id'); // Get the ID of the button that was clicked on.
var name = $("#name_"+id).val(); // value from `input` which is connected the clicked button.
// console.log(id+"---"+name);
$.ajax({ // AJAX request
url: 'update.php', // send request to server.
method: 'POST', // method is POST.
data: { //data which is sent to server.
id: id,name: name
},
success: function (data) { //success function called.
alert(data); // alert success data.
}
});
});
});
</script>
update.php:-
And in the php-side We catch it by:-
echo $id = $_POST['id'];
echo $name = $_POST['name'];
//use update query.
Note:- For more info regarding click()
https://api.jquery.com/click
So I've got this form for adding comments under a post. The methods utilized here are MYSQL(holds the submitted form data in a database) PHP(communicating with the database) and JavaScript, more specifically AJAX (for hooking up the submit button and handling events).
Typing in your comment into the form and pressing submit is supposed to print the comment onto the screen.
When I click submit, it doesn't print anything. Then, when I type another comment and click submit once more, it prints the contents of that comment. Other times, it successfully prints the contents of the comment instead of failing to submit.
I checked it out in inspect element and in the console log, whenever it misses, it still sends some blank <p> tags through with the class of the comment that should be submitted.
The PHP page for the comment form:
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="Forums.css">
</head>
<body>
<?php
$result = mysqli_query($link, $displayPost); ?>
<?php $row = mysqli_fetch_assoc($result);?>
<p> <?php echo $row["title"];?> </p>
<br>
<p> <?php echo $row["body"];?> </p>
<form action="<?php echo $url ?>" method="post" id="form-group">
<div class="forum col-md-12">
<textarea type="text" style="overflow: auto; resize: none;" name="body" class="txtBody"></textarea>
<input type="submit" name="submit" class="btnCreate" style="margin-bottom: 4px;">
</div>
</form>
</body>
<script>
function refreshData() {
$.ajax({
type:'GET',
url: 'getcomments.php?id=<?php echo $id ?>',
dataType: 'html',
success: function(result){
console.log(result);
$('#comments').html(result);
}
});
}
$(document).ready(function () {
refreshData();
$("#form-group").submit(function (event) {
var $form = $(this);
console.log($form.attr('action'));
var serializedData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: serializedData
});
refreshData();
event.preventDefault();
});
});
</script>
<div id="comments"></div>
The PHP page for getting previously submitted comments and printing them on the screen
<?php
$link = mysqli_connect("localhost", "root", "WassPord64", "forum");
$id = $_GET["id"];
$displayPost = "SELECT * FROM comments WHERE post_id='$id'";
$link->query($displayPost);
$result = mysqli_query($link, $displayPost);
if (mysqli_num_rows($result) > 0) :
// output data of each row
while($row = mysqli_fetch_assoc($result)) :
$row = mysqli_fetch_assoc($result);?>
<p class="postBody"><?php echo $row['body'];?></p>
<?php endwhile; ?>
<?php endif; ?>
You are calling refreshData() when the Ajax is not done. You can make a callback function by using $.ajax.success
Try this:
$(document).ready(function () {
refreshData();
$("#form-group").submit(function (event) {
var $form = $(this);
console.log($form.attr('action'));
var serializedData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: serializedData,
success: function(){
refreshData();
}
});
event.preventDefault();
});
});
i am trying to use ajax submit form but for some reason it doesn't work for me, any suggestions how to fix it.
I'm getting the alert message when I submit but it takes me to another page, what am i doing wrong with ajax request ?
<!DOCTYPE html>
<html>
<head>
<title>Get Data From a MySQL Database Using jQuery and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// AJAX forms
$("#search_form").submit(function(e){
e.preventDefault();
//var data = $(this).serialize();
var method = $(this).attr("method");
var action = $(this).attr("action");
var username = $('#username').val();
$.ajax({
url: 'process.php',
type: 'POST',
data: { name: username },
cache: false,
success: function(data){
$('#results').html(data);
}
})
})
});
</script>
</head>
<body>
<span>Search by name: </span>
<form method="POST" action="process.php" id="search_form">
<input type="text" id="username" name="name">
<input type="submit" id="submit" value="Search">
</form>
<div id="results"></div>
</body>
</html>
process.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Check if $_POST is set
if ( empty ( $_POST['name'] ) ) {
echo "Something wrong!";
exit;
}
$name = $_POST['name'];
$m = new MongoClient();
//echo "Connection to database successfully";
// select a database
$address = array(
'name'=>$name,
'city' => 'test',
'state' => 'test2',
'zipcode' => 'test3'
);
$db = $m->local;
//echo "Database mydb selected";
$collection = $db->user;
//echo "Collection selected succsessfully";
$collection->insert($address);
$user = $collection->findOne(array('name' => $name));
?>
<ul>
<li><?php echo $user['name']; ?>: <?php echo $user['city']; ?></li>
<script>
alert('test 1234');
</script>
</ul>
I had to change:
$("#search_form").submit(function(e){
to:
$(document).on('submit', '#search_form', function(){
Now it works fine.
<!DOCTYPE html>
<html>
<head>
<title>Get Data From a MySQL Database Using jQuery and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
// AJAX forms
$(document).on('submit', '#search_form', function() {
//e.preventDefault();
//var data = $(this).serialize();
var method = $(this).attr("method");
var action = $(this).attr("action");
var username = $('#username').val();
$.ajax({
type: 'POST',
url: 'process.php',
data: {
name: username
},
cache: false,
success: function(data) {
$('#results').html(data);
}
})
return false;
});
});
</script>
</head>
<body>
<span>Search by name: </span>
<form method="POST" action="process.php" id="search_form">
<input type="text" id="username" name="name">
<input type="submit" id="submit" value="Search">
</form>
<div id="results"></div>
</body>
</html>
I'm a newbie in the world of php and I was trying to learn it with a simple page.
I've created an html form and I want to send data using ajax but it still
POST http://localhost/Home.php 500 (Internal Server Error)
In particular I want to create a button for every table in a database which I'm using for testing, when I push a button it will show all lines from the database (I've not implemented it yet, I'm only trying to understend how php and ajax communicate)
This is my form (Home.php)
<?php
session_start();
if(!isset($_SESSION['login'])) {
header("Location: Login.php");
unset($_REQUEST);
}
else echo "<span class=\"welcome\"><strong>Benvenuto</strong> <em>" . $_SESSION['username'] . "</em></span>";
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='jquery-1.11.3.js'></script>
<script src='Script.js'></script>
</head>
<body>
<div id="functions">
<button id="createTable">CREATE</button>
<button id="displayTable">DISPLAY</button>
</div>
<div id="createForm">
<form id="queryForm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input class ="text" name="query" type="text" size="50">
<input type="submit" class="submit" name="createQuery">
</form>
</div>
<div id="displayForm">
<form method="post" id="selectForm">
<?php
include ("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$Tables = $Database->countTable();
foreach($Tables as $column) {
echo "<input type=\"radio\" class=\"submit\" id=\"selectQuery\" name=\"selectQuery\" value=\"". $column . "\"> " . $column;
}
?>
<input type="submit" class="submit" name="createSelect">
</div>
<div style="position:absolute; bottom:10px; left:50%; font-size: 15pt"></span><em>...</em> Logout</div>
</body>
</html>
<?php
if(isset($_POST['createQuery'])) {
include ("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$Database->createTable($_POST["query"]);
header("Location:Home.php");
}
?>
And this is my ajax file
$(document).ready(
function() {
$("#createTable").click(goCreate);
$("#displayTable").click(goDisplay);
$('#selectForm').submit(goSelect);
$("#createForm").hide();
$("#displayForm").hide();
}
);
function goCreate(data) {
$("#createForm").show();
$("#functions").hide();
}
function goDisplay(data) {
$("#displayForm").show();
$("#functions").hide();
}
function goSelect() {
var selectedTable = $("#selectQuery:checked").val();
console.log($("#selectQuery:checked").val());
$.ajax({
url: "Prova.php",
type: "POST",
dataType: "html",
data: {
'select': 'display',
'table': selectedTable
},
success: function(msg) {
console.log(msg);
},
error: function(xhr, desc, err) {
console.log("error");
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
return false;
};
And this is Prova.php where I managed ajax call
<?php
include 'ChromePhp.php';
ChromePhp::log("corretto");
echo "ok belo";
?>
I have a code here of inserting and displaying record without refreshing web page using ajax and plain php but I don't know how to set this up using codeigniter. Please help. Here are the codes
inserting.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle">
<span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
document.getElementById('content').focus();
$("#flash").hide();
}
});
} return false;
});
});
</script>
// HTML code
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Update" name="submit" class="comment_button"/>
</form>
</div>
<div id="flash"></div>
<div id="display"></div>
demo_insert.php
PHP Code display recently inserted record from the database.
<?php
include('db.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
mysql_query("insert into messages(msg) values ('$content')");
$sql_in= mysql_query("SELECT msg,msg_id FROM messages order by msg_id desc");
$r=mysql_fetch_array($sql_in);
}
?>
<b><?php echo $r['msg']; ?></b>
In your wellcome controller you can add the following:
public function inserting()
{
$this->load->view('inserting');
}
public function process()
{
$content=$this->input->post('content');
if($this->db->insert('mytable', array('msg' => $content))){
echo "<b>{$content}</b>";
}
You should then use inserting.php as your view, in application/views, and the ajax url would be /process.
Didn't test it, but this should do the trick. Also, you should check this example http://runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php