ajax to retrieve data from another page after post - php

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.

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.

Passing Javascript (HTML Table Contents) array to php file

Im very confused, I have been looking for a solution to pass HTML table contents via a javascript array (if this is indeed the best way of capturing HTML Table data) to a php file so I can then do whatever I like with the data.
I have simplified the table shown in my example code in order to make it easier, the table i will be using live will have a lot of rows with more complicated data etc.
The current code in get_table_data_php is:-
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<div id ="results_table">
<table id="stats_table">
<tr>
<td>Car</td><td>Engine</td><td>Color</td><td>Price</td>
</tr>
<tr>
<td>Ford</td><td>2 Litre</td><td>Blue</td><td>22,000</td>
</tr>
<tr>
<td>Audi</td><td>2.5 Litre</td><td>White</td><td>25,000</td>
</tr>
</table>
</div>
<script>
var myTableArray = [];
$("table#stats_table tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray); // alerts the entire array
alert(myTableArray[0][0]); // Alerts the first tabledata of the first tablerow
$.ajax({
type: "POST",
data: {myTableArray:myTableArray},
url: "stats.php",
success: function(msg){
$('.answer').html(msg);
}
});
</script>
The code in the stats.php file being called is as follows:-
<?php
var_dump($_POST);
?>
The code in the calling php file runs as expected and shows (via the alert(s) which are there for my sanity) the table data as expected.
The file called (stats.php) however does not do anything and as such I do not know if its working and what the issue is as to why it isn't.
I am pretty new to the Javascript and Ajax side of things so any help would be appreciated.
Regards
Alan

Issue with the font character from the value extracted through jquery ajax method

I am using jquery ajax to display some values inside the label when some value is selected from select box. but the value that i want to display in label is some different font and I think that is why the value is displayed with some question mark characters with black quad box as background [#nb-am-h��#w] . How to avoid this:
//Javascript code
<script type="text/javascript">
$("document").ready(function(){
var id=$(this).val();
//alert(id);
$.ajax({
type: "POST",
url: "ajax.php",
data: {id:id},
cache: false,
success: function(html){
//alert(html);
$("#malid").show();
/*$('#malid').css("font-family", "malfont");*/
$("#malid").html(html);
}
});
);
HTML code
<div>
<label>Book</label>
<select id="bookname">
<?php
for($i=0;$i<$count;$i++)
{
?>
<option value="<?php echo $bookid[$i];?>"><?php echo $book_name[$i];?> </option>
<?php
}
?>
</select>
<label id="malid" style="display:none;font-family: 'malfont';"></label>
</div>
//Php code inside ajax.php
if(isset($_POST['id']))
{
$id=$_POST['id'];
$book_results = $mysqli->query("SELECT book FROM booktable where book_id='$id'");
$row = $book_results->fetch_assoc();
$book = $row['book'];
echo $book;
}
Can you check out (using the networks tab or a proxy) what the response is from the AJAX call? Its probably bad encoding in your database / connection.
Also, please note that this AJAX endpoint is vulnerable for SQL Injection (You're not escaping the users' input $_POST['id'].
For more information, check out: https://en.wikipedia.org/wiki/SQL_injection#Technical_implementations
I got a solution for my issue. I just included the below line in my Ajax page and it is working fine now.
header('Content-Type: text/html; charset=ISO-8859-15');

jQuery Ajax replaces the div by whole .php page

I'm using jQuery Ajax function for populating my select box.
Here is the code:
$(function(){
$("#maker").change(function(){
var selected_value = $("#maker").val();
$.ajax({
type: "POST",
url: "search.php",
data: ({_maker: selected_value}),
success: function(response){
$("#models").html(response);
}
});
});
});
The problem is this replaces the div "models" by whole search.php page!!!
I only want to populate the option values within "models".
Here is the HTML:
<div id="models">
<select id="model" name="model" style="width:170px">
<option value="Any">Any</option>
<?php
foreach($current_models as $model) {
?>
<option value="<?php echo $model; ?>"><?php echo $model; ?></option>
<?php
}
?>
</select></div>
Any help is appreciated. Thanks in advance.
So it looks like you're returning the entire HTML page, and not searching through it to find the specific part of the page. Try something like this:
$(function(){
$("#maker").change(function(){
var selected_value = $("#maker").val();
$.ajax({
type: "POST",
dataType: "html",
url: "search.php",
data: ({_maker: selected_value}),
success: function(response){
$("#models").html($(response).find('#someDiv').html());
}
error: function(){
$("#models").html('Uh oh! Something went wrong and we weren't able to process your request correctly.');
}
});
});
});
You'll notice 2 things:
I specified a dataType property. This tell jQuery what to expect. Additionally the html data type, tells jQuery to execute any JavaScript on the loaded page before rendering the page into the response object.
I'm creating a jQuery object using the response, and then using jQuery's .find() method to get the inner HTML of a specific div in the response.
Here is an example JS Fiddle, with some slight modifications for proof of concept: http://jsfiddle.net/rvk44/1/
I also just wanted to note that you may want to add an error property so that if the page ever comes back as an error, the user knows that and isn't just sitting there staring at a blank screen expecting something to happen. (I've added a basic error message in the example, see the jQuery docs for further info on what the error property is returned).

I can't send full data through ajax script on php language. (code igniter)

<script language='javascript' type='text/javascript' charset='<?=$page_charset?>'>
$(document).ready(function(){
$('#btn_login').click(function(){
$.search_keyword();
});
});
here is the script
<form name='frm_search_keyword'>
<table style='width:250px;'>
<tr>
<td style='width:100px;'>
Search
</td>
<td>
<input type="text" name="web_keyword" />
</td>
<td>
<input type="submit" id="btn_login" name="btn_login" value="search!" />
</td>
</tr>
</table>
</form>
here is the form
search_keyword:function(type)
{
$.ajax({
type: 'POST',
url: '/web_keyword',
data: {'b_type':type},
cache: false,
async: false,
success: function(result){
if(result == 12001)
{
alert('please choose your interest.');
location.href = '/account/interest';
}else
location.href = '/'+type+'/'+result;
}
});
}
It successfully sends 'web_keyword' to db query and get result.
but I can't get type data through ajax script.
Can you help me to 'type' data from the form table to ajax script?
Thank you.
I'm not exactly sure if this is the problem, but it is suspect:
$('#btn_login').click(function(){
$.search_keyword();
});
Where is "type" supposed to come from? What is "type" referring to? Is "type" a value returned from your DB query? Or is it something selected by the user when they perform the search?
If type is something within your form element, then use Javascript or jQuery, or whatever, to "harvest" that value from the page, and then you will need to pass that data to the AJAX functionality.
$('#btn_login').click(function(){
//First get the "type" value, for example if "type" is retrieved from the form element
var type = $('#btn_login').attr('type'); //this is for example's sake, since you did not assign an id to this form element...
search_keyword(type);
});
You just need to get "type" from where ever it is being generated and/or stored and pass it to your AJAX function.
Also, maybe this is irrelevant, but your "search_keyword()" function definition looks odd to me...
Instead of:
search_keyword:function(type){...}
Should be:
search_keyword = function(type){...}
One final thing, could you tell us which Javascript library you are using?
Try adding
" dataType: 'json'," like
$.ajax({
type: 'POST',
url: '/web_keyword',
dataType: 'json',
data: {'b_type':type},
});
and return the date using
$data['return1']='true';
echo json_encode($data);
success: function(result){
if(result.return1 == 12001)
{
alert('please choose your interest.');
location.href = '/account/interest';
}else
location.href = '/'+type+'/'+result;
}
you should remove async:false
Setting this option to false is strongly discouraged, as it can cause the browser to become unresponsive.

Categories