How to: PHP Ajax page update - javascript

I have a input field and 2 buttons to add/remove words from a database.
I'm using 3 php files. The main file which is outputting the html code, the addtag.php, which can add a word and the removetag.php file which can remove a word.
I want to call addtag.php when the plus is clicked and send the content of the input field. removetag.php should be called when clicking on the minus symbol.
addtag.php and removetag.php should run in the background and the page should only update <tagboxtxt>.
The elements below are listed multiple times on the same page. There are different links and values but the elements are the same.
<!-- language-all: lang-html -->
<bdiv>
<div>
<img src="001.jpg" />
</div>
<tagbox>
<form>
<input type="text" id="tag" name="tag">
<input type="hidden" id="hash" name="hash" value="23547">
<button class="button" type="submit" formaction="addtag.php" method="GET">+</button>
<button class="button" type="submit" formaction="removetag.php">-</button>
</form>
<tagboxtxt>foo bar</tagboxtxt>
</tagbox>
</bdiv>
<bdiv>
<div>
<img src="002.jpg" />
</div>
<tagbox>
<form>
<input type="text" id="tag" name="tag">
<input type="hidden" id="hash" name="hash" value="67889">
<button class="button" type="submit" formaction="addtag.php" method="GET">+</button>
<button class="button" type="submit" formaction="removetag.php">-</button>
</form>
<tagboxtxt>bla huh</tagboxtxt>
</tagbox>
</bdiv>
I know that Ajax is the way to go, but I cant get it working.
I've tried to use function below. How should I use that in my example?
function addtag () {
$.ajax({
url:"addtag.php",
type: "POST",
success:function(result){
alert(result);
}
});
}

You're missing the javascript that captures the click on the 'plus' button, and calls your ajax function. Try pasting this javascriptsnippet below your function:
//Execute on page ready
$(function() {
$('body').on('click', '.plusSign', function() {
addTag();
});
});

i would call a js file and have it reference the two add and remove php files--i have mocked this up for you first in the main file that outputs the html put this
<head>
<script type='text/javascript'></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.0.min.js"></script>
<script type="text/javascript" src="tag.js"></script>
</head>
<tagbox>
<input type="text" name="tag">
<div class="cssCircle plusSign" id="plus">+ </div>
<div class="cssCircle minusSign" id="minus" style="position:absolute; top:20px; left:25px;">–</div>
</tagbox>
This will allow you to call the js file to run ajax. the js file named tag.js should look like this
$(document).ready(function() {
$("#plus").click(function() {
$.ajax({
type: "POST",
url: "addtag.php",
dataType: "json",
data: ({word: $("#tag").val(),}),
success:function(result){
alert(result);
}
});
});
$("#minus").click(function() {
$.ajax({
type: "POST",
url: "removetag.php",
dataType: "json",
data: ({word: $("#tag").val(),}),
success:function(result){
alert(result);
}
});
});
});
this should accomplish what you need

Related

Form submit only one value with AJAX passing form data to PHP in the same page

I need to pass a single value from my form to my php in the same page. It´s probably not an option to create another .php file and take the code there since there´s a lot going on.
This is the part of the code I need to fix, currently it only works when the code is on another file, since the $_POST is not messing around with other parts of the code. Specifically I need to manage to pass the 'client' or the 'empre' from the form alone to the php.
HTML
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
if($(".cliente").click(function() {
var name = $("#client").val();
var dataString = 'client='+ name;
}))else if($(".empresa").click(function() {
var name = $("#empre").val();
var dataString = 'empre='+ name;
}));
$.ajax({
type: "POST",
data: dataString});
});
</script>
</head>
<body>
<form>
<input name="client" type="text"><br>
<input class="cliente" type="submit" value="Buscar cliente"/><br>
<input name="empre" type="text"><br>
<input class="empresa" type="submit" value="Buscar empresa"/><br>
</form>
//PHP HERE
//HTML AGAIN
</body>
</html>
PHP (same page, just separating for readability)
if(isset($_POST['empre'])){
//DB QUERY
}
elseif(isset($_POST['client'])){
//DB QUERY
}
You can combine and send it in same AJAX call as below, and in PHP you can do:
$parameters = json_decode($_POST['params']);
$parameters would have all the variables sent in that AJAX call.
I would recommend, not to use same page for your AJAX. You should keep it in separate file. That would make code much cleaner, lighter, readable and easy-to-tweak.
$(function() {
$(".cliente, .empresa").click(function(e) {
e.preventDefault();
var paramsToSend = {};
if ($(this).hasClass('client'))
paramsToSend['client'] = $('form[name="client"]').serialize();
else
paramsToSend['empre'] = $('form[name="client"]').serialize()
$.ajax({
url: 'index.php' //assuming this is index.php (same page)
type: "POST",
data: {
params: JSON.stringify(paramsToSend)
},
success: function(data) {},
failure: function(error) {}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="client">
<input name="client" type="text" value="some value"><br>
<input class="cliente" type="submit" value="Buscar cliente" />
</form>
<form name="empre">
<input name="empre" type="text" value="some value"><br>
<input class="empresa" type="submit" value="Buscar empresa" />
</form>
//PHP HERE //HTML AGAIN
Why not use separate forms to process the data? (Your PHP logic mentioned will work with this proposed solution)
$(function() {
$(".cliente").click(function(e) {
e.preventDefault();
alert('Going to post data for client, check the console log now');
$.ajax({
url: $('form[name="client"]').attr('action'),
type: "POST",
data: $('form[name="client"]').serialize(),
success: function(data){
console.log(data);
},
failure: function(error){}
});
});
$(".empresa").click(function(e) {
e.preventDefault();
alert('Going to post data for empre, check the console log now');
$.ajax({
url: $('form[name="empre"]').attr('action'),
type: "POST",
data: $('form[name="empre"]').serialize(),
success: function(data){
console.log(data);
},
failure: function(error){}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="client" action="https://someurl.com/fileto.php">
<input name="client" type="text" value="some value"><br>
<input class="cliente" type="submit" value="Buscar cliente"/>
</form>
<form name="empre" action="https://someurl.com/fileto.php">
<input name="empre" type="text" value="some value"><br>
<input class="empresa" type="submit" value="Buscar empresa"/>
</form>

Js edited div content disappears

Hi I'm appending content to the div, after an ajax call success. But quickly the appended text disappears. Why that happens, could you please help?
My js is kept in another file and js is called via a button click event.
HTML:
<html>
<head> </head>
<body>
<script type='text/javascript' src='jq/jquery.js'></script>
<script type='text/javascript' src='js/bootstrap.min.js'></script>
<script type='text/javascript' src='js/script.js'></script>
<br/>
<form name="form">
<input type="text" id="uname" name="uname">
<input type="submit" onclick="postData()" id="data-submit">
</form>
<br/>
<br/>
<br/>
<br/>
<div id="feedback"></div>
<script type='text/javascript'>
//this sometimes show errors on google chrome.
//$(document).ready(function(){});
</script>
</body>
</html>
This is the full content of my js file
function postData(){
var uname=$('#uname').val();
$.ajax({
url:'checkempcode.php',
data: {name: uname},
type: "POST",
async: false,
success: function(data){
window.alert('Checking');
$('#feedback').html(data);
$( "#feedback" ).append( "<p>Test</p>" );
}
});
}
The page get reloaded since the submit buttons are submitting your form. Try changing the button type from submit to button
<input type="button" onclick="postData()" id="data-submit"/>
OR
Add return false in onclick function;
<input type="submit" onclick="postData(); return false;" id="data-submit"/>
You should just add event.preventDefault() to you function to prevent form from submiting :
function postData(){
event.preventDefault();
var uname=$('#uname').val();
$.ajax({
url:'checkempcode.php',
data: {name: uname},
type: "POST",
async: false,
success: function(data){
window.alert('Checking');
$('#feedback').html(data);
$( "#feedback" ).append( "<p>Test</p>" );
}
});
}
Hope this helps.

jQuery .val() not working on hidden fields added with .html()

I have an html form that loads the main portion of a document, postload an ajax request goes off and gets an xml file that is parsed out to create 'sub' forms which can be updated/submitted. This is the form 'preload'
<html>
<head>
<script src="jquery.js">
<script src="jquery.forms.js">
<script>
$(document).ready(function () {
//Script to execute when form is loaded
loadOrder(unid);
});
</script>
</head>
<body>
<form id="mainform" name="main" method="post" action="whatever">
<input type="hidden" id="unid" name="unid" value="123" />
</form>
<div id="orderForms">
</div>
</body>
</html>
Here is the form post load :
<html>...
<div id="orderForms">
<form id="order_1" name="order" method="post" action="whatever">
<input type="hidden" id="pid_1" name="pid" value="123" />
<input type="hidden" id="unid_1" name="unid" value="456" />
</form>
<form id="order_2" name="order" method="post" action="whatever">
<input type="hidden" id="pid_2" name="pid" value="123" />
<input type="hidden" id="unid_2" name="unid" value="789" />
</form>
</div>
</body>
</html>
JS code:
function loadOrders(unid){
var rUrl = "url";
$.ajax({type: "GET", url: rUrl, async: true, cache: false, dataType: "xml", success: postLoadOrders}) ;
}
function postLoadOrders(xml){
nxtOrder = 1;
var html="";
$('order',xml).each(function() {
// parses the xml and generates the html to be inserted into the <div>
});
$("#orderForms").html(html);
}
This all works, the main form loads, the 'hidden' forms in the <div> are written in. The trouble happens when I put a button on the main form that does this...
function submitOrder(){
$("#pid_1").val('555');
$("#order_1").formSerialize();
$("#order_1").ajaxSubmit();
}
If I alert($("#pid_1").val()) prior to the .val('555') it shows the original value, when I alert after, it shows the new value, however it submits the original value, and if I open the html in firebug the value isn't showing as changing.
If I put a hidden field into the main form, that exists when the document loads and change its value, not only does the new value post, it also shows as being changed when examining the source.
Any ideas?
$('order',xml).each(function() {
});
this is not Object in JQuery
You can edit:
$('[name=order]',xml).each(function() {
});

PHP Form with Button

I have some experience in JAVA GUI programming and I want to achieve the same in a PHP form.
Situation: I want to have a php form with a submit button. When the button is pressed an ActionEvent should be called to update another part of the form.
How to implement such a feature with HTML,PHP,JAVASCRIPT ?
Load latest version of jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
HTML code:
<form>
<button type="button" class="formLoader">Click button</button>
<div id="formContentToLoad"></div>
</form>
jQuery code:
<script type="text/javascript">
$(function(){
$(".formLoader").click(function(){
$("#formContentToLoad").load("scriptToRun.php");
});
});
</script>
Whatever markup you need to update in the form, can be put into scriptToRun.php
Use jQuery
Javascript
$(document).ready(function() {
$(".myForm").submit(function() {
$.ajax({
type: "POST",
url: "myForm.php",
data: $(this).serialize(),
success: function(response) {
// todo...
alert(response);
}
})
})
});
Html
<form method="POST" class="myForm">
<input type="text" id="a_field" name="a_field" placeholder="a field" />
<input type="submit" value="Submit" />
</form>
PHP
<?php
if(isset($_POST)) {
$a_field = $_POST["a_field"];
// todo..
}
If you want to use PHP and HTML to submit a form try this:
HTML Form
<form action="" method="post">
<input type="text" placeholder="Enter Name" name="name" />
<input type="submit" name="sendFormBtn" />
</form>
PHP
<?php
if(isset($_POST["sendFormBtn"]{
$name = isset($_POST["name"]) ? $_POST["name"] : "Error Response Here";
//More Validation Here
}

Submit jQuery ajax Form with multi buttons and PHP

here is my problem:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<form id="roomform" action="room.php" method="POST">
<button name="room" value="Room01">IMG01</button>
<button name="room" value="Room02">IMG02</button>
<button name="room" value="Room03">IMG03</button>
<button name="room" value="Room04">IMG04</button>
<button name="room" value="Room05">IMG05</button>
<button name="room" value="Room06">IMG06</button>
<button name="room" value="Room07">IMG07</button>
<button name="room" value="Room08">IMG08</button>
<button name="room" value="Room09">IMG09</button>
<button name="room" value="Room10">IMG10</button>
</form>
<script type="text/javascript">
var frm = $('#roomform');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</body>
</html>
PHP using $_POST['room'] to get the room name Room01-Room10(Room100 maybe?) and doing something special.
It works good.
Now I need to do this using Ajax. Above code seems ok, but I cannot get any data(Room01-Room10) from it.
then I found this:
<form action="/vote/" method="post" class="vote_form">
<input type="hidden" name="question_id" value="10" />
<input type="image" src="vote_down.png" class="vote_down" name="submit" value="down" />
<input type="image" src="vote_up.png" class="vote_up" name="submit" value="up" />
</form>
$(".vote_form").submit(function() { return false; });
$(".vote_up, .vote_down").click(function(event) {
$form = $(this).parent("form");
$.post($form.attr("action"), $form.serialize() + "&submit="+ $(this).attr("value"), function(data) {
// do something with response (data)
});
});
but it seems not suitable to my case, my all buttons with same name="room" for $_POST['room'] and no class.
and this not works:
$(function() {
$('input[name=room]').click(function(){
var _data= $('#roomform').serialize() + '&room=' + $(this).val();
$.ajax({
type: 'POST',
url: "room.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
return false;
});
});
anyone know how to solve this problem?
Your (last) code is not sending AJAX requests because you attached the handler to the wrong input selector. Your buttons are button elements, not input elements. This should work:
$('button[name=room]').click(function() { ...
Edit:
Your first code isn't working because your buttons are just buttons. You have to add the type attribute to let your form know you're pressing a submit button: <button type="submit"...>
The serialize() method does not collect the data from a button element. Take a look to the documentation on this link: https://api.jquery.com/serialize/. In your code I would assume that your data object is empty.
Also if you post several form controls (serialized) , they should have different name attributes.

Categories

Resources