Sending Information to a PHP Script using Ajax - javascript

I would like to send an ajax command to a php script each time when a button is clicked. The divs are called r, l, t, b for the different directions. So far I have tried using the code below. But somehow it doesn't work. I have not a lot of experience in jquery and that's why I am asking here for a simple solution. I could write 4 times the same function but this is certainly not what I am looking for.
$(document).ready(function(){
function control(id){
$.ajax({
type: "POST",
url: "control.php",
data: {id: "1"},
success: function(data){
alert(data);
}
});
}
$('#r').mousedown(function(){
control($(this).attr('id'));
});
});

Well first...
Just give all your divs a class
<div id="r" class="direction"></div>
<div id="l" class="direction"></div>
<div id="t" class="direction"></div>
<div id="b" class="direction"></div>
Then rewrite your jquery
$(document).ready(function(){
$('.direction').mousedown(function(){
$.post("control.php",{id: $(this).attr('id')},function(msg){
alert(msg);
});
});
});
If you happen to be receiving JSON from the servers....
You must specify the dataType as 'json' or 'jsonp' for cross domain json and use $.ajax
function control(theid){
$.ajax({
type: "POST",
url: "control.php",
data: {id: theid},
dataType: 'json',
success: function(msg){
alert(msg);
}
});
}
Or if you wanna keep it simple like the above $.post example.....use getJSON
$(document).ready(function(){
$('.direction').mousedown(function(){
$.getJSON("control.php",{id: $(this).attr('id')},function(msg){
alert(msg);
});
});
});

It's hard to know exactly what you are asking, but basically you want a multipurpose click event for multiple divs.
in jQuery, you can add multiple selectors by separating the selectors with commas
like so:
$('#id, .class, element')
Here is an example that uses less code to provide the same functionality, if I understood your question correctly.
$(function(){
$('#r,#l,#t,#b').mousedown(function(){
$.post('control.php',{id: $(this).attr('id')},function(data){
//handle data callback
alert(data);
});
});
});
I used $.post instead of $.ajax , but bear in mind if you use the simpler methods like post, get, or getJSON, you will not be able to assign an error callback as far as I'm aware. Hopefully this changes in future releases of jQuery.

function control(my_id){
$.ajax({
type: "POST",
url: "control.php",
data: {id: my_id},
success: function(data){
alert(data);
}
});
}
Using $_POST['id']; you should get the information you are looking for.

Related

how to make a post call in jquery

I wrote this jquery code:
$(document).ready(function () {
$("#testDiv").load("http://localhost:7908/ToLoadAjax.aspx");
});
It seems it is a Get http request.
How to make it a post call please?
$(document).ready(function () {
$.post('http://localhost:7908/ToLoadAjax.aspx', function(data) {
$("#testDiv").html(data);
});
});
Use $.post() see the documentation for more informations.
Since you asked:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
Btw, read the documentation! https://api.jquery.com/jQuery.post/
But it doesn't make any difference do either a GET or a POST unless you are really sending in any data.

Jquery response load

A jQuery function receives a string from a database using GET, after that I would like to inject that string into HTML in place of a div. Pretty standard stuff so it seems.
However I am not quite managing it.
Here is what I have going on:
<h1>Whatever</h1>
<div id="replace_me">
</div>
<a id="click_me" href="#">Click Me</a>
<script>
//AJAX
var brand_id = 8
var dataX = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$(function(){
$("#click_me").click(function(){
$.ajax({
type: 'GET',
url: '/ajax_request/',
data: dataX,
datatype: "json",
success: function(data) {
alert(data);
$("#replace_me").load(data);
},
error: function() {
alert("Nope...");
}
});
});
});
</script>
When the alert is set off I receive my string which shows everything is working fine, but how can I input that string I just received into the div "replace_me" without having to load from another url?
You have an error in your success function. Check documentation on jQuery load(). Instead, you should do
success: function(data) {
//alert(data);
$("#replace_me").html(data);
},
or, slightly better style
success: function(data) {
//alert(data);
$("#replace_me").empty().append($(data));
},
Also note, that you specified "json" in your datatype option. As a consequence, if your server responds in proper JSON, your data will be a JavaScript object, as jQuery will parse the JSON format for you. If you really want to see the object, you will need to use, e.g. JSON.stringify():
$("#replace_me").empty().append($(JSON.stringify(data)));
If your server does not produce valid JSON, your success method will not be called in most cases.
load() is a convenience method to do the two steps of calling the ajax url, then putting the data into the element all in a single function. Instead of calling .ajax(), just call .load()
i.e.
var brand_id = 8
var data = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$("#replace_me").load('/ajax_request/', data);

Append a php file with jquery

i have a file which echoes out data from a database.
I wish to have a load more button which appends this file so that it will keep loading the rest of the results.
The php page works fine but need help with the jquery...
have used this else where for a json return but dont think this is needed for this.
So i am trying this:
$(document).ready(function(){
$("#loadmore").click(function () {
$("#content").append('includes/loadmorebuilds.php');
});
});
In essence, this works but it appends 'includes/loadmorebuilds.php' as just that. I simply appends those words and not the file.
Any help on this?
Many thanks!
You could use $.ajax to get content from file to be appended into DOM. One important thing is that you should use Relative PATH to your web root on url parameter in $.ajax
So it will become like this
$('#loadmore').click(function() {
$.ajax({
url: '/relative/path/to/your/script',
success: function(html) {
$("#content").append(html);
}
});
});
And make sure you should be able to access your script on http://www.example.com/relative/path/to/your/script
You have two options:
$('#content').load('includes/loadmorebuilds.php');
Which will replace the content of #content with the new html.
Or this:
$.ajax({
url: 'includes/loadmorebuilds.php'
}).done(function(data) {
$('#content').append(data);
});
Which will append the new data.
use $.ajax
$(document).ready(function(){
$(".loader").click(function(){
$.ajax({
url:"index.php",
dataType:"html",
type:'POST',
beforeSend: function(){
},
success:function(result){
$(".content").append(result);
},
});
});
});

Accessing DOM object after AJAX call?

I have a typical AJAX call that appends some HTML to the current page. I want to be able to access the newly inserted HTML with typical jQuery selectors.
Here's what I'd like to be able to do...
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
}
});
$('#new_div').show();
#new_div would be some HTML element from the data I retrieved. I don't necessarily want to attach events to the new elements (like click), so using something like .load() or .on() doesn't work here (as far as I know).
I tried setting the $.ajax() call to a variable: var new_div = $.ajax(...) but that didn't get me anywhere.
If you would like to manipulate the new content immediately after (or even before) inserting it to the DOM, you can put that in the AJAX success callback too:
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
$('#new_div').show();
}
});
On the other hand, if you want to bind handlers to content that will be added to the page via ajax, jQuery does that like this:
$(document).on('click', '#new_div', function(){
alert("This function is bound to all #new_div's click events, even if they are added to the DOM via ajax later!")
});
If you want to decouple your code from the callback:
functionWithALotOfStuffToDo = function(data){
// do stuff here
}
$.ajax({
url: url,
success: functionWithALotOfStuffToDo
});
how about:
$.ajax({
url: url,
success: function(data) {
$('body').append(data).find('#new_div').show();
}
});
Assuming the data being returned is something like <div id='new_div' /> then try something such as
var newDiv = null;
$.ajax({
url: url,
success: function(data) {
newDiv = $(data).appendTo($('body'));
}
});
This will add the <div /> to the body of your page, and assign the jQuery element to the variable newDiv which can then be accessed again at a later stage.
However, if you access newDiv before success has been returned, it will be null or the previous value, if it was assigned previously.
Actually this sort of things can be solved by following way:
(I know it is similar to others, but a little bit more clear)
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
afterHtmlAppendCallback();
}
});
function afterHtmlAppendCallback()
{
$('#new_div').show();
}
I think it's ajax async cause the problem you mention.
In jQuery ajax funciton API says:
Perform an asynchronous HTTP (Ajax) request.
If you want to access the data from ajax right after request
you should put you code in the ajax.success function like:
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
$('#new_div').show();
}
});
Or turn the async setting into false
$.ajax({
url: url,
async:false,
success: function(data) {
$('body').append(data);
}
});
$('#new_div').show();
that will make sure the $('#new_div') selector gets the object
I have the same issue and find a method that was great.
If you have the jQuery functions in a file for example library_jquery.js, just load that file again in the success.
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
//LOAD THE SCRIPT FILE AGAIN
var path_script_file="libray_jquery.js";
$.getScript(path_script_file);
}
});

multiple jquery html() assignment not working

I want to show the user a "loader" before and during the ajax call. Here's the code (simplified version...)
$(document).ready(function() {
$("#btn").click(function(){
$("#log").html("loading ajax call...");
anotherFunc();
});
});
function anotherFunc(){
$.ajax({
type: "GET",
url: correct_url,
data: data_to_send,
dataType: "jsonp",
success: function(data){
$("#log").html("new html");
}
})
}
the problem is that "loading ajax call..." never appears. I only see "new html" displayed. the singles ajax #log modification call work perfectly alone (without the other)
is there another way to do?
what am I doing wrong?
ps. I also tryed to write in another id (#log2) with the same result.
Most likely everything works just fine, but the AJAX call returns very quickly (especially if you are testing locally). To see if that is the case, just do the following:
$(document).ready(function() {
$("#btn").click(function(){
$("#log").html("loading ajax call...");
setTimeout(function(){anotherFunc();},2000);
});
});

Categories