Data not passing through AJAX - php

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

Related

Cannot get Ajax update form to work with unserialize

I'm trying to put together a working demo (including mysql) of a form that uses jquery to serialize form data and php to retrieve the data so that it can be passed to a mysql query.
The form seems to be posting data correctly but I'm not sure how to set up the processing script which sees $_POST to unserialize the data so that I can pass it to mysql. You can see the demo at http://www.dottedi.biz/demo/code/ajax/serialize .
I have tried using:
$data=unserialize($_POST['data']);
to unserialize the data but it comes back empty. A simple print_r ($_POST); returns the array data from the form. You can see that if you test the demo. Suggestions please?
Added info - the contents of the script.js file:
$(document).ready(function() {
$('form').submit(function(evt) {
evt.preventDefault();
$.each(this, function() {
var input = $(this);
var value = input.val();
var column = input.attr('name');
var form = input.parents('form');
var linked_col = form.find('#associated').attr('name');
var linked_val = form.find('#associated').val();
// var serializedData = $(this).serialize();
$("#Status").html( "" );
$.ajax({
url: "update.php",
data: {
val: value,
col: column,
id: linked_col,
id_val: linked_val
},
type: "POST",
success: function(html) {
$("#Status").html( html );
}
});
});
});
});
9/22 - shortened script.js
$(document).ready(function() {
$('form').submit(function(evt) {
evt.preventDefault();
$.each(this, function() {
$("#Result").html( "" );
$.ajax({
url: "update.php",
data: $('form').serialize(), // works to post data
type: "POST",
success: function(html) {
$("#Result").html( html );
}
});
});
});
});
Comment - I tested and it seems that the same data is posted using serialize as above vs creating a variable like var serializedData = $(this).serialize() and posting the variable, but this is shorter.
Perhaps you should
$('form').submit(function(evt) {
// Serialize the data in the form
var serializedData = $(this).serialize();
//send off serializedData in your ajax
}
THEN
php script will have
$data=json_decode($_POST['data']);
NEW WAY
$.ajax({
url: "update.php",
data: {'data': $('form').serialize()}, // works to post data
type: "POST",
success: function(html) {
$("#Result").html( html );
}

Ajax post not appending data to URL

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.

PHP-AJAX: How to pass URL variable through Ajax

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},

how to use ajax response data in php

I am having problem with response data. I want to use response data in my php file. I want to assign them to a php variable.
here is the ajax code in insert.php file.
function change(){
var tp=$('#choose').val();
var country_val=$('#country_filter').val();
//alert(country_val);
//var country_val=$('#country_filter').val();
$.ajax({
type: "POST",
url: "filter.php",
data: { name: tp, country:"test"},
success:function( data ) {
alert(data);
}
});
}
here is php code in filter.php
if($_REQUEST["name"]){
$lvl = $_REQUEST["name"];
//global $lvl;
echo $lvl;
}
Now I want to use the response data to be assigned to a php variable in insert.php file. How may I do that?
Please help.
Send the data to insert.php file using ajax, instead of alerting it.
change success function to
$.ajax({
type: "POST",
url: "filter.php",
data: { name: tp, country:"test"},
success:function(response) {
var res = response;
$.ajax({
type: "POST",
url: "insert.php",
data: { res: res },
success:function(data){
alert(data);
}
});
});
In insert.php,
use this to get the variable.
$var = $_POST['res'];
If insert.php calls filter.php with ajax and then returns a value. you cannot apply that javascript var to a php var in the insert.php. That is because the Php script runs on the server when the page is loaded, and the javascript runs locally on the users computer. To apply anything to a php variable you will have to reload the page.

Using AJAX to pass variable to PHP and retrieve those using AJAX again

I want to pass values to a PHP script so i am using AJAX to pass those, and in the same function I am using another AJAX to retrieve those values.
The problem is that the second AJAX is not retrieving any value from the PHP file. Why is this? How can I store the variable passed on to the PHP script so that the second AJAX can retrieve it?
My code is as follows:
AJAX CODE:
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
PHP CODE:
<?php
$userAnswer = $_POST['name'];
echo json_encode($userAnswer);
?>
Use dataType:"json" for json data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
No need to use second ajax function, you can get it back on success inside a function, another issue here is you don't know when the first ajax call finished, then, even if you use SESSION you may not get it within second AJAX call.
SO, I recommend using one AJAX call and get the value with success.
example: in first ajax call
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
alert(data);
//or if the data is JSON
var jdata = jQuery.parseJSON(data);
}
});
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
data: data,
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
Use like this, first make a ajax call to get data, then your php function will return u the result which u wil get in data and pass that data to the new ajax call
In your PhP file there's going to be a variable called $_REQUEST and it contains an array with all the data send from Javascript to PhP using AJAX.
Try this: var_dump($_REQUEST); and check if you're receiving the values.
you have to pass values with the single quotes
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: '145'}), //variables should be pass like this
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
try it it may work.......

Categories