Return PHP Variable to Jquery - javascript

I have a page called index.php where I have some forms where the user must input information.
On this page I have this JQuery functions.
else if (result == 3)
{
jQuery.get('sample.txt', function(data) {
alert(data);
});
}
where the file sample.text its shown on an alert.
But, I have a page called download.php. When the user click on "submit" at page "index.php" , its send to the page "download.php", the values sent using Ajax POST.
var formData = new FormData($('#form_principal')[0]);
$("#loading").show();
setTimeout(function() {
$.ajax({url: "/tkclientespdo/etiquetaslog/000/0000/download.php",
type: "post",
data: formData,
cache: false,
async:true,
contentType: false,
processData: false,
success: function(result)
on page "download.php" i have this variable :
$horaenvio = date("dmYGis");
after this variable i have a code :
echo 3;
that return the function at index.php .
but i wanna change 'sample.txt" for the variable "$horaenvio".
someone could help.

You can use localStorage and storage event or SharedWorker to store the value data at index.php, and get the value at download.php, then .append() data to the FormData object, then echo the proper POST value.

Related

ajax success but not post data in the another page

i have this simple code:
var addUser = "simply";
$.ajax({
type: 'POST',
url: 'userControl.php',
data: {addUser: addUser},
success: function(response){
alert("success");
}
});
this is the page that i POST to: userControl.php, the if statement not entering so i didnt post? but i got alert message "success".
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){ //if page was requested with POST
echo $_POST['addUser'];
}
?>
I got the alert message "success", but the data is not POST to the other page.
Im also try out to write 'simply' with one apostrophe. in another page in the same project i have a same Ajax and its working, so why this one not working? any ideas? i need to do it only with ajax, submit with form will not help me.
thanks
Pass data this way data: 'addUser=' + addUser
see below code
var addUser = "simply";
$.ajax({
type: 'POST',
url: 'userControl.php',
data: 'addUser=' + addUser,
success: function(response){
alert("success");
}
});
and you should remove window.location because it is possible before your ajax call completes page will redirect

How can I use jquery function-1 variable value, inside function-2?

I have 2 jQuery events occurring inside a form. There is one select element inside a form:
Event 1 is on select change. It's storing the selected option value in a variable:
$('#sm_name').change(function(){
var option_value = $('#sm_name option:selected').val();
console.log(option_value);
});
Event 2 is on form submit using $.ajax():
$("#fb_form").on('submit', function (e) {
e.preventDefault();
$("#message").empty();
$("#loading").show();
$.ajax({
url: "submit.php",
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) { // A function to be called if request succeeds
}
});
});
How can I change the AJAX URL dynamically for each selected value from the select dropdown? Something like this:
url: "submit.php?id=" + option_value,
You can just read the value of the select within the submit handler:
$("#fb_form").on('submit', function (e) {
e.preventDefault();
$("#message").empty();
$("#loading").show();
$.ajax({
url: "submit.php?id=" + $('#sm_name').val(),
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
// do something on request success...
}
});
});
Note the use of val() directly on the select element - you don't need to access the selected option to get the value.
You can directly get value from dropdown to submit form to the url which is selected in dropdown
url: "submit.php?id="+$('#sm_name').val()
This is not specific to jQuery, in JavaScript you can use a feature called closures to use variables from outer scope:
var outerScopeVariable = null;
function a() {
outerScopeVariable = 'hello world';
}
function b() {
console.log(outerScopeVariable); // will output 'hello world' if
// function a() has previously been called.
}

Ajax change php variable

I've got this variable $type and I want it to be month or year.
It should be changed by pressing a div.
I've tried creating an onclick event with an ajax call.
The ajax call and the variable are in the same script (index.php)
Inside the onclick function:
var curr_class = $(this).attr('class');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
But the alert returns the whole html page.
When I console.log the data (create a var data = { type:curr_class }) and console.log *that data* it returnstype = month` (which is correct)
while I just want it to return month or year
So on top of the page I can call
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
}
and change the PHP variable so I can use it in the rest of my script.
But how can I accomplish this?
With kind regards,
as you are sending request to the same page so as a result full page is return .You will have to send it to another page and from that page return the type variable
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
echo $type;
keep this code in separate file and make an ajax call to that page
//Try This It's Work
Get Value
Get Value
$(".btn-my").click(function(){
var curr_class = $(this).data('title');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
});

Get php return value using ajax

I am having a form which gets value from the user and stores it to the database.
On submitting the form ,it calls the action.php file using ajax call.
e.preventDefault();
$.ajax({
type: "POST",
url: "action.php",
data: senData,
dataType: "JSON",
success: function(data) {
$("#name").val("");
$('.msg').fadeIn(500);
$('.msg').text("" + data.result + "");
}
});
The values are stored in the database without any errors, but I want to display a notification to the user after submitting the form inside the msg div.
In my action.php file I have added a JSON Encode statement to return a message too.
$msg = 'Thanks Yo Yo';
echo json_encode(array("result" => $msg));
But it is not working i.e, when I submit the form, it stores the data to the database and the webpage refreshes itself without displaying any message inside the .msg div.
Am I doing something wrong and is there a better way to do it??
You need to parse the JSON when it is returned to your javascript.
// Parse the response to JSON
var res = JSON.Parse(data);
$('.msg').text(res.result);
Your code should look like this.
e.preventDefault();
$.ajax({
type: "POST",
url: "action.php",
data: senData,
dataType: "JSON",
success: function(data) {
var res = JSON.Parse(data);
$("#name").val("");
$('.msg').fadeIn(500).text(res.result);
}
});

How to catch array sent by PHP script as Ajax response and use further?

I am working on an e-commerce project for practice and right now I am building product filters. So I have three files
catalogue.php
It basically shows all the products.
product filters on left and displays products on right. When user checks a box then AJAX call is made.
productsfilter.js
It contains Javascript and AJAX calls.
var themearray = new Array();
$('input[name="tcheck"]:checked').each(function(){
themearray.push($(this).val());
});
if(themearray=='') $('.spanbrandcls').css('visibility','hidden');
var theme_checklist = "&tcheck="+themearray;
var main_string = theme_checklist;
main_string = main_string.substring(1, main_string.length)
$.ajax({
type: "POST",
url: "mod/product_filter.php",
data: main_string,
cache: false,
success: function(html){
replyVal = JSON.parse(myAjax.responseText);
alert(replyVal);
}
});
product_filter.php
It is the PHP script called by the AJAX call.
$tcheck = $objForm->getPost('tcheck');
if(!empty($tcheck)) {
if(strstr($tcheck,',')) {
$data1 = explode(',',$tcheck);
$tarray = array();
foreach($data1 as $t) {
$tarray[] = "adv.attribute_deterministic_id = $t";
}
$WHERE[] = '('.implode(' OR ',$tarray).')';
} else {
$WHERE[] = '(adv.attribute_deterministic_id = '.$tcheck.')';
}
}
$w = implode(' AND ',$WHERE);
if(!empty($w))
{
$w = 'WHERE '.$w;
}
$results = $objCatalogue->getResults($w);
echo json_encode($results);
So product_filter.php returns an array of product_ids retrieved from the database and gives it back to AJAX. Now the problem is: that array of product ids I got from AJAX call, how do I use it in catalogue.php?
As I got {["product_id" : "1"]} from product_filter.php, I want to use this id in catalogue.php and find the related attributes and display the product details.
How can I pass this array to my catalogue.php page so that it can use this array and call further PHP functions on it?
If the question is unclear then kindly say so, and I will try to explain it as clearly as I can. Help would be much appreciated.
It seems you want to get data from one php and send it to a different php page then have the ajax callback process the results from that second page.
You have at least 2 options
Option 1 (the way I would do it)
In product_filter.php, near the top, do this
include('catalogue.php');
still in product_filter.php somewhere have your function
function getFilterStuff($someDataFromAjax){
// ... do some stuff here to filter or whatever
$productData = getCatalogueStuff($results);
echo json_encode($productData);
exit;
}
In catalogue.php somewhere have that function
function getCatalogueStuff($resultsFromFilter){
// ... get product data here
return $productData;
}
Then in your Ajax do this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (response) {
replyVal = response;
alert(replyVal);
}
});
Option 2
Nested ajax calls like this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (filterResponse) {
$.ajax({
type: "POST",
dataType: "json", // add this
url: "catalogue.php",
data: filterResponse,
cache: false,
success: function (catalogueResponse) {
alert(catalogueResponse);
}
});
}
});

Categories