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);
}
});
Related
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.
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);
}
});
});
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);
}
});
}
});
Hi all I have a AJAX query which I am calling using an onclick function as seen below, the query successfully POSTs the data from the form I have on my page - and I can use the data on my php script without an issue:
function tempFunction(obj){
var no= $(obj).attr('id');
$.ajax({
type: "POST",
url: "/tempproject/main/changepage",
data: $('form').serialize(),
success: function(msg){
alert( "success: " + msg ); //Anything you want
}
});
window.alert(no);
}
However I wish to also send the variable no along with the form data, I am a complete newbie when it comes to JS so could someone point me in the right direction of how to send the variable along with the serialized form data? can I append the serial data somehow? I feel this is probably really easy but I'm to new to JS
try this
function tempFunction(obj) {
var data = $('form').serializeArray();
data.push(
{
no: $(obj).attr('id')
}
);
$.ajax({
type: "POST",
url: "/tempproject/main/changepage",
data: data,
success: function (msg) {
alert("success: " + msg); //Anything you want
}
});
window.alert(no);
}
You may try to use jQuery Form plugin.
It allows ajax submitting form transparently, without worrying about serizalization.
Plugin: http://malsup.com/jquery/form/
Your code:
$('#form').ajaxSubmit({
data: { no: $(obj).attr('id') },
url: "/tempproject/main/changepage",
success: function(msg){
alert( "success: " + msg ); //Anything you want
}
});
I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});