jquery: calling invisible php-mailer? ajax? - php

hey guys,
i know how to create a simple php file that mails some information to me.
However what I don't know is how to call that php-file with jquery and hand over a variable.
Handing over a variable might work with isset()...
How can I call this PHP mailer from jquery and do that HIDDEN from the user. So there should not pop up a new window and shouldn't be a page refresh or anything like that.
$('a.report').click(function(e) {
e.preventDefault();
var id = $(this).attr('href');
//call mail script and pass along the "id" variable
//change text (maybe in a callback function IF THE MAILING WAS A SUCCESS.
$(this).parent().text('Thank you for reporting.');
})
So I have this a.report Link which should trigger the email script. In my email script I need to access the "id" variable set in jquery. And it would even be nice to have a callback function if the php script did it's thing so I could output "Thank you for reporting".
How to do that?
Thank you guys.

I would use $.post():
<script type='text/javascript'>
$(function(){
function onReportPosted(data) {
// data.status - either 'error' or 'success', from mailer.php
// data.message - some text, from mailer.php
$('.result').text(data.message);
}
$('a.report').click(function(e) {
$('.result').text('sending report...');
var data = {
text: $('textarea[name=text]').val()
};
$.post(
'mailer.php',
data,
onReportPosted,
'json'
);
return false;
});
});
</script>
And in mailer.php:
<?php
if ( isset($_POST['text']) ) {
// mail()...
$result = array(
'status' => 'success',
'message' => 'thank you for reporting',
);
} else {
$result = array(
'status' => 'error',
'message' => 'some error occurred',
);
}
header('Content-Type: application/json');
echo json_encode($result);
exit;
Update: here's a way how to "tie" callback to a specific element:
<script type='text/javascript'>
$(function(){
$('a.report').click(function(){
var htmlElement = $(this).parent();
var data = {
// ...
};
$.post(
document.location.toString(),
data,
function(data) {
htmlElement.html(data.message);
},
'json'
);
return false;
});
});
</script>

see $.post to know how to call and pass the id to the php script (http://api.jquery.com/jQuery.post/)
It will be somthing like
$.ajax({
context: $(this),
type: 'POST',
url: 'script.php',
data: {id: id },
success: function() {
$(this).parent().text('Thank you for reporting.');
}
});
And in the php script, $id = $_POST['id'];

try:
$.post('script.php', {variableName: value, variable2Name: value2});
in php: $value = $_REQUEST['variableName']; $value2 = $_REQUEST['variable2Name'];

jQuery provides some great AJAX methods for us under the AJAX API catagory. I think $.post would be what you're looking for. This is how I send JSON data to a simple PHP script in my Grooveshark userscript:
$.ajax({
type: 'POST',
url: 'http://path/to/script.php',
data: JSON.stringify({key: 'value', array: ['one', 'two', 'three']),
dataType: 'json',
success: function(data){
console.log('Mailer returned with object ', JSON.parse(data) );
}
});
And here's how I parse it in PHP:
$incoming = json_decode(file_get_contents("php://input"), true);
This returns nested associative arrays for the JSON content, very easy to parse! I highly recommend using JSON as your data interchange format. Much better than XML.

Related

Simple success/error return with ajax and php

Just starting to learn about ajax although I am running into trouble trying to return a success message in an array.
<script type="text/javascript">
$(function () {
$('#delete').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize()
}).done(function (response) {
if (response.success) {
alert('Saved!');
} else {
alert('Some error occurred.');
}
});
});
});
</script>
<?php
$array = array();
$array['success'] = TRUE;
echo $array;
?>
response.success should refer to $array['success'] correct?
You are trying to echo your array, which will just spit out "Array".
Instead you need to encode your array as JSON and echo that out.
Change this:
echo $array;
To this:
echo json_encode($array);
Also you probably need to add your dataType in your ajax params so jQuery auto-parses the response:
dataType : 'json' // stick this after "data: $form.serialize()" for example
Also, here's a good post to read on how to properly handle success/errors with your ajax calls (thanks #Shawn):
Jquery checking success of ajax post

Send data from Javascript to PHP and use PHP's response as variable in JS

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

How to return PHP variables on success AJAX/jQuery POST

How do I use AJAX to return a variable in PHP? I am currently using echo in my controller to display a price on dropdown .change in a div called price.
However I have a hidden field which I need to return the row id to on change. How do I assign the return var in jQuery so that I can echo it in my hidden field?
jQuery
$(document).ready(function() {
$('#pricingEngine').change(function() {
var query = $("#pricingEngine").serialize();
$('#price').fadeOut(500).addClass('ajax-loading');
$.ajax({
type: "POST",
url: "store/PricingEngine",
data: query,
success: function(data)
{
$('#price').removeClass('ajax-loading').html('$' + data).fadeIn(500);
}
});
return false;
});
});
Controller
function PricingEngine()
{
//print_r($_POST);
$this->load->model('M_Pricing');
$post_options = array(
'X_SIZE' => $this->input->post('X_SIZE'),
'X_PAPER' => $this->input->post('X_PAPER'),
'X_COLOR' => $this->input->post('X_COLOR'),
'X_QTY' => $this->input->post('X_QTY'),
'O_RC' => $this->input->post('O_RC')
);
$data = $this->M_Pricing->ajax_price_engine($post_options);
foreach($data as $pData) {
echo number_format($pData->F_PRICE / 1000,2);
return $ProductById = $pData->businesscards_id;
}
}
View
Here is my hidden field I want to pass the VAR to every-time the form is changed.
" />
Thanks for the help!
Well.. One option would be to return a JSON object. To create a JSON object in PHP, you start with an array of values and you execute json_encode($arr). This will return a JSON string.
$arr = array(
'stack'=>'overflow',
'key'=>'value'
);
echo json_encode($arr);
{"stack":"overflow","key":"value"}
Now in your jQuery, you'll have to tell your $.ajax call that you are expecting some JSON return values, so you specify another parameter - dataType : 'json'. Now your returned values in the success function will be a normal JavaScript object.
$.ajax({
type: "POST",
url: "...",
data: query,
dataType: 'json',
success: function(data){
console.log(data.stack); // overflow
console.log(data.key); // value
}
});
echo json_encode($RESPONDE);
exit();
The exit is not to display other things except answer. RESPONDE is good to be array or object.
You can access it at
success: function(data)
{ data }
data is the responde array or whatever you echo..
For example...
echo json_encode(array('some_key'=>'yesss')); exit();
at jquery
success: function(data){ alert(data.some_key); }
if u are returning only single value from php respone to ajax then u can set it hidden feild using val method
$("#hidden_fld").val(return_val);

Jquery .ajax doesn't return useful data

I have a jquery script in my file that says this:
<script type="text/javascript">
$(document).ready(function(e){
$('#myButton').click(function(e){
var formdata = {name: 'Alan', hobby: 'boxing'};
var submiturl = 'http://localhost/cake/gronsters/testJSON/';
$.ajax({
type: "POST",
url: submiturl,
data: formdata,
success: function(message){
console.log(message);
}
});
e.preventDefault();
})
});
Then I have a php script at testJSON that says this:
public function testJSON(){
$name = $this->request->data['name'] . '-Sue';
$hobby = $this->request->data['hobby'] . ' for donuts';
$data = array( 'name' => $name, 'hobby' => $hobby);
echo json_encode($data);
}
The place where console.log looks for message gives me {"name":"Alan-Sue","hobby":"boxing for donuts"}, which seems correct, except that it's immediately followed by the full html of my web page. And if I try console.log(message.name) it says 'undefined.'
What's going on here?
it sounds like your /testJSON/ page is outputting more than just whats written in your public function. if you are using an mvc or any kind of framework, you must immediately exit or die after that echo json_encode, otherwise the other part of the page will still render, probably.
You're on the right path, although as others have mentioned, it seems like you are using a MVC framework for your website and it is including the content of your webpage after displaying the JSON string. jQuery/JavaScript cannot parse JSON if there are other random text or characters in the response. You will need to use exit; or die(); after the JSON is echo'ed as the following example shows...
public function testJSON(){
$name = $this->request->data['name'] . '-Sue';
$hobby = $this->request->data['hobby'] . ' for donuts';
$data = array( 'name' => $name, 'hobby' => $hobby);
// Will halt the script and echo the json-encoded data.
die(json_encode($data));
}
Also, you will want to make sure that jQuery is parsing the response as JSON. By default it will attempt to make an intelligent guess of which type of data is being returned, but you cannot always rely on that. You should add the dataType option to the AJAX call like in the following example...
<script type="text/javascript">
$(document).ready(function(e){
$('#myButton').click(function(e){
// It is best practice to "preventDefault" before any code is executed.
// It will not cause the ajax call to halt.
e.preventDefault();
var formdata = {name: 'Alan', hobby: 'boxing'};
var submiturl = 'http://localhost/cake/gronsters/testJSON/';
$.ajax({
type: "POST",
url: submiturl,
data: formdata,
// This is the proper data type for JSON strings.
dataType: 'json',
success: function(message){
// JSON is parsed into an object, so you cannot just output
// "message" as it will just show "[object Object]".
console.log(message.name);
}
});
});
});
</script>
I've included some comments in the code to help better explain. Hopefully this will help you out a bit more. You also do not need to using the full $.ajax function unless you plan on using error handlers or any other of the more advanced options within that function. Alternatively, you can shorten your code by using $.post and accomplish the same as your original example with less code.
<script type="text/javascript">
$(document).ready(function() {
$('#myButton').click(function(e){
e.preventDefault();
var formdata = {name: 'Alan', hobby: 'boxing'};
var submiturl = 'http://localhost/cake/gronsters/testJSON/';
$.post(submiturl, formdata, function(message) {
console.log(message.name);
});
});
});
</script>
More options and usage information about $.ajax jQuery.ajax();
More information about $.post jQuery.post();
Parse the message variable as json before trying to log message.name.
data = $.parseJSON(message);
console.log(data.name);
Also do an exit in the php script after the echo statement and check..

PHP: Retrieving JSON via jQuery ajax help

Hey I have a script that is creating and echoing a JSON encoded array of magento products.
I have a script that calls this script using jQuery's ajax function but I'm not getting a proper response. When the GET request is performed firebug displays
GET http://localhost.com/magento/modules/products/get.php 200 OK then a **red cross** then 361ms
This is the script that creates the array:
// Load product collection
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('price');
$products = array();
foreach ($collection as $product){
$products[] = array("price" => $product->getPrice(),
"name" => $product->getName() );
}
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($products));
Here is my jQuery:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://localhost.com/magento/modules/products/get.php",
success: function(products)
{
$.each(products,function()
{
var opt = $('<option />');
opt.val(this.name);
opt.text(this.price);
$('#products').append(opt);
});
}
});
})
</script>
I'm getting a response from this but I'm not seeing a any JSON. I'm using firebug. I can see there has been a JSON encoded response but the response tab is emtyp and my select boxes have no options.
Can anyone see and problems with my code?
Here is the response I should get (and do get when I run the script manually via the browser):
[{"price":"82.9230","name":"Dummy"},{"price":"177.0098","name":"Dummy 2"},{"price":"76.0208","name":"Dummy 3"},{"price":"470.6054","name":"Dummy 4"},{"price":"357.0083","name":"Dummy Product 5"}]
Thanks,
Billy
use cache: false, as one of your AJAX parameters...
I know when i used JSON in AJAX, i had to do this:
success: function(data) {
$(".custName, .projectDesc").empty();
for(var x in data) {
$(".custName").append(data[x].message1);
$(".projectDesc").append(data[x].message2);
}
I'm not sure if this will help you or not :)
The PHP you're returning is not an array of objects, which is the way you are treating it in your javascript.
Change your PHP to:
$products = array();
foreach( $collection as $product ) {
$products[] = array( "price" => $product->getPrice(),
"name" => $product->getName() );
}
This should return JSON that looks like:
[{"price":"82.9230","name":"Dummy"},{"price":"177.0098","name":"Dummy 2"}, etc ]
jQuery.each should then be able to iterate over the returned array of objects:
success: function(products)
{
jQuery.each(products,function()
{
var opt = jQuery('<option />');
opt.val(this.name);
opt.text(this.price);
jQuery('#products').append(opt);
});
}
$.each(products,function(index, arr)
{
var opt = $('<option />');
opt.val(arr[name]);
opt.text(arr[price]);
$('#products').append(opt);
});
I hope it helps you
Try to add data type property on $.ajax configuration object:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://localhost.com/magento/modules/products/get.php",
dataType : 'json',
success: function(products) {
$.each(products,function() {
var opt = $('<option />');
opt.val(this.name);
opt.text(this.price);
$('#products').append(opt);
});
}
});
})
</script>
Maybe, $.ajax function doesn't know the response data type...
Add dataType: 'json' in jQuery.ajax parameter

Categories