A part of AJAX response storing in PHP variable - javascript

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.

Related

Issues passing form data to PHP using Ajax

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.

how to send data from one web page to another?

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.

How to pass json data from one javascript to another

Guys here the first script is designed to take static .json files to display certain content and animate them. The code snippet is
var self = this;
$.getJSON('data/post_'+ index +'.json', function(d){
self.postCache[index] = d;
callback(d)
but I want to modify it to so it could take data from database. I got the data in the same format as it was in static json files and my question is how can I pass that data to this script so that it work as it should.
I am sending request using ajax
$(function ()
{
$.ajax({
url: 'api.php',
data: "<?php echo $data?>",
dataType: 'json',
success: function(data)
{
//I really dont know what to write here :(
}
});
});
and the api.php file is getting data from database and I an encoding the data to json using json_encode
var self = this;
$.post('api.php',
{"post_id": index},
success: function(d)
{
self.postCache[index] = d;
callback(d);
});
see http://api.jquery.com/jquery.post/
In api.php do a SQL query where the post_id = $_POST['post_id'] then echo json_encode($database_row);
$.getJSON just calls $.ajax with some predefined values automatically set for you. This means, since you said the data is the same, that you can do exactly the same as you were doing previously.
Keep a reference to this
Make your async call
in the success function, save your reference and execute your callback
var self = this;
$.ajax({
url: 'api.php',
data: "<?php echo $data?>",
dataType: 'json',
success: function(data)
{
self.postCache[index] = data;
callback(data);
}
});

Setting string in javascript function in ASP.NET MVC give NullReferenceException

Inside my MVC view I have javascript that is executed by a button click. I'm trying to set a string to a random set of characters which I can get to work fine but when I try and set that string to 'randomchars' string inside the javascript I get a NullReferenceException when I try and run the view.
Below is the code snippet, the CreateRString is where the model parameter (RString) is set to the random string.
<script type="text/javascript">
function showAndroidToast(toast) {
var url = '#Url.Action("CreateRString", "Functions")';
$.ajax({ url: url, success: function (response) { window.location.href = response.Url; }, type: 'POST', dataType: 'json' });
var randomchars = '#(Model.RString)';
}
</script>
Is the syntax correct? I'm not too sure why it's getting the NULL.
The javascript is executed after the page been delivered to the client (i.e. web browser). Your razor code here is executed on the server before the page is sent to the client. Therefore, the ajax method will execute after you try to access Model.RString
To fix this you can either call CreateRString on the server, or you can set randomchars by using the response in the success callback.
To explain option 2 a bit further. You could do something like this:
//Action Method that returns data which includes your random chars
public JsonResult CreateRString()
{
var myRandomChars = "ABCDEF";
return new JsonResult() { Data = new { RandomChars = myRandomChars } };
}
//The ajax request will receive json created in the CreateRString method which
//contains the RandomChars
$.ajax({ url: url, success: function (response) {
var randomchars = response.Data.RandomChars;
window.location.href = response.Url;
}, type: 'POST', dataType: 'json' });
More specifically, the razor calls #Url.Action("CreateRString", "Functions") and #(Model.RString) execute first on the server.
Then showAndroidToast executes in the client's browser when you call it.

Ajax call within jquery each loop

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.)

Categories