Why does this JQuery/AJAX call not work? - php

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

Related

using ajax for change website language

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.

Dual ListBox not displaying options from database on first run

First of all, I am using Bootstrap Dual Listbox that I got from http://www.virtuosoft.eu/code/bootstrap-duallistbox/
After trying to implement it, I encounter a single problem. At first run, the options are not being displayed on either select box unless I click the Move All button.
So here is the structure as well as the codes.
Index.php
<!-- HTML -->
<select multiple="multiple" size="5" class="eItems" name="skillsTagged" id="skillsTagged">
</select>
<!-- Scripts-->
<script>
$(document).ready(function(){
var dlb1 = $('#skillsTagged').bootstrapDualListbox({
nonSelectedListLabel: 'Non-selected',
selectedListLabel: 'Selected',
preserveSelectionOnMove: 'moved',
moveOnSelect: false
});
getSkills();
});
function getSkills(){
var oldid = "1";
$.ajax({
type: "POST",
url: "get_selected_skills.php",
data: { specId : oldid }
}).done(function( res ) {
$("#skillsTagged").html(res);
});
}
</script>
get_selected_skills.php
<?php
echo "<option value='1'>1</option><option selected value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option selected value='5'>5</option>";
?>
So it seems like the options are there but are not being displayed on first run. Tried it on a regular listbox and is working so if anyone already encountered this when using Dual Listbox, your help will be greatly appreciated! Thanks!
Try to set ajax async property to false...
İn method : async:false
Or globally:
$.ajaxSetup({
async:false
});

How can i pass a variable from js file to another using ajax jquery?

I have 2 js files and i want to pass 2 variables from file1.js to file2.js. What i have done until now is to send these 2 variables from file1.js in a 3rd file file3.php with ajax using this:
$('#replace').click(function(){
var replacement = cur;
var replacement2 = cur2;
$.ajax({
url: DOMAIN_NAME+"file3.php",
type: "post",
data: {replacement: replacement, replacement2 : replacement2},
success:function(data){
console.log(data);
},
error:function(){
alert('Something Went Wrong');
},
});
});
In my file3.php:
if(isset($_POST['replacement']) && isset($_POST['replacement2']){
$a = $_POST['replacement'];
$b = $_POST['replacement2'];
}
<input type="hidden" id="af" value="<?=$a;?>">
<input type="hidden" id="bf" value="<?=$b;?>">
In my File2.js:
var a = $('#af').val();
var b = $('#bf').val();
i can see that in the network the ajax passes the variable with a status 200 OK but in the php file my variables doesn't pass. So the file2.js can't get the values. What i am doing wrong??
Let's say you have this simple form:
<form id="my_form">
<input type="text" name="a_field" id="a_field">
<input type="text" name="b_field" id="b_field">
<button id="submit_form">Submit</button>
</form>
The jquery script file (#1) for this form can be named "script1.js" and can look like that:
$(document).ready(function(){
$('#submit_form').on('click').function(e){
e.preventDefault();
var formData = $('#my_form').serialize();
$.ajax({
type: 'POST',
url: 'my_ajax.php',
data: formData
});
});
});
Notice that I serialized the form to be quicker... (If you want you can specify which variables you want to pass to ajax)
Here is an example of my_ajax.php:
<?php
session_start();
if(isset($_SESSION["a_var"])){unset($_SESSION["a_var"]);}
if(isset($_SESSION["b_var"])){unset($_SESSION["b_var"]);}
if(isset($_POST["a_field"])){$a_field=htmlspecialchars($_POST["a_field"]);}else{$a_field=""; exit();}
if(isset($_POST["b_field"])){$b_field=htmlspecialchars($_POST["b_field"]);}else{$b_field=""; exit();}
$_SESSION["a_var"] = $a_field;
$_SESSION["b_var"] = $b_field;
?>
With the above file, we created two php sessions based to the input-field values that we acquired from our html form.
Now the "tricky" part:
Your SECOND js file (#2) must be given an extension .php and NOT .js
It will however execute any javascript code if of course that code is enclosed in "script" tags
Let's name that file "script2.js.php" -which can be like that:
<?php
session_start();
if(isset($_SESSION["a_var"])){$value_a = $_SESSION["a_var"];}else{$value_a="";}
if(isset($_SESSION["b_var"])){$value_b = $_SESSION["b_var"];}else{$value_b="";}
?>
<script>/*...include jquery here (if necessary)...*/</script>
<script>
$(document).ready(function(){
//jquery is NOT necessary for my example
//I just included it in case you need to do other tasks...
var valueA = '<?php echo $value_a; ?>';
var valueB = '<?php echo $value_b; ?>';
//Now you can do anything with these values... For example, you could alert them:
alert('Value A: '+valueA+' - Value B: '+valueB);
});
</script>
One last thing:
While to include a js file to your html page you do:
<script src="http://www.example.com/scripts/yourscript.js"></script>
To include the "js.php" file you must do it by using the php "include" function:
This is how I would suggest to pass variables from one js file to another by using php sessions!
My example is quite "basic" and could take a lot of "polishing" work regarding functionality and security... But should give you an idea as of how to start...
Hope that helps you and/or others...

Ajax request inside ajax request fails - reloads the whole page again

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.

ajax to retrieve data from another page after post

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.

Categories