Suppose all forms in your application has this structure:
<div id="result_messages"></div>
<form action="/action">
<!-- all the form -->
</form>
A submit button for this form looks like this:
<input type="button" onclick="$.post( '/action', $(form).serialize(), function (data) {
$('#result_messages').html( data ); // At this point the 'data' is an standard HTML with a message
});" />
BUT, But not always the response is a message... how to detect when data is a message or not??????:
<input type="button" onclick="$.post( '/action', $(form).serialize(), function (data) {
if (isMessage( data ))
$('#result_messages').html( data );
else
doActionWith( data );
});" />
Using JSON maybe a solution:
{ response_type : 'message', data: 'all_data_here' }
{ response_type : 'nomessage', data: 'all_data_here' }
Other solution is to put a special STRING at the begin of data:
<!--message--><ul><li>form was processed</li></ul>
Have you other ideas? what do you think about this solutions?
what do you think about this solutions?
<input type="button" onclick="$.post( "/action", $(form).serialize(), function (data) {
That will fall over. The quote before /action will terminate the onclick attribute value
Inline JS is nasty. Bind your event handlers from external scripts.
If JS is not available, this won't work. Write a form that works (with a regular submit button) and then progressively enhance with JS.
form is undefined, that should be this.form
/action is repeating yourself. Write more reusable code: this.form.action
Using JSON maybe a solution
Yes. Use a structured data format instead of a blob of code to shove into the page.
What are the options, other than simple html output? json?
If so, you can send an object back and check it in the callback.
Related
I Have very simple PHP html code for change my website language and I need to use Ajax to not-reload after select language but honestly I never used ajax before and I don't have any idea how to use that.
I google it and found some code but I fail.
HTML:
<form action="" method="get">
<input type="submit" value="per" id="per" name="per">
<input type="submit" value="eng" id="eng" name="eng">
</form>
PHP :
function lang()
{
$lang = 'per';
if (isset($_GET['per']))
return $lang = 'per';
else
return $lang = 'eng';
}
Ajax:
$.ajax({
type: "GET",
url: 'index.blade.php',
data: {name: 'per'},
success: function(data){
alert(data);
window.location.reload();
}
});
All Code's are at one page named
index.blade.php
php code working fine just need for ajax to not-reload page when I click buttons
Try this:
html:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<form action="" >
<button type="submit" id="button1">Click
</button>
</form>
<script type="text/javascript" src="1.js"></script>
<!--<script type="text/javascript" src="2.js"></script>-->
</html>
js:
document.getElementById("button1").addEventListener("click",function(e){
//alert("hello");
e.preventDefault(); //a button's default behavior is to submit the form which this function prevents
$.ajax({
url:"example.php",
success:function(result){
alert(result);
location.href=location.href; //here you can specify where you want to get your ajax call to redirect to.
}
})
return false;
})
php file:
<?php
echo "Hello world";
?>
Hope this is what you are looking for!
I suggest studying a few tutorials on Ajax, I will try to briefly touch the subject here.
First of all, when doing Ajax, you basically call a web page or script (an actual url, not a function written in PHP). The result that you get (HTML, XML, CSS, JSON, JPG), you can use in your code, insert ii in the DOM, change the document, etc.
In my opinion, changing the language is a site-wide action that should probably be implemented as a normal call. Genearaly, if you change the language, then the whole page should be translated, from the top (title) to the last bit of text down before the closing body.
If you just need to change a small portion of the web page, please see the URL
jQuery get
The page uses an example
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
that performs what you want, just change the url. Hope I helped a bit.
Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!
I'm using JQuery Form Plugin for AJAX file uploader.
The (html) form is created dynamically, and looks like this:
<form id="formUpload" action="fileReceiver.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload" multiple>
<input type="submit" value="Upload File to Server">
</form>
Because, the form is created dynamically, I'm using jquery on(). I also need to send a few variables, I'm using data options from the plugin.
The Javascript looks like this:
$(document).on("submit", "form#formUpload", function() {
$(this).ajaxForm({
data: { someVariable : 'someValue' },
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
I think the form is binded correctly, I could call/alert something from the ajaxForm (jquery form plugin) function through beforeSend or Success options.
Now, the problem is the PHP couldn't get the data I posted in the Javascript.
My PHP is simple like this:
<?php
echo $_POST["someVariable"];
?>
It gives me error "Notice: Undefined index: someVariable blah blah blah"
Any advice? Thx :)
Try adding some variables in hidden input inside form
<input type="hidden" name="someVariable" value="someValue">
and remove $(document).on("submit",... event
You can try
var input = $("<input>").attr("type", "hidden").attr("name", "someVariable").val("someValue");
$('#formUpload').append($(input));
this links may help you
http://www.malsup.com/jquery/form/progress2.html
http://www.malsup.com/jquery/form/file-echo2.php.txt
Well, in case your form is being added dynamically then you'd have to use DOMNodeInserted event instead of submit. That way, whenever there's some addition in DOM your form will be attached to form plugin.
You can replace your function with following --
$(document).on("DOMNodeInserted", "form#formUpload", function() {
$(this).ajaxForm({
data: { someVariable : 'someValue' },
complete: function(xhr) {
// do something
}
});
});
But remember, using DOMNodeInserted event will fire that method whenever there's addition of any kind into DOM. So just put what is essential ( in this case form plugin init for #formUpload ) .
Try to locate if you already added the jQuery Form Plugin...
<script src="jquery.form.js"></script>
Your syntax is definitely correct according to http://malsup.com/jquery/form/#options-object
I have a page where users fill out $_GET data for some options. I'd like to pass these $_GET variables using AJAX to a .php script. But my issue is how do I pass those $_GET variables they filled out so far, without refreshing the page?
Here is my code so far.
$.ajax({
type: "GET",
url: "serverside script to process on data",
data:{name:youwant}, // Here is where I want to take what the user has filled out so
// far, and place it here all without refreshing the page
success: function(data){
alert("return here if success")
}
})
First of all, drop this task into small ones:
1) Get/process variables in JavaScript
2) Send them to PHP
3) Parse/handle the ones
4) Depending on result send respond back to JavaScript
5) Handle that respond and display a message to user
Take a look at this example,
Let's assume that jquery.js is loaded.
Assume that we want to send the values of the inputs we have - email and password.
<script type="text/javascript">
$("#Send").click(function(){
$.ajax({
type : "GET",
//Look carefully:
data : {
// it'll be PHP vars // This is JS vars
email : $("#email").val(),
password : $("#password").val()
},
success : function(respondFromPHP){
alert(respondFromPHP);
}
});
});
</script>
<input type="text" id="email" />
<input type="password" id="password" />
<br />
<button id="Send">Send to php</button>
In your php script, just handle vars you get, like this:
<?php
print_r($_GET); // will print smth like Array("email" => "foo", "password" => "bar")
// Then create function so that you can simplify handling of the vars.
// Like this:
function validate_password($password){}
function validate_email($email){}
I don't know your code, but you can have a form, but instead of submit it, you put a onsubmit method to a javascript function. In that function you gather all variables and pass it through ajax.
Example: <form name="form1" method="get" onSubmit="return send()">
<script>
function send() {
$.ajax(...);
return false;
}
</script>
You can use seralize function to send in $.ajax data field
Finally got my domain checker working. Now the question is I have a form (search-domains) when user types and submits at the moment it passes the query to process.php and that out puts:
echo "$Domain is/isn't available"
What I want is this to return on my results page (the results page also has a search form on it so if someone searches there it would display on same page). At the moment when user clicks it passes http://example.com/process.php?domain=domain.com(etc...).
What i think i need is Ajax to pull this url before it goes to process.php then ajax runs the query process sends result back to ajax an it outputs on the results page. Also I have another php script which displays the domain with different tlds and displays id they are available or not. So i also need ajax to run this and display aswell.
I am very new to ajax but looking for tutorials but most of them are for displaying success messages after contact forms and the like. If someone could point me in the right direction id much appreciate it.
EDIT
This is what i have but itsd still re-directing me to process.php
HTML
<form method="get" id="form">
<input type="text" class="searchdomains" onclick="if (this.value =='Domain Name Search...'){this.value=''}" value="Domain Name Search..." name="domain" id="search-domain-input">
<input type="image" src="<?php bloginfo('template_url'); ?>/inc/img/btn_up_search.png" class="search" name="Search" id="Submit">
</form>
JQuery
$.ajax(
{
type: 'GET',
url : "http://example.com/process.php?domain=",
// here you pass js object in convention: { 'query_string' : 'its value' }
data : { 'domain' : $('#search-domain-input').val() },
success: function (data) {
$("#results").html(data);
}
}
);
PHP
if(isset($avail)){
echo '<p>'.$avail.' is available to be registered</p>'
} else {
echo '<p>'.$avail.' is taken register with us for price</p>'
}
Thanks
Joe
in jquery (http://jquery.com/) you can make ajax requests by using the function :
$.ajax(
{
url : "url to fetch",
success: function (data) {
// data is variable that is returned from server as HTML by default, or you can use JSON format
$("#content").html(data);
}
}
);
If you dont want to use jquery javascript library, you need to create xmlhttprequest object and make helper functions for it, which i do not recommend, since jquery can be used for more stuff than just ajax calls.
EDIT :
#comment
simply create process.php where you will accept "domain" as query string - which will check if the domain exists, if not it should echo <p>'$result.'is/isn't available</p>, than in $.ajax({...}); pass that url and "data" will be available to you.
To pass GET params with $.ajax() you can use the following setting:
$.ajax(
{
type: 'GET',
url : "url to fetch",
// here you pass js object in convention: { 'query_string' : 'its value' }
data : { 'domain' : $('#domain_name_input_field').val() },
success: function (data) {
// data is variable that is returned from server as HTML by default, or you can use JSON format
$("#content").html(data);
}
}
);