I have set an Ajax call for Pagination. I need to pass one more vaiable which is stored in the URL
URL
http://thisite.com/pagetitl/?id=12 **// where 'id=' is a variable I want to pass.**
Ajax Call
function page(page) {
var dataString = '&page=' + page; // pagination with ajax
pag.ajax({
type: "GET",
url: "cmn_pg.php",
data: dataString,
success: function (ccc) {
pag("#search_results").html(ccc);
}
});
}
I have tried to GET it in PHP file $id=$_GET[id], but wont work.
I ask how to pass it with AJAX because I'm quite new to AJAX.
If you are building your query string manually then:
dataString = 'page=' + encodeURIComponent(page);
but you are using jQuery, so don't build it manually:
url: "cmn_pg.php",
data: {
"page": page
},
success: function (ccc) {
(You also need to use the right name for it in PHP: <?php $id = $_GET['page'] ?>)
You can pass via url like this
pag.ajax
({
type: "GET",
url: "cmn_pg.php?page="+page,
success: function(ccc)
{
pag("#search_results").html(ccc);
}
});
Or
pag.ajax
({
type: "post",
url: "cmn_pg.php",
data: {'data':dataString},//You can add as many datas seperated by comma to pass more values
success: function(ccc)
{
pag("#search_results").html(ccc);
}
});
And in php
$dataString = $_POST['data'];
You named the variable "page" and try to access it via "id" in PHP. You have to create the query string liek this:
var dataString = '&id=' + page;
Alertnitavly you can use pass an object to the "data" parameter andjQUery does the transformationf for you. Sample:
data: { id: page },
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
Soruce: http://api.jquery.com/jQuery.ajax/
Try this,
pag.ajax({
type: "GET",
url: "cmn_pg.php",
data: {
page: page, // your page number
id:12// your id to send
},
success: function (ccc) {
pag("#search_results").html(ccc);
}
});
function page(page) {
var dataString = '&page=' + page; // pagination with ajax pag.ajax
({
type: "GET",
url: "cmn_pg.php",
data: {
page: page
},
success: function(ccc) {
pag("#search_results").html(ccc);
}
});
if more data is there to pass add to data variable as given bellow :-
data : {page:page,data2:data2},
Related
My Javascript code is the following:
function on(logged_user) {
alert(logged_user);
$.ajax({
url: "update_stats.php",
type: "POST",
data: logged_user
});
}
update_stats.php contains
<?php
$logged_user = $_POST["logged_user"];
?>
but I can see that $logged_user is just an empty string (I'm inserting it into a database table)
Your data parameter for the $.ajax call is not in the right format. From the manual:
The data option can contain either a query string of the form
key1=value1&key2=value2, or an object of the form {key1: 'value1',
key2: 'value2'}
You should change that line to:
data: { logged_user : logged_user },
or
data: 'logged_user=' + logged_user,
just try this:
function on(logged_user) {
alert(logged_user);
$.ajax({
type : 'POST',
url : update_stats.php,
data : logged_user,
dataType : 'json',
encode : true
});
}
Its not javascript , its a jquery ajax, so please include a jquery library.
and change your function like this
Syntax to pass the values like,
data: '{ "key":' + value+ ', "key":"value" }',
or
data = "key=" + value
or
data: JSON.stringify({ key: value, key: value}),
function on(logged_user) {
var dataString = "logged_user=" + logged_user
$.ajax({
type: "POST",
url: "update_stats.php",
data: dataString,
cache: false,
success: function(result) {
alert(result)
}
})
}
You need to pass data in key - value format to get accesible by $_POST, $_GET and $_REQUEST array variables in php.
data: {'logged_user' : data: logged_user}
You can access raw input like JSON data or text data which not in the key value format you can use file_get_contents("php://input") to access data.
I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.
I have a page that gets the user from $_POST. It is something like this:
$login=$_POST['name'];
Then when I click a button it makes an AJAX request like the following:
var id = $(this).val();
var dataString = 'Empresa=' + id;
$.ajax({
type: "POST",
url: "processemp.php",
data: dataString,
success: function (html) {
This works fine but I need to send $login with the request too. How can I send two variables at once?
You can try one of the two solutions below, but please note that the script should be written in the PHP page, not in a separate javascript file.
The data option of jQuery.ajax() accepts two types of form: PlanObject or String.
data
Type: PlainObject or String Data to be sent to the server. It is
converted to a query string, if not already a string. It's appended to
the url for GET-requests. See processData option to prevent this
automatic processing. Object must be Key/Value pairs. If value is an
Array, jQuery serializes multiple values with same key based on the
value of the traditional setting (described below).
As a plain object,
var id = $(this).val();
$.ajax({
type: "POST",
url: "processemp.php",
data: {
Empresa : id,
login : '<?php echo $login; ?>'
},
success: function(html){
}
});
As a query string,
var id = $(this).val();
$.ajax({
type: "POST",
url: "processemp.php",
data: 'Empresa=' + id + '&login= <?php echo $login; ?>',
success: function(html){
}
});
I am trying to pass a value of a button using some ajax to a separate file.
Here is my code.
$("input#downloadSingle").click(function() {
var myData = $("input#downloadSingle").val();
$.ajax({
type: 'post',
url:'singleDownload.php',
data: myData,
success: function(results) {
alert('works');
}
});
});
However, when I test out the next page by doing a var_dump on $_POST. I don't get any data back. Thoughts?
You're not specifying the name of the $_POST variable you're gonna get on the singleDownload.php file (unless that's part of the button's value), so you should try something like:
$("input#downloadSingle").click(function() {
var myData = "whatever=" + $("input#downloadSingle").val();
$.ajax({
type: 'post',
url:'singleDownload.php',
data: myData,
success: function(results) {
alert('works');
}
});
});
And make sure $_POST in your php file is the same whatever variable
I would like to send some data by using jquery ajax function to my PHP file.
I have created such function:
function ajax_call (url, select, select_name)
{
$(select).change(function () {
$(".result").fadeIn(400).html('<img src="ajax-loader.gif"/>');
var select_value = $(this).val();
$.ajax({
type: 'POST',
url: url,
data: { select_name : select_value },
success: function(data){
$(".result").html(data);
}
});
});
}
I call it:
ajax_call ('url path to my PHP file', '#my_select_div', 'my_data_name');
I have problem with this part:
data: { select_name : select_value }
I would like to get:
$_POST['my_data_name']
but I'm getting:
$_POST['select_name']
Any ideas?
Thanks for your answers.
When using object literal syntax, the key can be a string or an identifier. The identifier represents the key name, not a variable. You have to assign the key/value after creating the object if you want to use variable key names.
var data = {};
data[select_name] = select_value;
$.ajax({
type: 'POST',
url: url,
data: data