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.
Related
$("#submit_login").click(function(){
var username=$('input[name=user_email]');
var password=$('input[name=user_password]');
var data;
data: "name="+username+"&pwd="+password,
$.ajax({
type: "POST",
dataType: "json",
url: "newExam.php",
data: data,
success: function(data) {
alert("Form submitted successfully");
}
});
});
How to give the data variable so that we can fetch it in PHP using $_REQUEST?
The above representation of the data variable shows an error.
You can pass the data as json,
$.ajax({
type: "POST",
dataType: "json",
url: "newExam.php",
data: {
name: username,
pwd: password
},
success: function(data) {
alert("Form submitted successfully");
}
});
Also, names should match the parameters in the function.
Client Side
$("#submit_login").click(function(){
var username=$("input[name='user_email']").val();
var password=$("input[name='user_password']").val();
$.ajax({
type: "POST",
dataType: "json",
url: "newExam.php",
data: {name : username, pwd : password },
success: function(data) {
alert("Form submitted successfully");
}
});
});
Server Side
<?php
// file : newExam.php
// to view post array
if(!empty($_POST))
{
print_r($_POST);
}
// access individual element
if(isset($_POST['name']))
{
echo $_POST['name'];
}
?>
The above representation of the data variable shows an error.
Absolutely. That is correct because there is an error. You have a variable and you are assigning a query string with : where it should be =:
data= "name="+username+"&pwd="+password;
But this is not a good idea because you have to post the values not the input objects. username is an html input element, instead you should post an object like:
$("#submit_login").click(function(){
var username=$('input[name=user_email]').val();
var password=$('input[name=user_password]').val();
var data = {name:username, pwd:password};
$.ajax({
type: "POST",
dataType: "json", // <---make sure you return json from the php side.
url: "newExam.php",
data: data,
success: function(data) {
alert("Form submitted successfully");
}
});
});
Your selectors dont look right to me.
var username=$('input[name="user_email"]');
var password=$('input[name="user_password"]');
Note the double quotes around the input name attributes
Can you try the below code format:
data: {name : username, pwd : password }
In the first document I added a JSON string filled with numbers to localstorage like this:
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier: aktuelle_verdier},
dataType: "json",
success: function(result){
var dataToStore = JSON.stringify(result);
localStorage.setItem('key', dataToStore);
}});
Then in another document I am trying to post the JSON string retrieved from local storage like this:
<script>
var data = JSON.parse(localStorage.getItem('key'));
var localData = data.join(", ");
$.ajax({
type: 'post',
data: {localData: localData},
url: '',
dataType: "json",
success: function(result){
console.log(result)
}});
</script>
The PHP on the same page as the post tries to fetch the data like this:
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$values = json_decode($user_id);
var_dump($values);
?>
When I run var_dump I get Array(), so in essence it doesn't post anything. Anyone know whats going wrong?
You don't need to use JSON when sending an array in an object argument to $.ajax. Just put the array there, and jQuery will URL-encode it.
var data = JSON.parse(localStorage.getItem('key'));
$.ajax({
type: "post",
data: { localData: data },
...
});
Then in PHP you can do:
$values = isset($_POST['localData']) ? $_POST['localData'] : array();
var_dump($values);
You can also send JSON this way:
var json_string = localStorage.getItem('key');
$.ajax({
type: "post",
data: { localData: json_string},
...
});
then in PHP do:
$values = json_decode(isset($_POST['localData']) ? $_POST['localData'] : '[]');
var_dump($values);
I am sending some data with ajax, and as a response i get multidimensional array.
$.ajax({
type: "POST",
url: "/slideshow/list.php",
data: imageId,
success: function(data){
imagesList = data;
console.log(imagesList);
curentImage = imagesList[0];
}
});
Response, data looks like this. This is what i get on console.log(imagesList):
I am using php, and the response is provided like this <?php echo json_encode($data) ?>
[
[1,487124,"<img src=\"http:\/\/example.com\/images\/1\/487124.jpg\" \/>","http:\/\/example.com\/photos\/salle-a-manger---mineral\/649518","Title 1"],
[2,732924,"<img src=\"http:\/\/example.com\/images\/1\/732924.jpg\"\/>","http:\/\/example.com\/photos\/salle-a-manger---","Title 2"],
[3,341649,"<img src=\"http:\/\/example.com\/images\/2\/341649.jpg\"\/>","http:\/\/example.com\/photos\/salle-a-manger---","Title 3"]
]
If i try to access the first array with imagesList[0] it only shows [
How can i access the first or second array, or values inside of them?
specify the dataType in ajax request
$.ajax({
type: "POST",
url: "/slideshow/list.php",
data: imageId,
dataType:"json",
success: function(data){
$.each(data,function(key,value){
console.log('key:'+key+", value:"+value);
//do your stuff
});
}
});
Use this
var obj = $.parseJSON(data);
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},
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