Is it possible to call a function using Ajax? - javascript

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.

Related

why I can't get the value when make a jquery/ajax call on link click?

In my website I have a link where user id is store like this :
<p>by <?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</p>
Here you can see variable $uid. This is the user id. So I want to make ajax call when I click on this link. It's should get the value of $uid to result page ofUser.php. But in result page (ofUser.php) it's showing :
Undefined index: id
Can you tell me how can I solve it ?
Here is the JS offUser function
function ofUser(id, event){
id = $(id);
event.preventDefault();
var formData = id;
$.ajax({
url : <?php echo "'ofUser.php'"; ?>,
type : 'POST',
xhr : function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend : function () {
$("#ofUser_message").val("Searching...");
},
success : function (data) {
$("#danger").hide();
$("#bydault_pagination").hide();
$("#bydeafult_search").hide();
$("#ofUser_message").html(data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
offUser.php
echo $uid = (int) $_POST['id'];
id = $(id); will cast id to jQuery object which is not making any sense here. It will make id as array(id=$(1) => [1])
Also note, your data being sent over server should be an object.
Try this:
function ofUser(id, event) {
event.preventDefault();
$.ajax({
url: 'ofUser.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function() {
$("#ofUser_message").val("Searching...");
},
success: function(data) {
$("#danger").hide();
$("#bydault_pagination").hide();
$("#bydeafult_search").hide();
$("#ofUser_message").html(data);
},
data: {
id: id
},
cache: false
});
}
Edit: Remove processData : true as it will send data as DOMDocument
Just try to pass id = id; instead id = $(id); because $(id) means you are trying to get any DOM element values using jQuery, I hope it will work, also tell me that, what HTML is generated for your this code
<p>by <?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</p>
To solve this problem, SIMPLIFY to make sure you are correctly passing the ID value. In your AJAX success function, ALERT the value you send back so you can immediately see what you received in PHP.
Try setting it up this way instead:
html:
<p>by <a id="uid_<?php echo $uid; ?>" href="#" ><?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</a></p>
javascript:
$('[id^=uid_]').click(function(event){
event.preventDefault();
var formData = this.id.split('_')[1];
$("#ofUser_message").val("Searching...");
$.ajax({
type : 'POST',
url : 'ofUser.php',
data : id=formData,
success : function (data) {
alert(data);
$("#danger").hide();
$("#bydault_pagination").hide();
$("#bydeafult_search").hide();
$("#ofUser_message").html(data);
}
});
});
ofUser.php
$uid = $_POST['id']; //REMOVE the (int) for now, to verify what PHP is receiving - then add it back.
echo 'Received $uid';
Notes:
(1) Note that you misspelled ofUser.php and offUser.php (not sure which is correct - I went with ofUser.php)
(2) Try not to use inline javascript. jQuery is easiest to use when you break out the javascript from the HTML, as per above example.
(3) In above example, the jQuery selector starts with is used:
$('[id^=uid_]').click(function(event){
That code is fired by any element whose ID begins with uid_, as we configured the <a> tag's ID to appear. That makes it easy to see in your HTML.
(4) This line:
var formData = this.id.split('_')[1];
uses pure javascript to get the ID, because it's faster - and simpler to type. The code splits off the 2nd part of the ID, at the _ char, resulting in just the ID number. That ID number is then assigned to the variable formData
(5) In the AJAX code block, make sure the url is spelled correctly:
url : 'ofUser.php',
Here are some other SIMPLE AJAX examples that might help. Don't just look at them - reproduce them on your server and play with them. They are simple, but you may learn a lot:
AJAX request callback using jQuery
When click over any hyperlink then start redirecting to provided URL. so you need to prevent its default action using below code inside your click event handler
event.preventDefault();

How to parse javascript/jquery to echo / execute within/after ajax result

Ajax returns all expected html result from php code, except the javacript and jQuery inside the "script" tags
var frm = $('#cell');
frm.submit(function (ev) {
$.ajax({
type: "POST",
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (html) {
//Create jQuery object from the response HTML.
var $return=$(html);
//Query the jQuery object for the values
var oneval = $return.filter('#cellWidthSlider').html();
alert(oneval);
$("#cellWidthDiv").html(oneval);
}
});
ev.preventDefault();
});
I have tried to append to head, but the jQuery code would execute only - before the elements.
var $response=$(html);
$("head").append($response);
var oneval = $response.filter('#cellWidthSlider').html();
As much as I've been afraid of JSON, it was actually much simpler than I thought and it really took me only around 3 hours to get the general understanding, feeling good, now so so much started to look familiar in ajax and jQuery:)
So The changes I've done...
Instead of generating js within external php I have created array with values e.g.:
$result = array(
array(
'prevCellId' => $prevCellId,
'prevCellWidth' => $prevCellWidth,
'thisCellId' => $latestCellId,
'thisWidth'=>$thisWidth,
'thisRowId' => $thisRowId,
'thisRowOrder' => $thisRowOrder,
'maxWidth' => $maxWidth,
'prevCellRowOrder' => $prevCellRowOrder));
echo json_encode($result);
Then, after long search I've managed to implement json values in my jQuery function:
$.getJSON( "cellWidth.php", function( json ) {
$.each(json, function(i, item) {
$('#slider').slider({ max:''+item.maxWidth+'',min: 10,step: 5, value:''+item.thisWidth+'', slide: handleSliderChange, stop: sendNew});
var $slider = $("#slider").slider({ max:''+item.maxWidth+'',min: 10,step: 5, value:''+item.thisWidth+''});
})
})
So simply used keyword "item." + "names of arrays" to "echo" / "use values" within jQuery - in this case this is a jQuery slider :))

What happens with data received by the server using ajax?

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"];

Telerik MVC Grid - Pass Value to New Controller Action

Using Telerik Extensions for ASP.NET MVC, I created the following Grid:
.. and I am able to extract the value of my Order Number using the client-side event "OnRowSelect", when the user selects any item in the grouped order. I can then get as far as displaying the selected value in an alert but what I really want to do is pass that value back to a different controller action. Is this possible using javascript?
When I tried the server-side control, I ended up with buttons beside each detail row, which was just not the effect/look desired.
You can easily make an ajax call in that event.
Kind of two part process (assuming your event handler resides in a separate .js file- otherwise you can define a url directly in .ajax call).
Define an url you need to post to - in $(document).ready(...)
like:
<script type="text/javascript">
$(document).ready(function() {
var yourUrl = '#Url.Action("Action", "Controller")';
});
Then place in your OnRowSelect event handler something like:
function onRowSelect(e) {
var row = e.row;
var orderId = e.row.cells[0].innerHTML;
$.ajax(
{
type: "POST",
url: yourUrl,
data: {id: orderId},
success: function (result) {
//do something
},
error: function (req, status, error) {
//dosomething
}
});
}
That should do it.
As it turns out there is an easier way to get to the new page by simply changing the Window.location as follows:
var yourUrl = '#Url.Action("Action", "Controller")';
var orderID;
function onRowSelected(e) {
var ordersrid = $('#IncompleteOrders').data('tGrid');
orderID = e.row.cells[1].innerHTML;
window.location = yourUrl + "?orderId=" + orderID;
}
Thanks to those who responded; however, the above answer as provided from Daniel at Telerik is more of what I was looking for.

jquery problem with live

I have code like this:
$(".delete").live('click', function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>", function(){
$(this).fadeIn('2000')
});
});
});
}
});
return false;
});
$('.delete').confirm(
{
msg: 'You are about to delete this message. Are you sure?<br>',
buttons: {
separator: ' - '
}
});//message deleting
When activated for the first time it is working (when I try to delete message, question is asked and if I say yes, message is deleted). When data again shown, when I click delete it is deleting message without asking. What is the problem?
It looks like you'll have to register the confirm plugin after every ajax load as it isn't using live internally.
Easiest way would be to move the code into its own function and call that inside the load callback and on page load.
function deleteConfirmSetup() {
$('.delete').confirm(
{
msg: 'You are about to delete this message. Are you sure?<br>',
buttons: {
separator: ' - '
}
});//message deleting
}
$(".delete").live('click', function() {
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>", function(){
$(this).fadeIn('2000');
deleteConfirmSetup(); // Add function call here
});
});
});
}
});
return false;
});
deleteConfirmSetup(); // Also call function here to setup initially
Clearly the "confirm" plugin doesn't operate with live and instead is using bind.
When the element is added, it doesn't have the confirmation bindings but does have the live ones, so it'll just delete.
You could attempt to re-call the confirm plugin in your success function after the new content is loaded, modify the plugin, do it yourself manually, or find a new plugin that's a bit better thought-out.
I haven't used the confirm plugin, but a slightly irritating hack to make this work as you want might be to do this:
var bindBackup = jQuery.fn.bind;
jQuery.fn.bind = jQuery.fn.live;
before you run .confirm(). Then just restore it afterwards:
jQuery.fn.bind = bindBackup;
I haven't tried it, but the live function doesn't implement bind in it's source, so I don't see a reason why it won't work.

Categories