one.php:
HTML:
<button value="testValue" name="foo">Click</button>
Javascript:
var keyVals = {foo:"bar"}
$(function() {
$("button").click(function() {
$.ajax({
type:"POST",
url:"two.php",
data: keyVals,
success: function() {
$("#center").append("<p>Data Transfer succeeded! </p>");
}
});
});
});
Now, what actually happens with the data? How can I use it in two.php? Say I want to save it in a file/database, why not save it directly from one.php?
I've tried the following:
two.php:
<?php
var_dump($_REQUEST);
?>
Comes out as empty. So what ACTUALLY happens with the data I sent from one.php? How can I use it?
Strangely enough, I've looked at every similar question to this I could find, and none of them were answered properly, and most of them were downvoted. What's wrong with this question?
send data like this -
data: { value : $(this).val() },
on php access it like this -
$value = $_POST["value"];
Related
I want to fetch data when onclick is invoked. I have four div in my form and I want only a particular div to be reloaded and fetch data. while loading it should not discard the form data. Anyone help. Thanks in advance for people who are going to help me in this.
my code looks something like this
<div id="fetch">
<?php
//query to fetch data
?>
</div>
<div id="data4">
//dynamic data
//Want to retain this data even after fetch
</div>
In this case you should use AJAX.
Onclick you can send a xmlhttprequest (JS) to a separate php file, which returns the data you need (for example as string / JSON), and insert it into your website with JS.
Example:
function test()
{
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if(xhr.readyState==4 && xhr.status==200)
{
result = xhr.responseText;
document.getElementById("test_field").innerHTML = result;
}
}
xhr.open("GET","your_ajax_file.php",true);
xhr.send();
}
your_ajax_file.php returns the data you want to insert.
You mentioned you have a problem with function call, but you did not give more information. so i will give you an example how to write an ajax request, then you can maybe give me more detailed info on where your problem is.
$.ajax({
url: 'ajax_file.php',
type: 'post',
data: {var1: 'value1', var2: 'value2'},
success: function( data ){
console.log('ajax request successful! data: '+data);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
And in your ajax_file.php do something like this:
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
echo $var1.', '$var2;
edit: typo, changed val2 to var2 in ajax request
I am desperately trying to submit multiple POST variables via AJAX, but just cant get manage to get the formatting right... Problem is that I have both a hardcoded / written action=problem_lookup variable and a dynamic field input as $(this).val and just cant manage to get both into one data string...
this works well:
data: 'problem=' + $(this).val(),
This does not:
data: { action: 'problem_lookup' , problem: $("problem").val() },
data: { action: 'problem_lookup' , problem: $(this).val() },
data: { action: problem_lookup, problem: $(this).val() },
I tried numerous formats from other threads and looked at the official jquery manual, but cant seem to get this figured out. Any help is appreciated.
EDIT:
full script below, tried the solutions posted so far but no success. $("problem") is a <select> field (with Select2 running) hence shouldnt cause me so much frustration, especially since the original approach with data: 'problem=' + $(this).val(), works fine.
$(function () {
$('#problem').change(function () { // on change in field "problem"
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
$.ajax({ // launch AJAX connection
type: 'POST', // via protocol POST
url: 'ajax.php',
//data: 'problem=' + $(this).val(), // send $_POST string
//data:"{'action':'"+action+"','problem':'"+$(this).val()+"'}",
//data:"{'action':'problem_lookup','problem':'"+$(this).val()+"'}",
//data: { action: 'problem_lookup' , problem: $("problem").val() },
//data : data_string,
data: $.param(data),
dataType: 'json', // encode with JSON
success: function (data)
{
// do something
},
});
});
});
An issue is in the
$("problem")
Jquery call.
If.problem is a css class try with
$(".problem")
if problem is a css id try with
$("#problem")
For posting arrays of object you can build data as an object containing arrays, changing a little bit your structure. Something like this
Var obj={};
obj.postData=[];
obj.postData.push(/*your first object here*/);
...
obj.postData.push(/*your n-th object here*/);
$.ajax({
.....
data:obj;
......
});
Try the FormData() FormData.
var data = new FormData();
data.append('action', value);
...
You need to specify your data variable first like this:
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
In AJAX serialize your data using $.param,
data: $.param(data),
Note: Twice check if $("problem").val() is correct. If problem is a class, you need to specify like this $(".problem").val() or if it is ID, $("#problem").val()
i have been able to fetch data with an ajax call from active directory .
the php file used to make the ajax call to active directory :http://pastebin.com/tSRxwQL8
The browser console shows that an ajax call returns this :
<p> sn: xxxxxx<br/>givenname: xxxxx<br/>
employeeID: 0050<br/
>distinguishedName: CN=xxxx xxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>
displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>
department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com
<br/>
mail: mhewettk#abc.com<br/>
title: xyz<br/>
I want to take only some attributes above like mail,displayname etc and display in my HTML :
<h2 class="profile__name" id="emailOfUser">Email : </h2>
Now the problem is the jquery that I have used here :
$('.leaderboard li').on('click', function() {
$.ajax({
url: "../popupData/activedirectory.php", // your script above a little adjusted
type: "POST",
data: {
id: $(this).find('.parent-div').data('name')
},
success: function(data) {
console.log(data);
$('#popup').fadeIn();
$('#emailOfUser').html(data); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
error: function() {
alert('failed, possible script does not exist');
}
});
});
problem is this :
$('#emailOfUser').html(data);
this line displays all data whereas I want to select only email,displayname from the above console data
kindly help me how to select only desired attribute data from the above browser console data.
Ideally you should return JSON from PHP file, however if it is not possible for you to make changes to PHP file then you can use split("mail:") and split("title:") to extract data
success: function(data) {
console.log(data);
$('#popup').fadeIn();
var email=(data.split("mail:")[1]).split("title:")[0];
$('#emailOfUser').html(email); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
You are getting response in HTML which makes difficult for you to extract mail, displayname, etc.
You should get the response in JSON which will make it easy for you to extract the required info.
Ask your back-end team to send response in JSON format.
Working Fiddle
Try :
var lines = 'sn: xxxxxx<br/>givenname: xxxxx<br/>employeeID: 0050<br/>distinguishedName: CN=xxxxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com<br/>mail:mhewettk#abc.com<br/>title:xyz<br/>'.split('<br/>');
jQuery.each(lines, function() {
var val = this;
if (val.indexOf('mail') > -1)
// alert(val.split(':')[1]); //Only for test
$('#emailOfUser').html(val.split(':')[1]);
});
I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.
I'm noob, and i recently knew about Ajax, so dont worry if my question seems idiot.
I tried to do that, but i had no success, but i will explain what i tried to do:
I have one draggble box with some words, and everytime that i drag some elements to a certain place, i want to record this transition into my database.
So, i did that in Ajax:
UPDATE
$(document).ready(function() {
$(".event").draggable();
$(".drop").droppable({
drop: function(event, ui) {
var id = ui.draggable.attr("id");
var targetid = event.target.id ;
$.ajax( {
type: 'post',
url: "new.php",
data : { 'day' : '3' },
success: function( response ) {
alert( response );
}
});
}
});
});
New file:
function eventTransition($day){
$day = $_POST['day'];
$insert="INSERT INTO events (event_day) VALUES (".$day.")";
mysql_query($insert);
}
eventTransition($day);
I tried to automatically put a value to the day variable.
Please try this in php file and reply if this helps you
function eventTransition($day){
$insert="INSERT INTO events (event_day) VALUES (".$day.")";
mysql_query($insert);
}
$day = $_POST['day'];
eventTransition($day);
You cannot call a PHP function directly using Ajax. A(n over-)simplified new.php file may look like the following:
$day = $_REQUEST['day'];
$insert="INSERT INTO events (event_day) VALUES (".$day.")";
mysql_query($insert);
In your ajax call you must specify:
dataType: 'json'
As #baxri advises, add an error handler.