How to pass variable inside dom using ajax? - javascript

Sorry it was a mistake to post a question about making a condition to checkbox earlier without further investigation. It seems i need to pass my variables here
function setsession(sessionid,action, data){
$("#totalselection").show();
$.ajax({
type:'POST',
url:'test.php',
data:'sBorrow='+sessionid+'&action='+action,
cache:false,
success:function(data){
var out = "<p align='center' style='text-decoration:none;color:white;'>Total Selection: "+data+"<br/>Click here to submit your request <a href='borrowform.php?subid=borrow' id='submitborrow' name='submitborrow' style='text-align:center;'><input type='button' value='REQUEST' id='submitborrow' name='submitborrow'></a> || Click here to clear the selection <a href='#' style='text-align:center;'><input type='button' value='CLEAR'></a></p>";
datachecked(data, this.indexValue);
$("#totalselection").html(out)
}
});
}
to the DOM of other php page. NOT TO THIS URL. It was different page. Im still not clear to this ajax and i know that ajax can only send to 1 url only. However i want the data value that this ajax hold to put it inside my php echo and make if else statement using that data. Should i create one more ajax? or else? How to send data from success to my php page and received it?

I think you are asking how to send your variable in ajax call. Try this simple syntax of jquery ajax call by which you can send any number of variables.
$.ajax({
url : 'process.php',
method: 'post',
data : {
var1 : val1,
var2 : val2
// by this way you can send multiple variable
},
success : function(response){
alert(response)
}
});
process.php:
$val1 = $_REQUEST['var1'];
$val2 = $_REQUEST['var2'];
// use it in your own way

$("document").ready(function () {
data = {
'name':'ys',
'surname':'ysss',
'pass':'123456',
'number':5
};
$.post('content.php',data,function(response,status){
if(status == 'success'){
$("#information").html(response);
}
});
you can send data as long as possible by writing to the 'data'

Related

Passing data with POST with AJAX

I'm trying to POST some data to another page with AJAX but no info is going, i'm trying to pass the values of two SELECT (Dropdown menus).
My AJAX code is the following:
$('#CreateHTMLReport').click(function()
{
var DeLista = document.getElementById('ClienteDeLista').value;
var AteLista = document.getElementById('ClienteParaLista').value;
$.ajax(
{
url: "main.php",
type: "POST",
data:{ DeLista : DeLista , AteLista : AteLista },
success: function(data)
{
window.location = 'phppage.php';
}
});
});
Once I click the button with ID CreateHTMLReport it runs the code above, but it's not sending the variables to my phppage.php
I'm getting the variables like this:
$t1 = $_POST['DeLista'];
$t2 = $_POST['ParaLista'];
echo $t1;
echo $t2;
And got this error: Notice: Undefined index: DeLista in...
Can someone help me passing the values, I really need to be made like this because I have two buttons, they are not inside one form, and when I click one of them it should redirect to one page and the other one to another page, that's why I can't use the same form to both, I think. I would be great if someone can help me with this, on how to POST those two values DeLista and ParaLista.
EDIT
This is my main.php
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "main.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// Use this to redirect on success, this won't get your post
// because you are sending the post to "main.php"
window.location = 'phppage.php';
// This should write whatever you have sent to "main.php"
//alert(data);
}
});
});
And my phppage.php
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
echo "Nothing sent!";
And I'm still getting "Nothing Sent".
I think you have a destination confusion and you are not retrieving what you are sending in terms of keys. You have two different destinations in your script. You have main.php which is where the Ajax is sending the post/data to, then you have phppage.php where your success is redirecting to but this is where you are seemingly trying to get the post values from.
/main.php
// I would use the .on() instead of .click()
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "phppage.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// This should write whatever you have sent to "main.php"
alert(data);
}
});
});
/phppage.php
<?php
# It is prudent to at least check here
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
# Write a default message for testing
echo "Nothing sent!";
You have to urlencode the data and send it as application/x-www-form-urlencoded.

Set session var with ajax

I want to create a session var. I have a web page with some tabs that don't recharge when I active one another. So, I don't know how to set my session var.
Indeed, my first tab will generate the session var when the user submit the form into this tab. I'm trying to do it with ajax. So in my ajax file, I have this to set my var :
if(pg_num_rows($res) == 1)
{
$flag=false;
$message = "L'identifiant de l'essai existe déjà dans la base";
array_push($tab_erreur,$cpt,$message);
}else {
$sessionIDEssai=$ligne[1]; //Here is my session var
}
After, I want to return that value with an other like this :
echo json_encode($tab_erreur),$sessionIDEssai;
First of all I don't know if it's correct, because I can't get it in my callback function.
function insert_essai_callback(responseObject,ioArgs) .
{
var jsonobject = eval(responseObject);
console.log(jsonobject);
}
I can get the first var $tab_erreur.
And after I don't know how to set my session var for all my tabs. I think that at the return of the ajax, I will get the value and I could set it and use it, but I'm not sure.
EDIT
I send an array in my ajax request like that :
$(document).ready(function(){
$('#submit_button_essai').click(function(){
$.post("ajax_insert_essai.php",{arr:data_essai}, insert_essai_callback,'json');
});
});
Ajax
$.ajax({
type : 'POST',
url : './session.php',
dataType: "json",
data: data,
success : function(data){},
error : function(){}
});
PHP
<?php
session_start();
$_SESSION['data']=$_POST['data'];
echo $_SESSION['data'];
?>
});
Data is what you send through a POST, now echo can return that data or a different amount of data to your Ajax request as a response.
Using, $.post():
$.post({
url: url,
data: data,
success: success,
dataType: dataType
});
However, $.ajax(), is much much better, since you have more control over the flow, and if success do this etc.

Sending form data with ajax echo data with php not displaying

Im learning Ajax...normally I dont like posting about a subject I know very little of but I believe Im on the right path here (maybe not...?) so I will take a chance to find out.
Ive got 3 select boxes each box populates with values based on the the selection of the box before it:
Everything is working perfectly, when the user clicks submit I want to send the 3 textbox values to 3 php variables and echo it on the same page...
Now my data is not echoing (the data of the variables are not displaying) but when I look in my console on firefox I can see the value of the variables...
Here is the selection made on the select boxes
Here is what im seeing in my console
Yet it is does not echo on the page....?
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {
console.log(data);
}
});
}
});
PHP below form
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$sport = $_POST['sport'];
$round = $_POST['round'];
$tournament=$_POST['tournament'];
echo $sport;
echo $round;
echo $tournament;
}
I don't see anything in your code that would make the values display on the page. You would need to either do some DOM insertion in your AJAX success function, or do a full page refresh and echo the data out via PHP (but that would probably defeat the purpose of doing an AJAX call in the first place.)
If you want to go the AJAX route, I would suggest editing your PHP to the following:
echo json_encode(array(
'sport' => $sport,
'round' => $round,
'tournament' => $tournament
));
This will return a JSON object for your jQuery AJAX call to consume.
In your jQuery success function, do something with those values, like so:
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
dataType: 'json',
success: function(data) {
$('<div></div>').text(data.sport).appendTo('body');
$('<div></div>').text(data.round).appendTo('body');
$('<div></div>').text(data.tournament).appendTo('body');
}
});
Note the additional dataType argument to $.ajax. To do it the right way, you'll also want to set your headers in your PHP response to "application/json"
You ajax is just displaying the output in console. Change the ajax success to display it in page.
Make changes after success as:
success:function(data){
$('someelementclassorid').text(data);
}

Pass a value to multiple PHP pages at once with JQuery

My inexperience has me here asking this question.
Can I pass a value to multiple PHP pages in JQuery?
Here is an example of what I am trying to do.
$(function() {
$("#account").change(function() {
$("#facilities").load("displayfacilities.php?q=" + $("#account").val());
$("#facilities").load("updatefacilities.php?f=" + $("#account").val());
});
});
When the user changes a selection within a drop down list, a unique ID will be sent over to displayfacilities.php. I also need that ID in updatefacilities.php which is called from displayfacilities.php.
Is this a bad idea, or is there a better way?
Try to make use of $_SESSION and example of the usage.
This object allows you to store and retrieve data and a usual use case is to share this data across multiple pages within a session.
ex.
$(function() {
$("#account").change(function() {
// store value in superglobal variable and retrieved
// by session_start() in php script, see usage examples above
<?php $_SESSION['some_key'] = *some_value* ?>
// the following value however needs to be sent to server
// either via AJAX or some request.
$("#account").val();
});
});
Hope this helps.
Check this out,
First call ajax, when the response is received, make the second ajax call.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#account").change(function() {
var dataString1 = "q="+$("#account").val();
$.ajax
({
url: "displayfacilities.php",
type : "POST",
cache : false,
data : dataString1,
success: function(result1)
{
alert("Response from PHP file 1");
var dataString2 = "f=" + $("#account").val();
$.ajax
({
url: "updatefacilities.php",
type : "POST",
cache : false,
data : dataString2,
success: function(result2)
{
alert("Response from PHP file 2");
}
}
});
});
});
});
</script>

Ajax request is not working php [duplicate]

This question already has an answer here:
ajax request without data not working
(1 answer)
Closed 8 years ago.
I have asked this earlier but still I wasn't lucky to get it work. Simply I am trying to update profile picture with a default picture when Delete button is clicked and I am trying to use ajax to do this, however whenever I click on the button nothing happens and the picture is not updated. I have tested the php page by itself and it works nicely but the js isn't working so could someone spot what I am doing wrong here?
html
<button href="javascript:void(0);" onclick="delete;" class="btn btn-default delbutt">Delete</button>
js
function delete()
{
$.ajax({
type: "POST",
url: "test.php?action=delete",
cache: false,
success: function(response)
{
var $divs = $("<div>" + response + "</div>");
$("#phd").fadeOut('slow');
$(".suc_pic").fadeIn('slow').empty().append($divs.find("#msg"));
}
});
}
and here is the php lastly
$username = $_SESSION["userCakeUser"];
if(isset($_POST["action"]) && !empty($_POST["action"]) || isset($_GET["action"]) && !empty($_GET["action"]))
{
if(isset($_GET["action"]) == "delete")
{
$profile = 'default.jpg';
$pp = $db->prepare("update users set profile = ? where username = ?");
echo $db->error;
$pp->bind_param('ss', $profile, $username->username);
$pp->execute();
}
}
else {
echo "Something is wrong. Try again.";
}
POST queries are by default not cached in jQuery ajax (1), so you probably should just use the $.post helper instead. Also, querystring values are not parsed to the $_POST super-global, so your code as-is will always read null from $_POST["action"].
function delete(){
$.post(
"test.php",
{
action: 'delete'
},
success: function(response){
var $divs = $("<div>" + response + "</div>");
$("#phd").fadeOut('slow');
$(".suc_pic").fadeIn('slow').empty().append($divs.find("#msg"));
}
);
}
(1) As defined in the API reference:
Pages fetched with POST are never cached, so the cache and ifModified
options in jQuery.ajaxSetup() have no effect on these requests.
It is my understanding that jQuery AJAX requests should have a data: option in there somewhere. Also, I see you're using GET to make the request, but tell jQuery to use POST.
$.ajax({
type: "GET",
url: "test.php",
cache: false,
data : {
action : 'delete'
success : function(response)
{
etc...
I'm no jQuery expert, but I think that may be your problem. The only other thing I can think of is the success function isn't working properly. Check your F12 menu and post any warnings/errors so we can see it.

Categories

Resources