How to call the ajax page in same page? - javascript

I have two files demo.php and post.php. How can I do in single
page instead of two page.
demo.php
<html>
<head>
<title>Dynamic Form</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js" ></script>
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "post.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td>
<select name="one" onchange="if (this.value=='other'){this.form['other'].style.visibility='visible';this.form['submit'].style.visibility='visible'}else {this.form['other'].style.visibility='hidden';this.form['submit'].style.visibility='hidden'};">
<option value="" selected="selected">Select...</option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>
<option value="Us">Us</option>
<option value="other">Other</option>
</select>
<input type="textbox" name="other" id="other" style="visibility:hidden;"/>
<input type="submit" name="submit" value="Add Country" style="visibility:hidden;"/>
</td>
</tr>
</table>
</form>
</body>
post.php
<?php
if(isset($_POST['other'])) {
$Country = $_POST['other'];
echo $Country;
}
?>
How can I use the post.php data in demo.php without passing data from one page to another.

Change the url of your ajax
$.ajax({
type: "POST",
url: "demo.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
And add this in your demo.php
<?php
if(isset($_POST['other'])) {
$Country = $_POST['other'];
echo $Country;
}
?>

I have a few personal observations:
the first one it's in the approach: I don't think it was a bad idea to have two separate files. This is not really a good optimization. Now you want a single file to handle a GET request and POST in two different ways (one for AJAX one for normal POST in case you want your javascript to degrade gracefully.
you might want to remove that "onchange" attribute. Look into the concept of Unobtrusive JavaScript for why this is good practice
never trust user input: always sanitize and validate appropriately
bellow is a version of your file rewritten. Notices I've re factored the onChange with something more maintainable and I'm using JS to make the initial hiding of the input and submit button. This way if JS is disabled the user can still add countries.
in order to determine how the post was triggered I pass an extra flag ajax=1 to the post.
<?php
$country = filter_input(INPUT_POST, 'other');
// Ajax
if (isset($_POST['ajax']))
{
echo 'Successfully added country: ' . $country;
exit();
}
// normal post
else
{
echo $country;
}
?>
Dynamic Form
$(document).ready(function(){
$('#country').on('change', hideStuff);
// hide the buttons to add extra option
$('#other, #submit').hide();
function hideStuff()
{
var select = $(this);
var flag = select.val() === 'other';
$('#other, #submit').toggle(flag);
}
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize() + "&ajax=" + 1;
$.ajax({
type: "POST",
url: $(this).data('url'),
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
</head>
<body>
<form method="post" data-url="<?php echo basename(__FILE__); ?>">
<table>
<tr>
<td>
<select id="country" name="one">
<option value="" selected="selected">Select...</option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>
<option value="Us">Us</option>
<option value="other">Other</option>
</select>
<input id="other" type="textbox" name="other">
<input id="submit" type="submit" name="submit" value="Add Country">
</td>
</tr>
</table>
</form>
</body>

that's very easy, just paste the below code on to the upper code.
And remove the jquery ajax call.
<html>
<head>
<title>Dynamic Form</title>
</head>
<body>
<form action="post">
<table>
<tr>
<td>
<select name="one" onchange="if (this.value=='other'){this.form['other'].style.visibility='visible';this.form['submit'].style.visibility='visible'}else {this.form['other'].style.visibility='hidden';this.form['submit'].style.visibility='hidden'};">
<option value="" selected="selected">Select...</option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>
<option value="Us">Us</option>
<option value="other">Other</option>
</select>
<input type="textbox" name="other" id="other" style="visibility:hidden;"/>
<input type="submit" name="submit" value="Add Country" style="visibility:hidden;"/>
</td>
</tr>
</table>
</form>
</body>
<?php
if(isset($_POST['other'])) {
$Country = $_POST['other'];
echo $Country;
}
?>

You can change the url into demo.php and use the below one along with exit();,
<?php
if(isset($_POST['submit'])){
$Country = $_POST['other'];
echo $Country;
exit();
}
?>

first you change the url of $ajax
$.ajax({
type: "POST",
url: "demo.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
and then change your "demo.php"
<html>
<head>
<title>Dynamic Form</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js" ></script>
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "post.php",
data: data
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
</head>
<body>
<?php
if(isset($_POST['other'])) {
$Country = $_POST['other'];
echo $Country;
}
else{
?>
<form>
<table>
<tr>
<td>
<select name="one" onchange="if (this.value=='other') {this.form['other'].style.visibility='visible';this.form['submit'].style.visibility='visible'}else {this.form['other'].style.visibility='hidden';this.form['submit'].style.visibility='hidden'};">
<option value="" selected="selected">Select...</option>
<option value="India">India</option>
<option value="Pakistan">Pakistan</option>
<option value="Us">Us</option>
<option value="other">Other</option>
</select>
<input type="textbox" name="other"id="other"style="visibility:hidden;"/>
<input type="submit" name="submit" value="Add Country"style="visibility:hidden;"/>
</td>
</tr>
</table>
</form>
<?php } ?>
</body>

Try this
<script>
$(document).ready(function(){
$("form").on('submit',function(event){
event.preventDefault();
var yData = $(this).serialize();
$.post('demo.php', {action:"other",yourData:yData}, function(msg) {
alert( "Data Saved: " + msg );
});
});
</script>
<?php
if($_REQUEST['action']=="other")
{
$country= $_REQUEST['yourData'];
echo $country;
exit;
}
?>

Hopefully this will help you but I don't understand what "data" is. Make sure it is a field or the variable which is supplying value that is required for the page.
$("form").on("submit",function() {
$.ajax({
type : "GET",
cache : false,
url : "post.php",
data : {
data : data
},
success : function(response) {
$('#content').html(response);
}
});
});

Related

PHP / SQL: Multiple delete data using Select Option

Now I create a system that can delete multiple data using select option. But here I got some issues. When i only select one data, and press button delete, it will delete. But if I choose more than one data, for example, 3 data, it will only delete the latest id of the data. Below is my the image
And below is my code:
index.php
<form method="post" id="multiple_select_form">
<select name="framework" id="framework" class="form-control selectpicker" data-live-search="true" multiple>
<?php foreach ($results as $row2): ?>
<option value= <?php echo $row2["framework_id"]; ?>><?php echo $row2["framework_name"];?></option>
<?php endforeach ?>
</select>
<br /><br />
<input type="hidden" name="framework_id" id="framework_id" />
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</form>
<script>
$(document).ready(function(){
$('.selectpicker').selectpicker();
$('#framework').change(function(){
$('#framework_id').val($('#framework').val());
});
$('#multiple_select_form').on('submit', function(event){
event.preventDefault();
if($('#framework').val() != '')
{
var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
//console.log(data);
$('#framework_id').val('');
$('.selectpicker').selectpicker('val', '');
alert(data);
}
})
}
else
{
alert("Please select framework");
return false;
}
});
});
</script>
insert.php
<?php
include("configPDO.php");
$smt = $conn->prepare("DELETE FROM frame_list WHERE framework_id = '".$_POST["framework_id"]."'");
$smt->execute();
if($smt){
echo "Data DELETED";
}else{
echo "Error";
}
?>
Can anyone knows how to solve this problem? Thanks
framework will hold one value every time.
Use input arrays -
Change name="framework" to name="framework[]".
and in query -
WHERE framework_id in ('". implode("','", $_POST["framework_id"]) ."')"
Try to use parameter binding for security.

Ajax value remain same after reload page

I am using 2 drop down lists. One list comes from Ajax code. My question is this, how do I keep the ensure the value remains in the second drop down while the form is reloaded. I am using trigger change event for value of model drop down.
My code is below
---i
Trigger Change Jquery i used from stack overflow.
--i have one more table name model the value of vehicle comes from make table.
--
<?php
include "conn.php";
$exe=$con->query("select * from make");
?>
<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$('#make').trigger("change");
//console.log(make);
function getModel()
{
var mid= document.getElementById("make").value;
//console.log(mid);
$.ajax({
type:"POST",
url :"model.php",
data:"makeid="+mid,
success:function(ans)
{
document.getElementById("model").innerHTML=ans;
}
});
}
</script>
</head>
<body>
<form method="post">
<table align="center">
<tr>
<td>Make</td>
<td>
<select name="make" id="make" onchange="return getModel()">
<?php
while ($row=$exe->fetch_object())
{
?>
<option value="<?php echo $row->make_id?>">
<?php if(isset($_POST['make']) && $_POST['make']==$row->make_id) echo "selected";?>
<?php echo $row->make_name?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Model</td>
<td><select name="model" id="model">
<option value="">.....</option>
</select></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
This code will store your dropdown value to the storage
let dropdownModel= document.getElementById("model").value
localStorage.setItem("myValue", dropdownModel);
This code will load your stored value from your dropdown and put it back to it
document.getElementById("model").value = localStorage.getItem("myValue");
Use jquery to call on change,
$(document).ready(function(){
$("#make").on('change', function(){
var make_id= $("#make option:selected").val();
$('#model').empty();
$.ajax({
url: 'model.php',
type: 'POST',
dataType: "text",
data: {
make_id: make_id,
}
}).done(function(data){
$('#model').html(data);
});//ajax success function
}).change();
});
in model.php make a drop down like this
<option>A</option>
<option selected >B</option>
With this code you can get the second drop down names model value. Then you can select it when the form has loaded.
<script>
$(document).ready(function() {
$("#make").trigger('change');
$("#model").selectedIndex = <?php echo $_POST['model']?>;
});
</script>

Alert Message on Success not working on AJAX

Hi i am beginner in AJAX and facing a problem in following code which does not pop up the alert message.
I was tried to insert data from form to database using AJAX.
This code successfully store the data into database.
But it not pop up the alert message which is major issue.
**//index.php**
// following is ajax code in which problem occur. i think.
$(document).ready(function(){
$('#submit').click(function(){
$.ajax({
url:"store.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
**//store.php**
// following is the data base releted query
$conn = mysqli_connect("localhost", "root", "", "prag");
$chapter_name = $_POST["chapter_name"];
$class = $_POST["class"];
$subjects = $_POST["subjects"];
$sql = "INSERT INTO chapter(class_id,subject_id,name) VALUES('$class','$subjects','$chapter_name')";
mysqli_query($conn, $sql);
echo "Data Inserted";
</pre>
//HTML CODE
//Following are the input fields through which data will store.
<input type="text" name="chapter_name" placeholder="Enter the Chapter name" class="form-control name_list" />
<select name="class" id="class" class="form-control">
<option>Select Class</option>
</select>
<select name="subjects" id="subjects" class="form-control">
</select>
<button type="submit" name="add_chapter" id="submit">Add </button>
<pre>
Use below code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(e){
e.preventDefault();
$.ajax({
url:"data.php",
method:"post",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
</script>
</head>
<body>
<form method="post" id="add_name">
<input type="text" name="chapter_name" placeholder="Enter the Chapter name" class="form-control name_list" />
<select name="class" id="class" class="form-control">
<option>Select Class</option>
</select>
<select name="subjects" id="subjects" class="form-control">
</select>
<button type="submit" name="add_chapter" id="submit">Add </button>
</form>
</body>
</html>
Check PHP Code:
<?php
$conn = mysqli_connect("localhost", "root", "", "prag");
$chapter_name = $_POST["chapter_name"];
$class = $_POST["class_name"];
$subjects = $_POST["subject_name"];
$sql = "INSERT INTO chapter(class_id,subject_id,name) VALUES('$class','$subjects','$chapter_name')";
if(mysqli_query($conn, $sql)) {
echo "Data Inserted";
}
else {
echo "Data Not Inserted";
}
?>

Dynamically displaying data from select using CSS class

I am using CSS in a select box,
but my dynamic data is not displaying. :(
If I remove the class in select box area and get by id,
the data displays after choosing 'province'.
My data is shown in the Firebug console,
but not displayed in the select box 'kabupaten'/'city'.
Screenshot:
Code:
index.php
<table>
<tr>
<td>Provinsi</td>
<td>
<div class="control-group">
<div class="controls">
<select name="profinsi" class="profinsi" >
<option value="" selected="selected">-->Choose Province<--</option>
<?php $sql="select * from all_provinsi";
$rs=mysql_query($sql);
while($row=mysql_fetch_object($rs)){ ?>
<option value="<?php echo $row->id_prov; ?>"><?php echo $row->nama_prov; ?></option>
<?php } ?>
</select>
</div>
</div>
</td>
</tr>
<tr>
<td>Kabupaten</td>
<td>
<img src="loading.gif" width="10px" height="10px" id="imgLoad" style="display:none">
<select name="Kabupaten" class="kabupaten" >
<option value="" selected="selected">-->Choose City/Kabupaten<--</option>
</select>
</td>
</tr>
<tr>
<td>Kecamatan</td>
<td>
<img src="loading.gif" width="10px" height="10px" id="imgLoad" style="display:none">
<select name="Kecamatan" class="kecamatan">
<option value="" selected="selected">-->Choose Kecamatan<--</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit" name="submit" value="SUBMIT" /></td>
</tr>
</table>
<script type="text/javascript">
// Get province and send to class city/kabupaten
$("select.profinsi").change(function(){
var IDProfinsi = $("select.profinsi").val();
$("#imgLoad").show("");
$.ajax({
type: "POST",
dataType: "html",
url: "getkabupaten.php",
data: "prov="+IDProfinsi,
success: function(msg){
if(msg == ''){
alert('No Data');
}
else{
$("select.kabupaten").html(msg);
}
$("#imgLoad").hide();
}
});
});
</script>
<script type="text/javascript">
// Get city/kabupaten and send to class kecamatan
$("select.kabupaten").change(function(){
var IDKabupaten = $("select.kabupaten").val();
$("#imgLoad").show("");
$.ajax({
type: "POST",
dataType: "html",
url: "getkecamatan.php",
data: "kab="+IDKabupaten,
success: function(msg){
if(msg == ''){
alert('No Data');
}
else{
$("select.kecamatan").html(msg);
}
$("#imgLoad").hide();
}
});
});
</script>
Code: getkabupaten.php
<?php
include('koneksi.php');
$sel_prov="select * from datakabupaten where IDProfinsi='".$_POST["prov"]."'";
$q=mysql_query($sel_prov);
while($data_prov=mysql_fetch_array($q)){
?>
<option value="<?php echo $data_prov["IDKabupaten"] ?>"><?php echo $data_prov["namakabupaten"] ?></option><br>
<?php
}
?>
Code: getkecamatan.php
<?php
include('koneksi.php');
$sel_prov="select * from all_kecamatan where id_kabkot='".$_POST["kab"]."'";
$q=mysql_query($sel_prov);
while($data_prov=mysql_fetch_array($q)){
?>
<option value="<?php echo $data_prov["id_kec"] ?>"><?php echo $data_prov["nama_kec"] ?></option><br>
<?php
}
?>
If I'm reading your question right you want to have your list updated after a ajax request.
This answer Looks to cover exactly of what you need. Keypoints in the answer by "CMS" are the '.empty()' and '.append()'.
Also I don't think <br /> is necessary in between options of a select list.
EDIT 2/25/2015:
While I still feel my first answer is true, providing a link to a view that I can see whats going on a little better is good. I'm speculating at the inner workings in my answer so, my assessment is:
Consider the html pulled directly from the site:
<tr><td>Kabupaten</td><td>
<div class="selectify focus" tabindex="0" style="width: 189px;">
<div class="header">
<div class="selected" data-id="">-->Pilih Kabupaten<--</div><div class="icon"></div>
</div>
<div class="options" style="width: 189px; max-height: 290px; display: none;">
<div class="option" data-id="" data-text="-->pilih kabupaten<--">-->Pilih Kabupaten<--</div>
</div><!--endheader-->
</div>
<select name="Kabupaten" class="kabupaten" style="display: none;">
<option value="" selected="selected">-->Pilih Kabupaten<--</option>
</select>
</td></tr>
In the Ajax call this line $("select.kabupaten").html(msg); looks for a select list with the class of kabupaten. While your code does have a class and select list with that under the select list you are viewing constituting that you have 2 select lists and the one that has the class 'kabupaten' is hidden with style="display:none;"
I can only speculate if there is more going on in the background at this point. There is some obfuscated code in your template or include files but tracking down where <div class="header"> is coming from will allow you to correctly set the class '.kabupaten` on your select list.

how to change form response into ajax response?

I have a form, that uses a php file. The form lets the user:
-input 3 text fields for Title/Price/Description
-Select an image for his product
-Choose a table from the dropdown list (options are the table values)
As you see on my code after the user press the submit button, the browser redirects to another page, saying that "1 records was adder successfully".
I want it to be like after the user clicks the submit button on the form, a (javascript/ajax) messagewill appear letting him know that the records was added successfully.
Sorry for long coding, I think you might need everything.
OPEN TO ANY SUGGESTIONS
form
<div id="addForm">
<div id="formHeading"><h2>Add Product</h2></div><p>
<form id = "additems" action="../cms/insert.php" enctype="multipart/form-data" method="post"/>
<label for="title">Title: </label><input type="text" name="title"/>
<label for="description">Desc: </label><input type="text" name="description"/>
<label for="price">Price: </label><input type="text" name="price" />
<label for="stock">Quan: </label><input type="text" name="stock" />
<p>
<small>Upload your image <input type="file" name="photoimg" id="photoimg" /></small>
<div id='preview'>
</div>
<select name="categories">
<option value="mens">Mens</option>
<option value="baby_books">Baby Books</option>
<option value="comics">Comics</option>
<option value="cooking">Cooking</option>
<option value="games">Games</option>
<option value="garden">Garden</option>
<option value="infants">Infants</option>
<option value="kids">Kids</option>
<option value="moviestv">Movies-TV</option>
<option value="music">Music</option>
<option value="women">Women</option>
</select>
<input type="submit" name="Submit" value="Add new item">
</form>
</div>
insert.php (used on the form)
session_start();
$session_id='1'; //$session id
$path = "../cms/uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$table = $_POST['categories'];
$title = $_POST['title'];
$des = $_POST['description'];
$price = $_POST['price'];
$stock = $_POST['stock'];
$sql="INSERT INTO $table (title, description, price, image, stock)
VALUES
('$title','$des','$price','$path$actual_image_name','$stock')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "<h1>1 record added into the $table table</h1>";
echo '<button onclick="goBack()">Go Back</button>';
with jquery its quite simple:
Just do the following:
1st thing, remove the type="submit" in your input and give it a unique identifier like this:
<input id="submit_form" name="Submit" value="Add new item">
2nd thing, in your javascript file, do:
$(document).ready(function(){
$('input#submit_form').on('click', function() {
$.ajax({
url: 'addnew.php',// TARGET PHP SCRIPT
type: 'post' // HTTP METHOD
data: {
'title' : $('input[name="title"]').val()
},
success: function(data){
alert(data); // WILL SHOW THE MESSAGE THAT YOU SHOWED IN YOUR PHP SCRIPT.
}
});
});
})
3nd thing, in you php file:
Do the same thing but just do:
die("1 record added into the $table table")

Categories