Show DIV with AJAX in PHP After Saving Data to Mysql - php

I Have a problem here. I try to show up the information box using DIV after successfully save the data to mysql.
Here my short code.
// Mysql insertion process
if($result){?>
<script type="text/javascript">
$(function() {
$.ajax({
$('#info').fadeIn(1000).delay(5000).fadeOut(1000)
$('#infomsg').html('Success.')
});
}
</script>
<?php }
How can DIV appear? I tried but nothing comes up. Any help? Thank you

a basic jQuery ajax request:
$(function() {
$.ajax({
url: "the url you want to send your request to",
success: function() {
//something you want to do upon success
}
});
}

lets say you have a session of ID and you want to retrieve it in your database.
here is: info.php
<input type="hidden" name="id"><input>
<input type="submit" onclick="showResult(id)" value="Click to Show Result"></input>
function showResult(id){
$j.ajax(
method:"POST",
url:"example.php",
data: {userid:id},
sucess: function(success){
$('#infomsg').html(Success)
});
}
<div id= "infomsg"></div>
example.php
$id = $_POST['userid']; ///////from the data:{userid :id}
//////////config of your db
$sql = mysql_query("select * from users where id = $id");
foreach ($sql as $sq){
echo $sq['id']."<br>";
}
the "infomsg" will get the result from the function success and put it in the div.

Related

How to send values of Select button from Mysqli database and send to second pages?

I tried to coding it. I am still getting stuck over it. The main goal was if user select value from mysqli database selected it and send the values to other pages. I know people recommend it use by AJAX. I tried to use it. still not working. I'll put details code below.
Main pages Code(main.php)-
<?php
session_start();
$conn=mysqli_connect('localhost','root','','user');
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$resultset=$conn->query("SELECT name from newtable"); ?>
<!DOCTYPE html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</head>
<body>
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
click
</center>
<script type="text/javascript">
$(document).ready(function(){
var search='';
$("#tables option:selected").each(function() {
if ($(this).attr('value') !== '') {
search=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
method: 'post',
url: 'database1.php',
data: {key:search},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
</body>
</html>
as alert box i am getting value of it but second pages get error that key value doesn't exist. here the second one pages (database1.php) -
<?php
$conn=mysqli_connect('localhost','root','','user');
session_start();
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$database=$_POST['key'];
echo'You Selected'.$database.'from table';
$sql = "SELECT * FROM $database";
$result=mysqli_query($conn,$sql);
if($result){
echo'Worked';
}else{
echo'ERROR!';
}
?>
so what the problem occurred?
UPDATED ANSWER
Thanks to #swati which she mentioned that use form tag instead of AJAX (i know its simple answer) still by the way thanks for answer. :)
UPDATED CODE FULL -
<body>
<form action="database1.php" method="GET">
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option
value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<input type="submit">
</center>
</form>
</body>
SECOND PAGE(database1.php) CHANGES LITTLE -
$database=$_GET['tables'];
You are calling each loop on page load that will give you the already selected value not the value which is selected by user.Also , this loop is not need as you have to pass only one value .
Your script should look like below :
<script type="text/javascript">
$(document).ready(function() {
//no need to add loop here
var search = '';
$("a").click(function() {
search = $("#tables option:selected").val(); //getting selected value of select-box
$.ajax({
method: 'post',
url: 'database1.php',
data: {
key: search
},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
Also , as you are using ajax no need to give href="database1.php" to a tag because you are calling this page using ajax .i.e: Your a tag should be like below :
<a>click</a>
And whatever you will echo in php side will be return as response to your ajax .So , your alert inside success function will show you that value.

Insert into mysql database from html form without redirecting [duplicate]

This question already has answers here:
Form submit with AJAX passing form data to PHP without page refresh [duplicate]
(10 answers)
Closed 7 years ago.
I'm working with a mysql database and a webpage that i'm trying to make comunicate with it.
Here's my situation:
i have the listmat.php file that echoes all the records in the table Material and it works.
Now i manage to show the output of the listmat.php file inside a specific div witouth refreshing the hole page with the following code:
<script>
$(document).ready(function(){
$("#matbutton").click(function(){
$("#matins").load('listmat.php');
});
});
</script>
Where matbutton is the id of the submit button in the form and matins is the id of the div where i show the output of listmat.php
Here's my form:
<form id="formmatins" method="post" action="listmat.php">
<p>Name:<input type="text" Name="Mat" id="Material"></p>
<center><input type="submit" value="Insert/Remove" id="matbutton"></center>`
</form>
What i'd like to do is to use the matbutton to also insert the value of the textbox in the table that listmat.php echoes all his records. So that everytime i click a record is inserted and in the div is shown the new table
The problem is that if i insert the button in the form with the method post , by clicking it redirects to the output changing page but if i put it out the echoes work but i cannot pass obviously the value of the textbox to the listmat.php file to be the argument of the insert because the button is not interested by the method post.
I looked around and looks like the solution is using some articulated structure in jquery/ajax but i really don't know how to fix. Any help would be really appreciated
UPDATE
<script>
$(function () {
$('#formmatins').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'listmat.php',
data: $('#formmatins').serialize(),
success: function () {
$("#matins").load('listmat.php');
alert('form was submitted');
}
});
});
});
</script>
And again it switch page
UPDATE
<?php
$user = "**";
$pass = "**";
$db = "**";
$host = "localhost";
$con = mysqli_connect($host,$user,$pass,$db);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$m = $_POST['Mat']; //the text box in the form
$ins = $con->query("INSERT INTO mattemp (Material) VALUES ('$m')");
$query = $con->query("SELECT Material FROM mattemp");
while ($row = $query->fetch_assoc()) {
echo $row['Material']."<br>";
}
?>
It print the table updated everytime but still in a new page...what am i doing wrong?
SOLVED BY MYSELF
Thanks to all have tried to help me. The solution that gave me -1 on the post was not correct and here the solution of my code , in case someone would encounter the same problem
`<script>
$(function () {
$('#matbutton').on('click', function(event){
event.preventDefault();
$.ajax({
type: 'post',
url: 'listmat.php',
data: $('#formmatins').serialize(),
success: function (data) {
$("#matins").load('listmat.php');}
});
});
});
</script>`
You'll need $.ajax
For exemple :
$.ajax({
url: "your_url.php",
type: "POST",
data: $('#formmatins').serialize(),
success: function(response){
// Do something, or not...
}
})

I have encountered a really weird thing while Inserting jquery var in mysql table from a php page

I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});

Codeigniter AJAX Example

I've been looking for a week now for a decent full working example of how to use AJAX with Codeigniter (I'm an AJAX novice). The posts / tuts I've seen are old - all the programming languages have moved on.
I want to have an input form on a page which returns something to the page (e.g. a variable, database query result or html formatted string) without needing to refresh the page. In this simple example is a page with an input field, which inserts the user input into a database. I'd like to load a different view once the input is submitted. If I could understand how to do this I'd be able to adapt it to do whatever I needed (and hopefully it would help others too!)
I have this in my 'test' controller:
function add(){
$name = $this->input->post('name');
if( $name ) {
$this->test_model->put( $name );
}
}
function ajax() {
$this->view_data["page_title"] = "Ajax Test";
$this->view_data["page_heading"] = "Ajax Test";
$data['names'] = $this->test_model->get(); //gets a list of names
if ( $this->input->is_ajax_request() ) {
$this->load->view('test/names_list', $data);
} else {
$this->load->view('test/default', $data);
}
}
Here is my view, named 'ajax' (so I access this through the URL www.mysite.com/test/ajax)
<script type="text/javascript">
jQuery( document ).ready( function() {
jQuery('#submit').click( function( e ) {
e.preventDefault();
var msg = jQuery('#name').val();
jQuery.post("
<?php echo base_url(); ?>
test/add", {name: msg}, function( r ) {
console.log(r);
});
});
});
</script>
<?php echo form_open("test/add"); ?>
<input type="text" name="name" id="name">
<input type="submit" value="submit" name="submit" id="submit">
<?php echo form_close(); ?>
All that happens currently is that I type in an input, updates the database and displays the view "test/default" (it doesn't refresh the page, but doesn't display "test/names_list" as desired. Many thanks in advance for any help, and for putting me out of my misery!
Set unique id to the form:
echo form_open('test/add', array('id'=>'testajax'));
I assume that you want replace a form with a view:
jQuery(document).ready(function(){
var $=jQuery;
$('#testajax').submit(function(e){
var $this=$(this);
var msg = $this.find('#name').val();
$.post($this.attr('action'), {name: msg}, function(data) {
$this.replace($(data));
});
return false;
});
better way if you return url of view in json response:
$.post("<?php echo base_url(); ?>test/add", {name: msg}, function(data) {
$this.load(data.url);
},"json");
from your last comment - I strongly not suggest to replace body, it will be very hard to support such code.
but here is anser:
$.post("<?php echo base_url(); ?>test/add", {name: msg}, function(data) {
$('body').replace(data);
});

Easiest Way To Make A Form Submit Without Refresh

I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.

Categories