Jquery Ajax get request to separated urls in the same function - javascript

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"));
});

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>

Ajax double forms, first form with select then classic form

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()
})

Correct method of sending a variable from a html form to a php function via ajax

I'm coding a voting system for multiple uploads; each uploaded image is in a foreach statement with a form attached to each, with three buttons to vote up, down or none, each associated with an INT in my mysql database.
I got it to work by submitting the form data straight to the PHP function that 'UPDATE's the database. To avoid a page refresh, I attach ajax. I got the ajax to send the two variables needed for the PHP function to update the correct "image" row and INT in the db.
Question: The ajax function works, but the PHP function doesn't seem to update.
SUSPECTED PROBLEM: I'm pretty sure it's the way I'm defining the variables in ajax that I want to pass, I was trying to grab the ID of the "image" it's handling, but I don't know how to translate this data to the PHP function so that it UPDATE's correctly.
Here's the form, javascript, and php:
// IMAGE, and rest of foreach above this, and ending after form
// This form only shows one button, there are three, each
// I'll treat the same once I get one to work
<form action="feed.php" method="post" id="vote_form_1">
// If js isn't turned on in broswer, I keep this
// hidden input, to send unique ID
<input type="hidden" name ="input_id"
class="input_id" value="<?php echo $row['id']; ?>"/>
<input type="submit" name="post_answer1" onclick="sayHi(event);"
class="answer_L" id="<?php echo $row['id']; ?>"
value="<?php echo $row['post_answerL']; ?>"/>
</form>
// end of foreach
//AJAX
<script type="text/javascript">
function sayHi(e) {
var input_id = $(e.currentTarget).attr('id');
var post_answer1 = $("input[name='post_answer1']");
jQuery.ajax({
type: 'POST',
url: 'feed.php', //name of this file
data:input_id,post_answer1,
cache: false,
success: function(result)
{
alert ('It worked congrats');
}
});
e.preventDefault();
</script>
// PHP VOTE UPDATE FUNCTION
<?php>
if(isset($_POST['post_answer1'],$_POST['input_id'])){
$current_id = $_POST['input_id'];
$vote_1 = "UPDATE decision_post set " .
"post_answer1=post_answer1+1 WHERE id = '".$current_id."' ";
$run_vote1 = mysqli_query($conn2, $vote_1);
if($run_vote1){ echo 'Success'; }
}
?>
Here a simple answer, just serialize all your form data!
$('form').submit(function(){
$.post('feed.php', $(this).serialize(), function(data){
console.log(data);
}, 'json');
return false;
});
var post_answer1 = $("input[name='post_answer1']").val();

How to post data without a form

Good day sir/ma'am I am a new programmer, I would like to ask how to post data like the functionality of form that when submitting the form the URL in action will display using javascript.
"WITHOUT USING A FORM" or using xmlHTTP that not return to main page
sample is
HTML
<input type="button" value="revise" onclick="revisetask(<?php echo $id; ?>)">
JS
function revisetask(idtask)
{
//In this function sir i would like to post here
}
Im very sorry if my english is too bad.. thanks in advance :D
You can use javascript for submitting the values of input boxes,
to do so,
write a javascript function which will read all your input boxes values into javascript variables,
Prepare a URL, and call that URL using window.location.href
function SubmitMyForm
{
var Firstname = document.getElementbyId('FirstName').value;
var Lastname = document.getElementbyId('LastName').value;
var URL="myDBoperations.php?firstname="+Firstname+"&lastname="+Lastname;
window.location.href= URL;
}
On the operations form you will receive these value in GET.
Hope this will help you.
U can use ajax for this. U don't need a form for ajax post, and it won't refresh the page too.
Below is an example code
<input type="text" id="test_name" />
<input type="button" value="Submit" obclick="save_this()" />
<script type="text/javascript">
function save_this(){
var text = $('#test_name');//stores te value in text field
$.ajax({
url: 'http://example.com/test.php',//your URL
type: 'POST',
data: { text: text },
success: function(data){
alert(data);
}
});
}
</script>
test.php
<?php
echo $_POST['text'];
As I've seen in this code:
<input type="button" value="revise" onclick="revisetask(<?php echo $id; ?>)">
I assume and believe that the reason why you don't want to use form because you want your $id to be submitted through javascript/jquery. But alternatively, you could just do it this way:
HTML:
<form method = "POST" action = "updatetask.php">
<input type = "hidden" value = "<?php echo $id; ?>" name = "taskid" id = "taskid"/>
<input type = "submit" value = "UPDATE" name = "updatebutton">
</form>
PHP:
<?php
$taskid = $_POST['taskid'];
?>
In the above code I just set the type hidden and which contains the value of your $id in which would be post in your Php file.
UPDATE:
If it still doesn't fit to what you want then you could just have this other alternative which will be using the GET method: <a href = "updatetask.php?id='<?php echo $id; ?>' REVISE </a>"
That's the only option you have. and if you don't want to show the id in your url then you could just use URL Rewriting (refer to this link: https://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/)
Hope this helps.

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.

Categories

Resources