Ajax double forms, first form with select then classic form - javascript

So I have one form in frontend. And second form in process file.
With first form i calling second form with products information.
FIRST FORM
$izmena_proizvoda = $conn->query("SELECT * FROM proizvodi");
$izmena_proizvoda->execute();
echo '<form method="POST">';
echo '<select class="form-control" name="izmena_proizvoda" id="izaberi_proizvod" onchange="izmena_proizvoda_ajax(this.value);">';
echo '<option>Izaberite proizvod</option>';
while($izmena_proizvoda_o=$izmena_proizvoda->fetch()){
echo '<option value="'.$izmena_proizvoda_o['id_sata'].'">';
echo $izmena_proizvoda_o['nazivsata'];
echo '</option>';
}
echo '</select>';
echo '</form>';
And ajax for this form
function izmena_proizvoda_ajax(val){
$.ajax({
url: "../sadrzaj/stranice/izmenaproizvoda.php",
type: 'POST',
data: {
izmena_proizvoda:val
},
success: function (response) {
document.getElementById("izmena_proizvoda_prikaz").innerHTML = response;
console.log(response)
}
});
}
In process file i have this one.
if(isset($_POST['izmena_proizvoda'])){
$izmena_proizvoda_forma = $conn->prepare("SELECT * FROM proizvodi WHERE id_sata = :id_sata");
$izmena_proizvoda_forma->bindParam(':id_sata', $_POST['izmena_proizvoda'], PDO::PARAM_INT);
$izmena_proizvoda_forma->execute();
echo '<hr>';
echo '<form method="post" action="#" id="izmena_proizvoda_update_form" class="ajax" >';
while($izmena_proizvoda_forma_o=$izmena_proizvoda_forma->fetch()){
echo'
<input type="hidden" name="slika_za_brisanje" value="'.$izmena_proizvoda_forma_o['slika'].'">
<input type="hidden" name="id_izmena" value="'.$izmena_proizvoda_forma_o['id_sata'].'">
<label for="naslov_izmena">Naziv sata</label>
<input type="text" id="naslov_izmena" name="naslov_izmena" class="form-control" value="'.$izmena_proizvoda_forma_o['nazivsata'].'">
<label for="cena_izmena">Cena</label>
<input id="cena_izmena" type="text" name="cena_izmena" class="form-control" value="'.$izmena_proizvoda_forma_o['cenasata'].'"><br>
<label for="vodootpornost">Vodootpornost</label>
<input id="vodootpornost" type="text" name="vodootpornost" class="form-control" value="'.$izmena_proizvoda_forma_o['vodootpornost'].'"><br>
<label for="zalihe">Zalihe</label>
<input id="zalihe" type="text" name="zalihe" class="form-control" value="'.$izmena_proizvoda_forma_o['zalihe'].'"><br>
<label for="pol">Pol sata</label>
<input id="pol" type="text" name="pol" class="form-control" value="'.$izmena_proizvoda_forma_o['pol'].'"><br>
<label for="opissata_izmena"></label>';
echo ' <textarea id="opissata_izmena" rows="10" name="opissata_izmena">'.$izmena_proizvoda_forma_o['opissata'].'</textarea><br>';
echo '<input type="submit" name="izmena_proizvoda_potvrda" value="Sacuvaj izmene" class="btn btn-info">';
}
echo '</form>';
}
So when i do that on frontend. works fine. But when i try to do another ajax for form2 i have a problems. I dont know how i can run a ajax for another form.
I try to put ajax code in forntend page but didnt work. Also i tryed to put ajax in process file below the form. To call both together. also didnt fork.
How I can make some trigger for ajax 2 from ajax 1 like
Ajax1: Hey ajax2 i do my job. You now have a form. When user click submit, do your job and dont refres a page.
Sorry beacuse my bad english.

You get rid of your onchange handler, keep your <form> tags and attach your event handler to all forms instead of a specific form. Then use $(this) to reference the values of the form which generates the submission event.
$("form").on("submit", function(event) {
event.preventDefault();
var data = $(this).serialize(); // Grabs all data from the form being submitted
$.ajax({
url: "../sadrzaj/stranice/izmenaproizvoda.php",
type: 'POST',
data: data,
success: function(response) {
document.getElementById("izmena_proizvoda_prikaz").innerHTML = response;
console.log(response);
// If you need to alter success handlers you can add data elements to your form HTML and reference them here
// Same is true if you need to alter submission URL or whatever
}
});
});

You need other way to assign the event to your new HTML elements.
This way assign an event to any dynamic HTML element.
$(function() {
//Assign event to input submit with name izmena_proizvoda_potvrda
$(document).on('click', 'input[name=izmena_proizvoda_potvrda]',
function(e) {
e.preventDefault();
//Ajax request
}); //end function()
})

Related

PHP jQuery HTML form insert to MySQL then stay on same page

I have a simple PHP intranet site where there is an HTML form that takes 2 input fields. I want to take the user input from the HTML form, insert the values into MySQL database, but keep the user's browser on the same page. I have a separate PHP file that does the MySQL INSERT. I have been trying to do this with both pure PHP, and with the help of jQuery, but I can't get it to work! Any help would be greatly appreciated.
Here's my HTML form (which is in a PHP file):
<form name ="form" action="" method="POST">
Claim Title: <br>
<input type="text" name="title" required>
<span class="error">* </span>
<br><br>
Claim Body: <br>
<textarea name="claim" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" name ="submit" value="Submit"/>
</form>
The PHP file that does the db processing is called db-insert.php:
<?php
require 'connect.php';
$conn = Connect();
// Claim form and sql insert variables
$title = $conn->real_escape_string($_POST['title']);
$claim = $conn->real_escape_string($_POST['claim']);
$claimInsert = "INSERT INTO claims(claim_title,claim_body,claim_type) VALUES('" . $title . "','" . $claim . "','T');";
$success = $conn->query($claimInsert);
$conn->close();
?>
The connect.php file:
<?php
function Connect(){
// Connection variables
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) or die($conn->connect_error);
return $conn;
}
?>
Finally the .js file that I've written (I use the term 'written' loosely as I obtained it from another StackOverflow page on something similar) is:
$(document).ready(function(){
$("button").click(function(){
$.get("db-insert.php", function(data, status){
alert("Data: " + data + "/nStatus: " + status);
});
});
});
I'm a bit of novice with jQuery/AJAX/related JavaScript and my PHP skills are growing but not amazing. I am using FireFox JavaScript debugger console and when I click the SUBMIT button for my form it isn't displaying anything, which makes me think it isn't processing the form data.
EDIT: I should have added this to underpin a comment made earlier in my post - I am in the early stages of dev work, please don't tell to parametrise and protect my SQL statements - I am aware of this :)
If your main goal is to do this without changing or refreshing the page, you can use Ajax and jQuery like this:
$(document).on('click', '#submit-my-form', function(){
var title = $("#title").val();
var claim = $("#claim").val();
jQuery.ajax({
type: "POST",
url: "http://your-site-url/db-insert.php",
dataType: 'json',
data: {title: title, claim: claim},
success: function(res) {
if (res)
{
alert('Hurray! Successfully done');
}
},
error: function(xhr) {
if (xhr)
{
alert('There was an error');
}
}
});
});
You can also add code to receive the insert status and process it in the return section of the Ajax code. Modify your html code by adding id tags to the inputs like this:
<input type="text" name="title" id="title" required>
<textarea name="claim" id="claim" rows="5" cols="40"></textarea>
<input type="submit" name ="submit" id="submit-my-form" value="Submit"/>
That should do it.
Use $.post() to send your data to PHP, and preventDefault() to prevent the page from reloading.
$.post() - Load data from the server using a HTTP POST request.
preventDefault() - The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
$(document).ready(function(){
$("form").on('submit', function(e){
e.preventDefault();
var data = {title: $('#title').val(), claim: $('#claim').val()};
console.log(data);
// $.post("db-insert.php", data, function(data, status){
// alert("Data: " + data + "/nStatus: " + status);
// });
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name ="form" action="" method="POST">
Claim Title: <br>
<input id="title" type="text" name="title" required>
<span class="error">* </span>
<br><br>
Claim Body: <br>
<textarea id="claim" name="claim" rows="5" cols="40"></textarea>
<br><br>
<input id="sub" type="submit" name ="submit" value="Submit"/>
</form>
Then in your db-insert.php
<?php
$title = $_POST['title'];
$claim = $_POST['claim'];
// rest of the code here
hope can help u
$("document").ready(function()
{
$("[name='submit']").click(function ()
{
sendS();
});
});
function sendS()
{
$.ajax(
{
type:"POST",
dataType:"json",
url:"php.php",
data:{title:$("[name='title']"),claim:$("[name='claim']")},
success: function(data)
{
//display or do somethg
alert(data);
},
error: function ()
{
alert("Error!");
}
});
}
<?php
$data1=$_POST["title"];
$data2=$_POST["claim"];
echo "Title : ".$data1."<br> Claim : ".$data2;
?>
Something like this
$(document).ready(function(){
$('form[name="form"]').submit( function(e){
e.preventDefault();
/*
you can put the url in the form action as normal,
its an old habit of mine, so if JavaScript is off on
the clients browser the form still works.
*/
var url = $(this).attr('action');
var iData = {
title: $('input[name="title"]').val(),
claim: $('textarea[name="claim"]').val()
};
console.log(url);
console.log(iData);
/*
Obviously you're going to need to un-comment this,
Ajax doesn't really work well on SO website
$.post(url, iData, function(data){
//do something on return
});
*/
//yea it's old school
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name ="form" action="db-insert.php" method="POST">
Claim Title: <br>
<input type="text" name="title" value="" required>
<span class="error">* </span>
<br><br>
Claim Body: <br>
<textarea name="claim" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" name ="submit" value="Submit"/>
</form>

Send php response to ajax and display result in div

I have made a simple form through which i can search the keywords and find the related output from database dynamically. The code works perfect without AJAX . But now i have applied some AJAX code to get the response on same page within a div named coupon. I am unable to get the response. I don't know where am i doing wrong. Any suggestions please. Here is the complete code.
form
<form action="" id="search_form" method="POST">
<p><input name="query" autocomplete="off" id="list_search" type="search" required class="list_search" /></p>
<p align="center"><input type="submit" id="click" name="click" class="but" value=" search" /></p>
</form>
<div class="coupons"></div>
AJAX
$("document").ready(function(){
// $(".but").click(function(event){ // here
$("#search_form").submit(function (event) {
{
event.preventDefault();
var myData={ query: $( 'input[name="query"]' ).val() };
$.ajax({
url: 'result.php',
data: myData,
type: 'post',
dataType: "html",
success: function(result){
//console.log(result);
$('.coupons').html(result);
},
error: function() {
alert('Not OKay');
}
});
});
});
result.php
$keyword = mysqli_real_escape_string($con,$_REQUEST['query']); // always escape
$keys = explode(" ", $keyword);
$sql="SELECT c.* , sc.* , sm.* ,ca.* from store_category sc INNER JOIN store_manufacture sm ON sm.sm_id=sc.store_id INNER JOIN categories ca ON ca.cat_id=sc.cat_id INNER JOIN coupons c on c.c_sc_id=sc.sc_id WHERE c.c_name LIKE '%$keyword%' OR sm.sm_brand_name LIKE '%$keyword%' OR ca.cat_name LIKE '%$keyword%' OR c.c_description LIKE '%$keyword%'";
foreach ($keys as $k) {
$sql.="OR c.c_name LIKE '%$k%' OR sm.sm_brand_name LIKE '%$k%' OR ca.cat_name LIKE '%$k%' OR c.c_description LIKE '%$k%'";
}
$result = mysqli_query($con, $sql);
$count=mysqli_num_rows($result);
if($count!=0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$res=$row['c_name'].$row['c_description'];
echo json_encode($res);
}
}
else
{
echo "no result";
}
Do not use a click event and a button does not have a submit event - use the form's submit event instead
$("#search_form").on("submit",function(e) {
e.preventDefault();
$.post("result.php?query="+encodeURIComponent($("#list_search").val()),function(data) {
$('.coupons').html(data); // you likely need to render the JSON instead here or send HTML from server
});
});
You should try with:
var myData={ query: $( 'input[name="query"]' ).val() };
So you can get back a query field on the server.
The Problem is your ajax request does have your value as key in $_REQUEST. There might be some way to handle this but it is not very intuitive.
And right you should register the submit handler on your form not your button.
$("#search_form").submit(function(event){ ... }

Sending data to server with $.ajax request

I have a simple form with 2 input:
<form name="contact" id="contact">
<input type="text" id="firstName" name="firstName"/>
<input type="text" id="lastName" name="lastName"/>
<input type="submit" value="Send"/>
</form>
On submit I want using jQuery ajax method to send data to print.php. Code looks next:
var contact=$("#contact");
contact.on("submit",function(event){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
});
I want that Print.php script simply prints sent data, but nothing is happening. Script looks next:
<?php
$fname = $_POST['fname'];
$lname=$_POST['lname'];
echo $fname;
?>
Problem is obviusly in print.php.
you need to use following.
$("form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "print.php",
dataType: "json",
data: {
fname: firstName,
lname: lastName
},
success: functon(dt) {
alert(dt);
}
});
});
There is no $subject variable anywhere.
You set the first name and last name variables properly.
To check your script's response (which will be an error), go to your console and check network, and then repsonse data.
Change $subject to $fname and it should "work"
Also add on .on() submit event handler to your jQuery AJAX call like so:
$('form').on('submit', function() {
//ajax call
});
Edit:
You made an edit and changed $subject to $name. There is no $name variable either.
You do not need the JSON type on the ajax form. And include the preventDefault to avoid natural action(page refreshes when submitting)
contact.on("submit",function(event){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
event.preventDefault();
$.ajax({
type:"POST",
url:"print.php",
data:{
fname:firstName,
lname:lastName
}
});
});
It looks like your problem is that your HTML form doesn't know where to go ounce the submit happens and that is why nothing is happening. You need to tell your HTML form to run javascript.
You could link your HTML form to your javascript by using JQuery's .submit() method document here http://api.jquery.com/submit/
This will trigger your javascript to run once it is submitted if you wrap all your javascript around it.
$("form").submit(function( event ) {
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
});
Also you could give your HTML form an action so it knows what to do when the form is submitted.
Below we are saying run myFunction() when this form is submitted, we will then need to wrap all your javascript in myFunction().
<form name="contact" action=“javascript:myFunction();”>
<input type="text" id="firstName" name="firstName"/>
<input type="text" id="lastName" name="lastName"/>
<input type="submit" value="Send"/>
</form>
Your javascript will look like this
function myFunction(){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
}
Once you get that far you will want to fix your php. The way you have it now $name is empty and won't print anything. You will want to fill the variable in before you echo it out. I am assuming you want $name to contain a concatenated version of $fname and $lname.
<?php
$fname = $_POST['fname'];
$lname=$_POST['lname'];
$name = $fname . ' ' . $lname;
echo $name;
?>
That should work for you.

Using AJAX to post form data to PHP page

I am simply trying to use the data submitted in a search form to query the database and bring back results similar to the search. My form looks like this:
<div id="searchform">
<form method="get">
<form id="submitsearch">
<input id="shop" name="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="submit" value="Go"/>
</form>
</form>
<div id="searchresults">
</div>
</div>
the Javascript I've got is:
$("#submitsearch").submit(function(event) {
event.preventDefault();
$("#searchresults").html('');
var values = $(this).serialize();
$.ajax({
url: "external-data/search.php",
type: "post",
data: values,
success: function (data) {
$("#searchresults").html(data);
}
});
});
return false;
I have also tried...
$("#submitbutton").click(function(){
var form_data = $("#submitsearch").serialize();
$.ajax({
url: "external-data/search.php",
type: 'POST',
data: form_data,
success: function (data) {
$("#searchresults").html(data);
}
});
return false;
});
And this seems to work slightly as it shows results, the first doesn't do anything. It's not sending the data to the PHP page but the PHP I've got is:
<?php
$str_shops = '';
$shop = $_POST['form_data'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE name LIKE '%$shop%'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<strong>" . $row['name'] . "</strong><br>" .
$row['address'] . "<br><br>";
}
mysqli_free_result($result);
echo $str_shops;
mysqli_close($db_server);
?>
Any help would be greatly appreciated! Thanks in advance.
You have two form tags. This won't work. You want one form tag with two attributes
<form method="get">
<form id="submitsearch">
to
<form method="get" id="submitsearch">
you can do it without using html form.
first you call the php page and then display a data within html.
this is what I do?!
<div>
<input id="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="button" value="Go"/>
</div>
<div id="searchresults">
</div>
<script type="text/javascript">
$(function() {
$("#submitbutton").click(function(){
try
{
$.post("root/example.php",
{
'shop':$("#shop").val().trim()
}, function(data){
data=data.trim();
$("#searchresults").html(data);
// this data is data that the server sends back in case of ajax call you
//can send any type of data whether json or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>

Jquery Ajax get request to separated urls in the same function

I have the following form:
<p>Choose your page:</p>
<form id="ChartsForm" onsubmit="return submitForm();">
<select name="accmenu" id="accmenu" style="width:300px;">
<?php
$user_accounts = $facebook->api('/me/accounts','GET');
foreach($user_accounts['data'] as $account) {
?>
<option data-description="<?php echo $account['category'] ?>" data-image="https://graph.facebook.com/<?php echo $account['id']; ?>/picture" value="<?php echo $account['id'] ?>"><?php echo $account['name'] ?></options>
<?php
}
?>
</select>
<p>Choose your insights:</p>
<div class="chartsbuttons">
<input type="submit" name="submit" value="Daily new likes">
<input type="submit" name="submit" value="Daily unlikes">
<input type="submit" name="submit" value="Daily page views">
</div>
</form>
which contain a select and for the moment three test submit buttons called: "Daily new likes", "Daily unlikes" and "Daily page views". I use an ajax call like this defined in the submitForm function:
function submitForm() {
$.ajax({type:'GET', url: 'check.php', data:$('#ChartsForm').serialize(), success:
function(response) {
alert(response);
}});
return false;
};
to check for now if the selected option value is send to the php script and alert me the response which must be the facebook page id. Here is the php script:
<?php
echo $_GET['accmenu'];
?>
This is working fine but I will create a php file for each of the submit button to send request to. Example: if I press "Daily new likes" it will send a get request to newlikes.php and if I press "Daily page views" it will send a get request to pageviews.php. I have defined just one form and I would like to keep it that way. How is possible to send to a specific url with JQuery Ajax based on the submit buttons? I have to create a new JavaScript function for each of the inputs? What about the form, I have to create new ones? If I create new ones the select will not be available to each of them right? I really need guidance because I am stuck at this issue. Any help is appreciated.
With PHP, you should not need to set up 3 separate files to perform the requests unless you really want to. You should be able to use your existing function with a few modifications to perform the heavy lifting, but here is a modification that calls a different file based on parameter specified:
function submitForm(action) {
$.ajax({type:'GET', url: action + '.php', data:$('#ChartsForm').serialize(), success:
function(response) {
alert(response);
}});
return false;
};
Next you would assign some attribute to the buttons, and bind the click event to trigger your function:
HTML
<input type="submit" name="submit" value="Daily new likes" data-action="new_likes">
JavaScript
$("input[type='submit']", "#ChartsForm").on("click", function(e){
e.preventDefault();
submitForm($(this).attr("data-action"));
});

Categories

Resources