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.
Related
So, basicly what I'm trying to achieve:
In index.php
I would enter products code to search for products information and it's images (that query is run in open_first.php, called via ajax post request).
It works just perfect..
When open_first.php is loaded, it displays me some images I can select from (when I click on the image, it's relevant checkbox get's checked containing the image id).
This works too, just fine.
BUT,
If I enter a code in the field: "productCodeCopy" and click on "confirmCodeCopy" -button it reloads the whole page, I mean index.php and everything I've entered is lost and I'm back in the starting point again. I don't understand why it does so. I suppose it has something to do with the fact, that the second ajax request is made from a dynamically created page (open_first.php)?? Do I miss something I should POST too?? Or what's the problem, this is really frustrating me since I've tried to fix this for hours now.
Note:
Jquery is loaded in index.php, open_first.php and open_second.php, I've just ignored that to keep the code simpler.
FILE: index.php (the "starting point")
<!-- head -->
<script type="text/javascript">
$(document).ready(function() {
$("#confirmCode").on('click', function(){
var productCode = $("#productCode").val();
$.ajax({
url: 'open_first.php',
type: "POST",
data: ({code: productCode}),
success: function(data){
$("#found").html(data);
},
error: _alertError
});
function _alertError() {
alert('error on request');
}
});
});
</script>
<!-- body -->
<input type="text" class="textfields" id="productCode" name="productCode" value="YT-6212">
<input type="button" class="admin-buttons green" name="confirmCode" id="confirmCode" value="Search">
<div id="found"></div>
FILE open_first.php
<script type="text/javascript">
$(function() {
$("#foundImage").on('click', function(){
$('#foundImage').toggleClass("foundImage-selected foundImage");
var myID = $('#foundImage').data('image-id');
var checkBox = $('input[id=selectedImages-'+myID+']');
checkBox.prop("checked", !checkBox.prop("checked"));
});
$("#confirmCodeCopy").on('click', function(){
var checkedItems = $('input:checkbox[name="selectedImages[]"]:checked');
// this code here reloads the whole page / view (as in "index.php")
$.ajax({
url: 'open_second.php',
type: "POST",
data: ({checked: checkedItems, copyTo: productCodeCopy, code: "<?php echo $_POST['code']; ?>"}),
success: function(data){
$("#copyToProducts").append(data);
},
error: _alertError
});
/*
// the code below runs just fine when I hit the button "confirmCodeCopy"
alert('Fuu');
return false;
*/
});
function _alertError() {
alert('error');
}
});
</script>
<!--BODY-->
<!-- these are dynamically generated from php, just to simplify we have checkbox that contains value "1" to be posted in ajax -->
<div class="foundImage" id="foundImage" data-image-id="1"><img src="image.jpg"><input type="checkbox" id="selectedImages-1" name="selectedImages[]" value="1" style="display: none;"></div>
<label for="productCodeCopy">Products code</label>
<input type="text" class="textfields" id="productCodeCopy" name="productCodeCopy">
<br /><br />
<label for="confirmCodeCopy"> </label>
<input type="button" class="admin-buttons green" name="confirmCodeCopy" id="confirmCodeCopy" value="Search">
<div id="copyToProducts"></div>
open_second.php only prints out POST variables for now, so nothing special yet.
SOLVED
So ok, I solved it. With dumdum's help.
I removed the line:
$('input:checkbox[name="selectedImages[]"]:checked');
And added this:
var checkedItems = new Array();
var productToCopy = $('#productCodeCopy').val();
$("input:checkbox[name=selectedImages[]]:checked").each(function() {
checkedItems.push($(this).val());
});
Since there was no form element present, it didn't get the field values unless "manually retrieved" via .val() -function.. Stupid me..
I don't know how much this affected but I changed also:
data: ({checked: checkedItems, copyTo: productCodeCopy"})
To
data: {"checked": checkedItems, "copyTo": productToCopy}
So now it's working just fine :) Cool!
WHen you apply event hander to a button or a link to do ajax...always prevent the browser default processing of the click on that element
There are 2 ways. Using either preventDefault() or returning false from handler
$("#confirmCodeCopy").on('click', function(event){
/* method one*/
event.preventDefault();
/* handler code here*/
/* method 2*/
return false;
})
The same is true for adding a submit handler to a form to do ajax with form data rather than having the form redirect to it's action url
your code $('input:checkbox[name="selectedImages[]"]:checked'); is returning undefined making the json data in the ajax call invalid. Check you selector there.
I know this is very easy, but i only know the DOM equivalent of this code. the very long one. i've already searched trough some of the questions here in stack but i cant seem to find the solution.
so basically i have this script:
function searchNow(str)
{
$.ajax({
url: "search.php",
type: "POST",
async: false,
data: {"search": str},
success: function(data){
alert("test");
$("#result").html(data);
}
});
}
<table>
<tr>
<td>Search: </td>
<td><input type = "text" name = "search" onBlur="searchNow(this.value)"> </td>
</tr>
this will submit search to search.php to do a query search and retrieve the result and display it at id result.
i can do this easily using the old DOM ajax but then i wanna try using this jquery version instead since it is cleaner and maybe faster.
at my search.php
i have this:
$search = $_POST['search'];
return $search;
sadly i cant seem to return anything at all.
some input would be greatly appreciated, im already starting to be familiar with jquery ajax but only on the same page, not on inter page manipulation.
thank you,
-magician
Your PHP file should output the value. The ajax is going read that page and get it's content.
$search = $_POST['search'];
echo $search;
You want to be doing echo $search rather than return.
You can also add print_r($_POST); to take a look at what is going on in the PHP side of things.
Once you see what that is doing you can develop your php script a little further.
// Sets the correct response type
header('Content-type: application/json');
// get your search string/query
$search = $_POST['search'];
/*
* Do whatever you need in order to get a result
*/
echo json_encode($result);
exit;
If you are passing the search query to a database be sure to read Nettuts great intro to PDO. There are a lot of common pitfalls that can lead to security issues/exploits - avoiding one of the main ones (SQL injection) is covered in that post.
As per your comment, make sure your page with the search field is properly including jquery in the right place (sorry I don't mean to patronise if this is obvious!)
<html>
<head>
<title>Jquery Ajax</title>
<!-- google nicely host jquery for free... -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function searchNow(str)
{
$.ajax({
url: "search.php",
type: "POST",
data: { "search": str },
success: function(data) {
alert("test");
$("#result").html(data);
}
});
}
</script>
<table>
<tr>
<td>Search: </td>
<td><input type="text" name="search" onBlur="searchNow(this.value)" /></td>
</tr>
</table>
<div id="results"></div>
</body>
</html>
Dont forget to create an HTML element with ID="result" used by the selector to contain the result printed by your search.php.
$("#result").html(data);
Your PHP file should output the value. The ajax is going read that page and get it's content.
$search = $_POST['search'];
echo $search;
Also, the success option is set to be deprecated in the future releases of jQuery. You should instead use .done(callbackFunction) like so:
$.ajax({
url: 'beh.php',
type: 'POST',
data: {search: "beeeeeeeh"}
}).done(function () {
// do stuff
})
Also, is there any reason in particular why you are setting async to false?
I tried using
type: 'GET'
and in php file, got the value as
$search = $_GET['search'];
echo $search;
It worked. Hope it works for you also.
Trying to implement an autocomplete box ultimately. For now im following php academy's lead. I just want to echo out "suggestions go here" underneath the input area when anything is entered. I have to files. home.php and country.php. home contains the input part and country.php just prints the dummy suggestion text. Right now when I type in the input area ..nothing happens. I am using jquery v 1.6.2 (jquery-1.6.2.min.js)
home.php is:
<html>
<head>
<script type ="text/javascript" src ="jquery.js"></script>
<script type ="text/javascript">
function getSuggestions(value){
#.post("country.php", {countryPart:value}, function(data){
$("#suggestions").html(data);
});
}
</script>
</head>
<body>
<div id = "content_holder">
<input type = "text" name="country" value= "" id = "country" onkeyup="getSuggestions(this.value);" />
<div id ="suggestions"></div>
</div>
</body>
</html>
country.php is
<?php
echo "Suggestions Go Here";
?>
Never seen #.post before... try using $.post
you wrote
#.post
should be
$.post
try that :)
$.post
not
#.post
it will work.
if you're working with jquery
$.post("country.php", {countryPart:value}, function(data){
$("#suggestions").html(data);
});
You can use like below code.
$.ajax({
type: "POST",
url: "country.php",
data: "name=value",
success: function(data){
$("#suggestions").html(data);
}
});
If you're truly using JQuery, you need to change your post call to this:
$.post("country.php", {countryPart:value}, function(data){
$("#suggestions").html(data);
});
You had # instead of $ before the post call.
It should be $.post and #.post
The method name should be
$ not #
you can use the "console of error"(ctrl + shift + j in monzilla firefox) for check error in javascript/HTML execution
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.
I'm implementing a relatively simple autosave system and I'd like to do so using the Prototype library. I'm using the PeriodicalUpdater request, but it's not working as I'd hoped. In short, I'm trying to, periodically, send a textarea's content via an AJAX request to a PHP page that will save it to a MySQL database. I'm doing something like (abbreviated code):
<html>
<head>
<script type="text/javascript" src="scripts/prototype.js"></script>
<script>
function autosave() {
new Ajax.PeriodicalUpdater('save_message', 'autosave.php',
{
method: 'post',
parameters: {id: $('id').value, save_text: $('myInput').value},
frequency: 5,
decay: 2
});
}
</script>
</head>
<body>
<input type="hidden" id='id' name='id' />
<textarea id='myInput' name='myInput'></textarea>
<script>
autosave();
</script>
</body>
</html>
Then autosave.php will take the form contents and write them to my database. That part is working fine. What is happening, as I discovered, is PeriodicalUpdater is called with the original form input, then is called periodically with that initial form input.
So that was a long setup for a relatively short question: How do I use Prototype (if possible) to periodically make an AJAX request using the current textarea's value?
you could just use Ajax.Request with setinterval,something like this:
document.observe("dom:loaded", function() {
intervalID = window.setInterval("autosave()",500);
});
function autosave() {
new Ajax.Request('autosave.php',
{
method: 'post',
parameters: {id: $('id').value, save_text: $('myInput').value},
});
}
Ajax.Request is the right move, but why not make it more reusable
If you just have one input, or even if you had many I'd advise something like:
<form action="/user/4" method="post">
<input type="text" name="user[name]" value ="John" class="_autosave" />
<input type="hidden" name="user[id]" value ="4" class="uid"/>
<input type="submit" />
</form>
...
$$('input._autosave').each(function(s){
s.observe("change", function(event){
var el = event.element();
var uid = el.next("uid").value;
var r = new Ajax.Request(el.up("form").readAttribute("action"),{
parameters: {el.readAttribute("name"): el.value},
});
});
});
Just place your periodical updater in dom:loaded event. It is used to ensure that all components have been loaded, better than using window.onload event. Just remember, that there is a little bit different between dom:loaded event and native window.onload event, where dom:loaded called when all dom loaded except images and window.onload called when all dom loaded including images file.
document.observe("dom:loaded", function() {
new Ajax.PeriodicalUpdater('save_message', 'autosave.php', {
method: 'post',
parameters: {id: $('id').value, save_text: $('myInput').value},
frequency: 5,
decay: 2
});
});