I have a little question about Ajax calls in Mootools.
I wrote a handler script and a listener script in Jquery using AJAX but i cant figure out how to convert it so it works with mootools instead of Ajax.
The function is called using a html link tag with onclick='changePage($page, $total)'
This is the original JQuery Ajax call. it gets returned in the Ajax file as an array.
The variable gets returned as followed:
$data = array();
$data['result'] = '1';
$data['html'] = $this->result; //Returns Pagination bar with current selected page.
$data['html2'] = $this->result2; //Returns a block of HTML (result of Solr request styled with bootstrap
JQuery version of the script
function changePage(page, total) {
$.ajax({
url: '/public/ajax.php?do=getPageView',
type: 'POST',
dataType: 'json',
data: {
page: page,
total: total,
//type : type
},
success: function(data) {
//console.log(data.result);
if (data.result == 1) {
$('#placeHolder').html(data.html);
$('#vrouwen').html(data.html2);
} else if (data.status == 2) {
//do nothing :) - nothing has been input
} else {
alert("Fout!!\n" + textStatus + "\n" + errorThrown);
}
},
error: function error(jqXHR, textStatus, errorThrown) {
alert("Fout!!\n"
+ textStatus + "\n" + errorThrown);
}
});
};
My presumed Mootools version of the script
function changePage(page, total) {
var ajax = new Request({
async: false,
url: '/public/ajax.php?do=getPageView',
method: 'POST',
dataType: 'json',
data: {
'page': page,
'total': total,
//type : type
},
onSuccess: function(data) {
//console.log(data.result);
if (data.result == 1) {
$('placeHolder').set('html', data.html);
$('vrouwen').set('html', data.html2);
} else if (data.status == 2) {
//do nothing :) - nothing has been input
} else {
//alert("Fout!!\n" + textStatus + "\n" + errorThrown);
}
}
});
ajax.send();
};
In the view i have a div named placeholder, thats where the pagination bar goes.
And html2 gets inserted into the div with id='vrouwen'.
Hope you guys can help me out on this one.
--EDIT---
Figured it out after brainstorming with a few fellow programmers. posting the findings here for all to see.
The difference lies in the way Jquery and Mootools handle returned values.
Apperantly JQuery handles returned values as JSON objects when you set dataType: 'json'.
Mootools does not do this so i added to the onSuccess function the following:
onSuccess: function(data) {
data = JSON.decode(data);
//console.log(data.html2);
if (data.result == 1) {
$('placeHolder').set('html', data.html);
$('vrouwen').set('html', data.html2);
} else if (data.status == 2) {
//do nothing :) - nothing has been input
} else {
//alert("Fout!!\n" + textStatus + "\n" + errorThrown);
}
}
Now it properly replaces the Divs.
Mootool Request is An XMLHttpRequest Wrapper
onSuccess attached Method is Fired when the Request is completed successfully.
The arguments returned to the attached Handler are responseText & responseXML
responseText - (string) The returned text from the request.
responseXML - (mixed) The response XML from the request.
Request.JSON - Wrapped Request with automated receiving of
JavaScript Objects in JSON Format. Means it is made for json requests
and when it receives data it converts it to json object.
Here onSuccess Fired when the request completes. This overrides the signature of the Request success event.
The arguments returned to the attached Handler are responseJSON & responseText
responseJSON - (object) The JSON response object from the remote request.
responseText - (string) The JSON response as string.
Related
So what I'm trying to do, is send some jQuery variables to my PHP script using Ajax post. However, for some reason, I cannot set the PHP variables to contain the values of the jQuery variables.
I have tried multiple types of Ajax data, like forms (new FormData();) and arrays.
script.js
$.ajax({
url: 'file.php',
type: 'POST',
data: {
'document_id': document_id,
'section_id': section_id,
'active_state': active_state
},
beforeSend: function () {
console.log('the data is: ' + document_id + section_id + active_state + '...');
},
success: function (response) {
console.log(response + ' is locked!');
},
fail: function (error) {
console.log(error + ' could not be locked');
});
file.php
print_r($_POST);
However, in the success function of the Ajax request, I DO receive an array back with the proper variables. When I check the output of the PHP file, it just returns a blank array.
This is what I eventually need to do:
if(isset($_POST['document_id'])){
$document_id = $_POST['document_id'];
$section_id = $_POST['section_id'];
$active_state = $_POST['active_state'];
// echo back the data to the success function
// proceed with insert into database
} else {
echo 'the data has not been set';
}
Any insights on what I may be doing wrong?
Try to use this to get the response from ajax request
<?php
extract($_POST);
print_r($_POST);
?>
I'm using jquery multiselect plugin and I want to perform an ajax request on a select/deselect event.
My problem: When I send the request to the php file, ISSET(VAR) returns every time false so that I can't pass variable to the php file.
But Firebug extension for Chrome/Firefox shows me that the POST value is set right POST -> "Response myvar" but GET is empty.
How do I pass the variable to the php file?
(I've searched arround the web but found nothing.)
My script, where this pointer is from the multiselect plugin and afterSelect returns if a object is selected
afterSelect: function()
{
this.qs1.cache();
this.qs2.cache();
count++;
var dataString = "count=" + count;
if ( count > 0 )
{
$.ajax
({
type: 'POST',
url: 'page-to-send-request.php',
data: dataString,
success: function()
{
$("#div-to-load").load("page.php #div-to-load").fadeIn('slow');
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(thrownError);
}
});
}
},
The php page to load has for test only
if($_POST['count'])
{
$count = $_POST['count'];
echo "Count " .$count;
}
else{ echo "FALSE"; }
Expected result should be
Count 5
But real output is
FALSE
1st try
success: function(data)
{
console.log(data);
},
it should output "Count " .$count; if not
try to use
var dataString = {count: count};
and then you can use
$("#div-to-load").html(data).fadeIn('slow');
the reason of return false .. you used the .load to load the php page .. when you load it .. javascript know it as a separated page .. so $_POST['count'] is undefined in this case . and It will return False always
your success function should be like this
success: function(data)
{
$("#div-to-load").html(data).fadeIn('slow');
},
I am using an inline jquery ajax to delete a list one by one. When giving an action to delete a list, the ajax will send some post data and the response is json encoded. Upon successful response, a pop up box will open in the first ajax success field asking for the username and password. Then an inline ajax will execute there, sending the pop up box's values along with the response from first ajax. I have given a condition in the inline ajax success field to validate the response for the second posted values. The response is coming true but the condition fails, i don't know why. Please refer the code...
$('.deleteButton').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: 'phpPage.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize() + "&del=del",
success: function (d) {
$(".popupContainer").show();
var text = "Do you really want to delete the report dated:";
$('#info').text(text);
$('#delForm').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: 'delRept.php',
type: 'POST',
data: $(this).serialize() + "&vtime=" + d.vtime + "&vdate=" + d.vdate + "&delbox=delbox",
success: function (data) {
if (data == 'string') {
$('#rrr').append("True : Delete it");
} else {
$('#rrr').append(data);
}
}
});
});
return false;
}
});
});
Here it will execute the else condition even if the response is true. Please help me to find the mistake in the coding...
Thanks
I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3
i have some problems with collecting the data i fetch from database. Dont know how to continue.
What i did so far:
JQ:
$(document).ready(function(){
$('#submit').click(function(){
var white = $('#white').val();
$.ajax({
type:"POST",
url:"page.php",
data:{white:white}
});
});
});
PHP (requested page.php) so far:
$thing = mysql_real_escape_string($_POST["white"]);
..database connect stuff..
$query = "SELECT * FROM table1 WHERE parameter='$thing'";
if($row = mysql_query($query)) {
while (mysql_fetch_array($row)) {
$data[]=$row['data'];
}
}
What i dont know, is how to send out data and receive it with ajax.
What about errors when request is not succesful?
How secure is ajax call against database injection?
Thanks :)
You'll need a success parameter in $.ajax() to get a response once a call is made
$('#submit').click(function(){
var white = $('#white').val();
if(white == '')
{
// display validation message
}
else
{
$.ajax({
type:"POST",
url:"page.php",
data:{"white":white}
success:function(data){
$('#someID').html(data);
}
});
});
Whatever you echo (HTML tags or variables) in page.php will be shown in the element whose ID is someID, preferable to keep the element a <div>
In page.php, you can capture the value entered in the input element by using $_POST['white'] and use it to do whatever DB actions you want to
To send out data to you can write following line at the end :
echo json_encode($data);exit;
To receive response and errors when request is not successful in ajax :
jQuery.ajax({
type:"POST",
url:"page.php",
data:{white:white},
asyn: false,
success : function(msg){
var properties = eval('(' + msg + ')');
for (i=0; i < properties.length; i++) {
alert(properties[i]);
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
For Feeling more safety do the following things:
1. Open a Session.
2. Detect Referrer.
3. Use PDO Object instead mysql_real_escape_string
4. Detect Ajax call :
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) ||
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !='xmlhttprequest') {
//Is Not Ajax Call!
}