Return variable from PHP after AJAX Post - javascript

I've read countless examples but I just can't get the following to work. I want to submit a form, process it on the server side then decide which php script to load into a div (dynamic loading I can do).
The head:
$.ajax({
type: "POST",
url: url, // passed with onclick
data: $("#" + formName).serialize(),
success: function(data) {
// Some JSON? to go here to store variable returned from PHP ($thisVariable)
}
});
return false; // avoid to execute the actual submit of the form.
The php:
// Process the request (add to database e.g.)
$thisVariable back to ajax

Related

What is the jquery data parameter for php file upload in this example?

I have an html page with a section that collects basic customer information: email, first and last name, etc. The form ends with a button for the end-user to click, and I'm using an onClick event to call a jquery script. The jquery script calls a php file to send the data to the server.
For example:
function postData() {
return $.ajax({
url : 'upload.php',
type: 'POST'
});
}
function sendReply() {
// autoresponder
}
postData().done(sendReply);
In some examples, I have seen a "data" parameter that would go in the postData function. For example:
function myAjax() {
$.ajax({
type: "POST",
url: 'your_url/ajax.php',
data:{action:'call_this'},
});
}
My question is: if I'm calling upload.php, will that automatically take the form data and process it in the php file, provded that the php file is coded correctly for form data upload (using $_POST['variable_name'];)? In other words, is the data parameter in this jquery code irrelevant when I'm calling a php file with html data?
I'm sorry if this question is very elementary, but I'm new to php and I've never done this before.

Unserialize data from a jquery ajax from and send email

I have a very long form in a php template, all data are send by a jquery ajax in serialize mode to a php page to send an email.
I have this problem: How I can unserialize the data in the php page, and send them by email ?
The php template is completed with different data. So I can't use for each fields just urldecode in this way $nome = urldecode($_POST['nome']);
I have to find a way for take all the data arrive in the php page and send them in an email. I read about parse_str But I don't know if can works and how use it.
At moment this is my ajax code:
var datiform = $("#FormWorkspace").serialize();
$.ajax({
type: "POST",
url: ".../form-cf/engine.php",
data: datiform,
dataType: "html",
success: function(datiform)
{
alert("success" + datiform);
},
error: function()
{
alert("no success " + datiform);
}
});
serializing in jquery means to actually create a string var1=1&var2=234. You can simple access the data using GET['var1'] or POST['var2'] in PHP.

jQuery AJAX reload specific div

I have the following code, as part of a code to add some value to a database.
After executing the $.ajax succesfully, I want a specific div (with class 'lijst') to be reloaded with the refreshed data.
$.ajax({
url: \"frontend/inc/functions/add_selectie.php\",
type: \"POST\",
data: ({ 'p_id' : p_id, 'v_id' : v_id, 'pd_id' : pd_id }),
cache: false,
success: function()
{
$(\".lijst\").hide().fadeIn('slow');
}
});
However, with this solution, only the div is refreshed, not the actual PHP variables that are specified in there. When I refresh my browser manually, the values are updated.
How can I refresh the div and also update the variables?
According to the jQuery.ajax documentation, the function signature of "success".
Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR ) A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server ...
So in other words:
success: function(data) {
$(".lijst").html(data).hide().fadeIn('slow');
}
Actually, the PHP variables specified in the html are worked at the sever part. PHP variables in the html have replaced by the string of there value when it is ready to be sent to the browser. And your ajax request will cause PHP to update database. So when you have sent the request and then refresh the page, PHP will replace the varables in the html again.
According to this above, your ajax request and the server repsonse are not aware of the PHP variables's existence. So you must update the content yourself.
Maybe you will do something like this:
success: function(data) {
$(".lijst").hide();
$(".title").html(data.title); // $(".title") may be a tag that surround a PHP variable
$(".content").html(data.content); // the same as $(".title")
$(".lijst").fadeIn('slow');
}

Return info from jQuery AJAX call and execute additional jQuery on success

I have the following jQuery AJAX to duplicate a background image. I am stumped as to how to effectively return information back to the original page. Here is the AJAX I send on click of "'#dupBtn"...
//DUPLICATE BACKGROUND
$('#dupBtn').click(function() {
jQuery.ajax({
type: "POST",
dataType:'json',
url: "../system/bgUpdate.php",
data: {
"user":<?= $_POST['user'] ?>,
"bgID":bgID,
"refID2":<?= $_POST['refID2'] ?>,
"refTable":"<?= $_POST['refTable'] ?>",
"bgTitle":($('#bgTitle').val()),
"path":path,
"bgColor":bgColor,
"bgPoz":bgPoz,
"bgRepeat":bgRepeat,
"attach":attach
}
});
});
Here is the basic MySQL query on the PHP page bgUpdate.php.
mysql_query("INSERT INTO backgrounds (user,title,path,bgColor,bgPosition,bgRepeat,bgAttachment) VALUES ('".$_POST['user']."','$title','".$_POST['path']."','$bgColor','".$_POST['bgPoz']."','$rt','$attach')");
$bgIDnew = mysql_insert_id();
What I want to do is have the following code fired on the original page upon successful execution of the MySQL entry, dynamically catching the '$bgIDnew' from the MySQL PHP page.
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
You can accomplish this with the success attribute of the .ajax() function:
$('#dupBtn').click(function() {
jQuery.ajax({
type: "POST",
dataType:'json',
url: "../system/bgUpdate.php",
data: {
...
},
success:
function(response)
{
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
});
});
That's only part of it though... The other half is that your PHP needs to return something that jQuery can understand as a "successful" call. My preference is to use HTTP status codes. In your case, your PHP script should return a 200 code if it was successful; otherwise, it should return something in the 400 range. (By the way, if you want jQuery to do something separate with errors, you can use the error property of .ajax().)
However, if you need to return data from the server to the client-side script, then your PHP can print out that information like this:
mysql_query("INSERT INTO backgrounds (user,title,path,bgColor,bgPosition,bgRepeat,bgAttachment) VALUES ('".$_POST['user']."','$title','".$_POST['path']."','$bgColor','".$_POST['bgPoz']."','$rt','$attach')");
$bgIDnew = mysql_insert_id();
// Best practice to keep it in some sort of understandable format
// Here, we'll put it in an associative array:
$response = array('id' => $bgIDnew);
print_r(json_encode($response));
This PHP script sends back to the ajax() method a JSON representation of the $response variable. You've already configured that ajax() method to read the response dataType as JSON, so it already knows how to read the response parameter... Which means your success function can look something like this:
success:
function(response)
{
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=' + response.id);
}
jQuery.ajax() has a success property that acts as a callback that you can use. Another is complete which is fired if the request is successful or not.
jQuery.ajax({
/* your stuff here */
success: function(response) {
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
});
You can write up the logic in the success callback function of your ajax Request..
This is fired when an ajax request is successfully returned..
success: function(response) {
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
Add this to your ajax Request...

Send content created by javascript in PHP mail?

I'm using a javascript shopping cart on a store, and I want to send an order confirmation on checkout. The problem is that the cart isn't saved in database of any kind, and is printed with javascript. How would I attach it to the email? I've included the shopping cart script on the page that sends the mail.
<table class="simpleCart_items"></table> would print the cart, but how would I attach the printed cart to email?
Hidden input or something?
UPDATE
My ajax call looks like this:
var data = $('#yhteystiedot').serialize();
data.cartContent = $('.simpleCart_items').html();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "order.php",
data: data,
dataType: "text",
error: function(){ alert("Jotakin meni pahasti pieleen! Yritä uudelleen?");
},
success: function() {
$(document).html("Tilaus lähti.");
}
});
You can make an ajax call to a php function that sends an email. The argument is the content generated by javascript.
You'll need to post the cart values to serverside PHP script and recreate the HTML for the cart in order to be able to send it through email. You can do direct form post or ajax post based on your need.
I asume your $.ajax() call looks something like this:
$('form').submit(function(){
var dataTrunk = $(this).serializeArray();
dataTrunk.push( { name: 'cartContent', value: $(your_table_selector).html()});
$.ajax({
url: 'mail.php', // your mail script
data: dataTrunk,
type: 'post'
});
return false;
});
In php you would trap $_POST['cartContent'] and render it in email and send it.
If you are sending email with html and plain text body, then it would probably be a good idea to strip html elements and replace them with chars that are compatible with plain text.
// edited: I've fixed the error

Categories

Resources