I originally had a regular HTML form that submitted the data entered through a button, which redirected the user to the PHP code page ran the code and everything worked.
Since everything now is confirmed working I need to pass the variables in the form to PHP using Ajax instead to keep the user on the original page.
All of my code checks out everywhere except for any Ajax request I use in the below function. The function correctly grabs all the variables from the form but no matter what form of Ajax or $.post that I use it fails to pass anything.
I am trying to pass all data to http://localhost/send-email.php and respond to the user with a pop up including the echo response from the PHP code.
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"
function capacity(){
var fullname = document.getElementById("fullname").value;
var time = document.getElementById("time").value;
var aux = document.getElementById("aux").value;
var issue = document.getElementById("issue").value;
var issueid = document.getElementById("issueid").value;
var reason = document.getElementById("reason").value;
}
Like I said I read all documentation on Ajax and followed many examples on here but i could not get anything to work. Any help on what my Ajax call should look like is appreciated.
There are a couple of different ways you can POST in the backend.
Method 1 (POST Serialize Array from Form) -
jQuery.post()
$.post('/send-email.php', $('form').serializeArray(), function(response) {
alert(response);
});
Method 2 (Structure Object and POST Object) -
jQuery.post()
var formObject = {
fullname: $('#fullname').val(),
time: $('#time').val(),
aux: $('#aux').val(),
issue: $('#issue').val(),
issueid: $('#issueid').val(),
reason: $('#reason').val()
};
$.post('/send-email.php', formObject, function(response) {
alert(response);
});
Method 3 (Use AJAX to POST Serialize Array from Form) -
jQuery.ajax()
$.ajax({
method: 'POST',
url: '/send-email.php',
data: $('form').serializeArray(),
}).done(function(response) {
alert(response);
});
Method 4 (Use AJAX to POST Form Data) -
jQuery.ajax() - FormData Objects
var formData = new FormData();
formData.append('fullname', $('#fullname').val());
formData.append('time', $('#time').val());
formData.append('aux', $('#aux').val());
formData.append('issue', $('#issue').val());
formData.append('issueid', $('#issueid').val());
formData.append('reason', $('#reason').val());
$.ajax({
url: '/send-email.php',
dataType: 'json',
contentType: false,
processData: false,
data: formData,
type: 'POST',
success: function(response) {
alert(response);
}
});
Virtually, there are many different methods to achieving what you are attempting.
Related
I need to store a piece of data, into PHP variable, which is received through AJAX response in an input box. How can I do this?
<script type="text/javascript">
$(document).ready(function() {
$("#user_id").change(function() {
var id = $(this).val();
var dataString = 'user_id='+ id;
$.ajax({
type: "POST",
url: "wmat_details.php",
data: dataString,
cache: false,
success: function(result) {
var data = result.split(",");
$('#name').val(data[0]);
$('#email').val(data[1]);
$('#ref_id').val(data[2]);
$('#candidature_start').val(data[3]);
$('#candidature_end').val(data[4]);
$('#default_attempts').val(data[5]);
$('#existing_complimentary').val(data[6]);
$('#wmat_start').val(data[9]);
$('#wmat_end').val(data[10]);
$('#attempts_taken').val(data[11]);
}
});
});
});
</script>
As shown in above code, I want to store $('#attempts_taken').val(data[11]); this value to a PHP variable. Any insight is appreciated.
Unfortunately you can't.
PHP is server side while jQuery (JS) is client side. They are two separate layers of abstraction that interact only when the client call the server.
I don't have enough informations about what you need to do with data[11] but it seems that you have only one option: make a consecutive AJAX call to the php file that will manipulate data[11].
The consecutive AJAX call must be executed from inside the first call success callback; something like this:
success: function(result){
// Your on success logic
// ...
// Prepare the object to send to the server
var objData = {};
objData.attemptsTaken = data[11];
// Execute the second AJAX call to the server
$.ajax({
type: "POST",
url: "second_call_destination_file.php",
data: objData,
success: function(result){
// Do something on success
},
error: function(){
// Do something on error
},
complete: function(){
// Do something on complete (executed after success and error)
}
}
You cannot store ajax response into a php variable.
way 1 :
You can make another ajax call.
way 2 :
you can set session.
I don't how to ask this question but if their are duplicates send me that. Their are several .php files i have made
content.php, show.php and showFilteredResult.php .
content.php sends the start date and end date to the show.php and it returns the the orderIds which are of that date
$(document).ready(function () {
var srt = $("#cal1Date1").val();
var end = $("#cal1Date2").val();
$.ajax({
url: "http://localhost/show.php",
data: {
srt: srt,
end: end
},
type: "POST",
dataType: "json",
complete: function (response) {
$rtndata = response.responseText;
var dat1a = jQuery.parseJSON($rtndata);
var result = dat1a.OrderID;
console.log(result[0]); // send this result
}
});
});
now I want to send this $result with orderids to showFilteredResult.php where then i can make tables etc.
I'd skip the AJAX and just use request parameters (GET or POST).
cal1Date1 and cal1Date2 are input fields I assume. Wrap them in a form and post the values to a PHP form handler that could handle the lookup and display. No need for the AJAX middle-man here.
Just make a similar Ajax request to showFilteredResult.php I would have them in a separate function.
function showFilteredResult($result){
$.ajax({
url:"http://localhost/showFilteredResult.php",
data: {
result:$result
},
type:"POST",
dataType: "json",
complete:function(response){
$rtndata=response.responseText;
var dat1a=jQuery.parseJSON($rtndata);
var result=dat1a.OrderID;
console.log(result[0]);// do something with the data returned from showFilteredResult.php
}
});
}
and from the request that you have just call that funciton like
... $rtndata=response.responseText;
var dat1a=jQuery.parseJSON($rtndata);
var result=dat1a.OrderID;
console.log(result[0]);// send this result
showFilteredResult(result[0]);
}
});
Instead making another request to server , you have another option to do that. Let's say you get orderId from show.php before sending back , right ? Then you can use this orderId to do what u want such as query which u have written in showFilteredResult.php . then return back to client for final result . In that way you can eliminate the unnecessary http request.
I'm working on the review page before a user buys a product, and on the page is a small field for discount codes, which I want to pass to an endpoint via ajax. I'm using the following javascript function, and the submission happens and returns (even hits the intended endpoint) - but no data gets passed through (verified in logs).
Any idea why no params would be getting passed through?
<script>
$("#discount_code_submit").click(function() {
var url = "/confirm_discount"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#discount_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
This is because jQuery's serialize method creates a String representation of the form data, in the traditional url query string format. (Please see here: http://api.jquery.com/serialize/)
E.g., calling serialize can return a string such as:
'?query=help&numResults=200'
On the other hand, jQuery's ajax method expects the form data to be provided as an object literal. (Please see here: http://api.jquery.com/jQuery.ajax/)
E.g.
{
query: 'help',
numResults: 200
}
So you can change your ajax call to look like:
$.ajax({
type: "POST",
url: url,
data: {
param1: 'somevalue',
param2: 200
},
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
Or, you could also construct your object literal from the form using a custom function and then provide the reference in the ajax call.
$.ajax({
type: "POST",
url: url,
data: myPreparedObjectLiteral,
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
You could also use http://api.jquery.com/serializeArray/ since it does pretty much what you'll need to convert a form to the json literal representation.
Finally, for a good discussion on converting forms to json objects for posting, you can see the responses here on an SO question: Convert form data to JavaScript object with jQuery
Here is a function that I have to write to an xml file through an ajax call. The code works fine the first time the ajax call is made. On the second each loop, the ajax call isn't made at all. I don't know why. I specified asyn to false. That did not help. That doesn't seem to be the problem anyway.
$('#'+divid).children('div').children('div').each(function () {
var url = $(this).find('a');
var urlname = url.text();
var urllink = url.attr('href');
var urlid = $(this).attr('id');
alert ("from javascript urlid: "+urlid+" urlname: "+urlname+" urllink: "+urllink);
$.ajax({
url: "add_url.php",
type: "POST",
data: { nodeid: divid, urlid: urlid, urlname: urlname, urllink: urllink },
cache: false,
async: false,
success: function (response) {
if (response != '')
{
alert(response);
}
}
});
});
This really works for me
http://jsfiddle.net/genesis/DTjZQ/4 (3 POST request sent with response status 404)
be sure that your html is good and with same structure as in my fiddle
Instead of making multiple AJAX requests, I suggest appending the data to an array and then sending the entire array of objects.
(Basically the literal object you're using for data would be appended to an array instead of used in a request, and then once the each is done, you would send the array as the data.)
I'm got a form laid out like a spreadsheet. When the user leaves a row, I want to submit fields from that row to the server using jQuery Ajax. The page is one large form, so this isn't really a javascript clicking the submit button scenario - the form is huge and I only want to send a small portion of the content for reasons of speed.
I've got the code written that identifies the row and iterates through the fields in the row. My issue is how to build the dat object in order to submit something comprehensible I can disassemble and store at the server end.
At the moment my code looks like this
var dat=[];
$("#" + finalrow).find("input").each(function () {
var o = $(this).attr("name");
var v = $(this).val();
dat.push({ o: v });
});
$.ajax({
url: 'UpdateRowAjax',
dataType: 'json',
type: 'POST',
data: dat ,
success: function (data) {
renderAjaxResponse(data);
}
});
The assembling of dat doesn't work at all. So how should I build that dat object in order for it to "look" as much like a form submission as possible.
You can add the elements that contain the data you want to send to a jQuery collection, and then call the serialize method on that object. It will return a parameter string that you can send off to the server.
var params = $("#" + finalrow).find("input").serialize();
$.ajax({
url: 'UpdateRowAjax',
type: 'POST',
data: params ,
success: function (data) {
renderAjaxResponse(data);
}
});
You can use $.param() to serialize a list of elements. For example, in your code:
var dat= $.param($("input", "#finalrow"));
$.ajax({
url: 'UpdateRowAjax',
dataType: 'json',
type: 'POST',
data: dat ,
success: function (data) {
renderAjaxResponse(data);
}
});
Example of $.param(): http://jsfiddle.net/2nsTr/
serialize() maps to this function, so calling it this way should be slightly more efficient.
$.ajax 'data' parameter expects a map of key/value pairs (or a string), rather than an array of objects. Try this:
var dat = {};
$("#" + finalrow).find("input").each(function () {
dat[$(this).attr('name')] = $(this).val();
});