how to load user's data from db to php to ajax and then manipulate the DOM?
here's what is in my mind :
user logged in -> fetch user data from db with php -> ajax request all the data using post -> do something on DOM
how the ajax look like? I only know how to use this to do from ajax to php to db :
$.ajax({
type: "POST",
url: "send.php",
data: { item : text }
})
You can do your backend operation in send.php, then you can return the html data from the backend
Eg. In send.php
echo "<h2>" . $your_db_thing . "</h2>";
In ajax, add success settings,refer Jquery Ajax
$.ajax({
type: "POST",
url: "send.php",
data: { item : text },
success:function(data) { // data will be <h2>your_db_thing</h2>
$('#successDiv').html(data); // the success element in which your html to be placed
}
})
Related
I am trying to send a variable from JS to php through ajax but I'm not able to get in php file.
JS
var names = ['lee','carter'] ;
$.ajax({
type: "POST",
url: "http://localhost/test/ajax.php",
data: {name:names},
}).done(function() {
location.href = 'http://localhost/test/ajax.php' ;
});
PHP
print_r($_POST);
this is showing an empty array but when I do console.log(data) it shows an array in console.log
var names = ['lee','carter'] ;
$.ajax({
type: "POST",
url: "http://localhost/test/ajax.php",
data: {name:names},
}).done(function(data) {
console.log(data) ;
});
Edit: (by mega6382) I believe OP wants to open a page in browser with post params, which cannot be done by AJAX. All others who answered got mistaken by the AJAX code in the question and started providing AJAX solutions, without realizing what OP is trying to do. If you were to read OP's comments on Jeroen's answer.
The problem is with what you do when the ajax request finishes:
}).done(function() {
location.href = 'http://localhost/test/ajax.php' ;
});
Here you are re-directing to http://localhost/test/ajax.php (requesting it a second time...), using a GET request so $_POST is indeed empty.
Just do the following in your php file to receive a json formatted string
echo json_encode(['success' => true]);
Instead of ajax try sending a dynamically generated form like:
var names = ['lee','carter'] ;
var newForm = $('<form>', {
'action': "http://localhost/test/ajax.php",
'target': '_top',
'method': 'POST'
});
names.forEach(function (item, index)
{
newForm.append($('<input>', {
'name': 'name[]',
'value': item,
'type': 'hidden'
}));
});
$(document.body).append(newForm);
newForm.submit();
This will send the values over POST via a form. It will do both redirect to the new page and send post vals.
Since you're using an AJAX request, in this case POST, you could use the _REQUEST method in php for obtaining the JS variable. In your case try:
$names = $_REQUEST['name']
echo $names;
/* Or try JSON_ENCODE if echo isn't working*/
$json = json_encode($names)
echo ($json);
var names = ['lee','carter'] ;
JSON.stringify(names);
$.ajax({
type: "POST",
dataType: 'json',
url: "http://localhost/test/ajax.php",
data: {name:names}
}).done(function() {
console.log('ok');
});
This is a successful ajax call. Now in order to "check by yourself" that is working you don't have to redirect to the other page because that way you refresh and lose the data. What you have to do is:
Open developer tab in your browser
Go to network tab
Locate your ajax call (it has the name of your php class that you do
the call)
go to response tab and there you have your php output
This link is to help you understand how to debug ajax call
Hello everybody i sent some value to php from Jquery $.post method and i want give some data from database
when load data from database is not completed show loading text and when load completed show data(It's contain some tables, div, text and image)
var val = "";
$.post("showData.php",{val: "loadMyTable"},
function(response) {
// if data loaded do something
// if not show loading text
});
Show your loading text in beforeSend and show your data in complete callback:
$.ajax({
type: 'POST',
url: "showData.php",
data: {val: "loadMyTable"},
beforeSend : function() {
$('#loadingText').show();
},
success : function(data) {
$('#loadingText').hide();
$('#myNewContent').html(data);
}
});
One of my php pages was changed to handle POST data (in order to accommodate a few form text fields), instead of GET (which was previously used).
So now, instead of if($_GET) { } it uses if($_POST) { }. They (team) wont allow both methods using ||.
I need to send a querystring to that same page using jQuery, but because of if($_POST) { }, it will not get through.
The querystring is formed from this : <i class="icon-hand remove" data-handle="se25p37x"></i>
I used to send it using jQuery ajax before, but that will not work now. Any idea how I can send it as POST?
$('.remove').live('click', function() {
var self = $(this);
var handle = $(this).data("handle");
if(handle) {
$.ajax({
type:"POST", // this used to be GET, before the change
url:"/user/actions/"+handle,
dataType:'json',
beforeSend:function(html) {
},
Just change type: "GET" to type: "POST" and add data parameter:
...
type: "POST",
data: $('form').serialize(), // OR data: {handle: $(this).data("handle")}
dataType: 'json',
...
I want to refresh the data of my div when I click on link that shows the div.
I could not find answer, even though there were a lot of similar answers.
So what I have:
I have several divs, that got shown by click on links.
I have the main page, I have:
<div id="#id">
<select id="list">
<?php inlucde('getlist.php'); //basically retrieves the options
</select>
</div>
in my php file:
<?php
//basically getting connected to mysql,
//and retrieve data from a table;
echo "<option> data </option>";
echo "<option> data </option>";
...
?>
The problem here is, the data I want to show is updated in another
div, I am updating the data in mysql, since the both divs are on the same page, The updated data is not shown in the list, when I refresh the page, it shows.
So what I want, is when I click the link to show the list, I would like to refresh the list before showing it.
How can I do it? Thanks.
What you want is refreshing the data upon change which can only be done (without page refresh) with the use of AJAX. Since you have tagged jquery I would suggest reading about $.ajax().
Long story short:
var request = $.ajax({
url: "script.php", // your server script that will reply to your request.
type: "POST", // method used for your request.
data: { id : menuId }, // data to pass to your server script.
dataType: "html" // the response type you expect from your server
});
request.done(function( msg ) { // executed when you get a successful reply
alert(msg); // your reply is inside msg variable
});
request.fail(function( jqXHR, textStatus ) { // in case of an error this is being executed
alert( "Request failed: " + textStatus );
});
request.always(function() { // will always be executed after success or failure
alert( "Request completed." )
});
Use mine
formData = {
id: $("#id");
}
$.ajax({
type: 'GET',
contentType: 'application/json',
url: "getlist.php",
dataType: "json",
data: formData,
success: function(data) {
//success handling
},
error: function(data) {
//error handling
}
});
I'm pretty new to ajax and I applied it succesfully to a Drupal site. But I was wondering, how do I get an URL to a page where part of the content is loaded through ajax. Is this even possible? The JSON object is retrieved on click, so how do I make it work when retrieving a certain URL?
I realize this is a very broad questionany, any help would be greatly appreciated.
Thanks in advance!
My JS looks like this:
Drupal.behaviors.ajax_pages = function (context) {
$('a.categoryLink:not(.categoryLink-processed)', context).click(function () {
var updateProducts = function(data) {
// The data parameter is a JSON object. The films property is the list of films items that was returned from the server response to the ajax request.
if (data.films != undefined) {
$('.region-sidebar-second .section').hide().html(data.films).fadeIn();
}
if (data.more != undefined) {
$('#content .section').hide().html(data.more).fadeIn();
}
}
$.ajax({
type: 'POST',
url: this.href, // Which url should be handle the ajax request. This is the url defined in the <a> html tag
success: updateProducts, // The js function that will be called upon success request
dataType: 'json', //define the type of data that is going to get back from the server
data: 'js=1' //Pass a key/value pair
});
return false; // return false so the navigation stops here and not continue to the page in the link
}).addClass('categoryLink-processed');
}
On the begining of the page load ajax based on hash part of the url page#id,
$(document).ready(function() {
$.ajax({
type: 'POST',
url: "/path/to/page",
success: updateProducts,
dataType: 'json',
data: 'id=' + window.location.replace(/.*#/, '')
});
$('a.categoryLink:not(.categoryLink-processed)', context).click(function () {
$.ajax({
type: 'POST',
url: "/path/to/page",
success: updateProducts,
dataType: 'json',
data: 'id=' + this.href.replace(/.*#/, '')
});
});
Or you can use jquery-history but I didn't test it.
I don't know what exactly you are trying to do. But unless you have a module that creates the JSON data you need to do it yourself.
You would need to create a menu callback with hook_menu. In the callback function you can return json data by using drupal_json.
If you create the menu callback etc yourself, the URL will be whatever you make it to. Else you just have to use the URL defined by the module you want to use.