I have a file called post-blog.php this is collecting the data and storing it in a variable called page.
var page = title + content+ image + datetime +categories;
I'm then sending this off to publish.php, if sent correctly send the user to that page.
$.ajax({
type: 'POST',
cache: false,
url: 'publish.php',
data: page,
success: function( page ) {
alert(page);
window.location.href = "publish.php";
}
});
return false;
This I my php script which is on the 2nd page (publish.php). How can I store the jquery data into php varible. So that I can display them on publish page.
<?php
if ( $_POST['page'] == true )
{
echo "Inserted";
}
?>
You can send this by setting data as follow:
data: {'page': page},
jQuery has some examples on the $.ajax and $.post page:
http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.post/
You can send data using query string variable in url like this
$.ajax({
type: 'POST',
cache: false,
url: 'publish.php',
data: page,
success: function( page ) {
alert(page);
window.location.href = "publish.php" + "?page=" + page ;
}
});
return false;
Then on publishing page you could get data using following code
if (isset($_POST['page']) && $_POST['page'] != '') {
var_dump($_POST['page']);
echo 'inserted';}
?>
you can pass your variable like this
var page = {
title : title,
content : content,
image : image ,
datetime : datetime ,
categories : categories
}
and then in php
<?php
if(isset($_POST["title"])){ // you can use content , image ,... same way
$title = $_POST["title"];
echo $title;
}
?>
and in ajax
success: function( response) { //response is the data which returned from php .. for sure (page) will work but just to be clear
alert(response);
//window.location.href = "publish.php";
}
if you want to use page as an array you can use
var page = [];
page.push(title);
page.push(content);
.......
then in php use
<?php
if (isset($_POST['page'])) {
print_r($_POST['page']);
}
?>
Related
I have rows of data in a mysql table called user_timeline.
I have a column in this table labeled deleted.
I'm running my query to fetch all results in my table where deleted = 0.
$result = $conn ->query ("SELECT * FROM user_timeline WHERE user_id = '$p_id' AND deleted = '0' ORDER BY time_date DESC");
I want to give the user the option to be able to mark a result as deleted in the table by setting this to 1.
I figure i can do this by creating a link that will post to my page del_timeline.php
if(isset($_SESSION['CUSTOMER_ID'])){
echo '<a id="del_t" href="assets/del_timeline.php?t_id='.$row['id'].'"><div class="delete_timeline"></div></a>';
}
In del_timeline.php i have the following update query:
<?php
session_start();
include 'connect.php';
if(isset($_GET['t_id'])){
$t_id = $conn->real_escape_string($_GET['t_id']);
$myID = $_SESSION['CUSTOMER_ID'];
$conn->query("Update user_timeline Set deleted = '1' Where id = $t_id AND user_id = $myID") ;
}
?>
As you can imagine, each result in my table will have a specific/unique ID. So that it can keep track of which result the user is trying to set as deleted. Whilst this works via a normal href click event. I am trying to get this to run using ajax to avoid a page refresh.
I am not entirely sure how to pass a mysql $row parameter through ajax. I have tried the following but it doesn't seem to work.
<script>
$( "#del_t" ).submit(function( event ) {
event.preventDefault(); // <---- Add this line
$.ajax({
type: "POST",
url: "assets/del_timeline.php?t_id=$row['id']",
data: $( "#del_t" ).serialize(),
success: function(data) {
// print here
},
dataType: 'html' // for json response or 'html' for html response
});
</script>
please can someone show me where I am going wrong?
First of all, you need to attach event handler to prevent page reload when users click on href links. Consider something like this in your javascript:
$( document ).on( 'click', 'a[id="del_t"]', function( event ) {
event.preventDefault();
$.ajax( {
type: 'POST',
url: $( this ).attr( 'href' )
} )
.done( function( response ) {
// Do something with the success response...
// Maybe delete the row containing deleted data
} );
} );
Then, you'll need to send some data from your del_timeline.php.
Use PHP's echo to pass mysql result or any PHP variable to the client browser (your javascript code).
<?php
session_start();
include 'connect.php';
if(isset($_GET['t_id'])){
$t_id = $conn->real_escape_string($_GET['t_id']);
$myID = $_SESSION['CUSTOMER_ID'];
$conn->query("Update user_timeline Set deleted = '1' Where id = $t_id AND user_id = $myID") ;
// Send some success response
echo 'success'; // or any data you want to send
}
// Send some error response
echo 'error';
?>
You not need to add the id from php to ajax function. You can use the href address from the link.
$( "#del_t" ).click(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('href'),
data: '',
success: function(data) {
// print here
},
dataType: 'html' // for json response or 'html' for html response
});
Or, better, put the id into an attribute in <a> (ex. in title), use $_REQUEST in php. In ajax get the id from that attribute to pass it in data sent via post. In php:
echo '<a id="del_t" href="assets/del_timeline.php?t_id='.$row['id'].'" title="'.$row['id'].'"><div class="delete_timeline"></div></a>';
In del_timeline.php:
if(isset($_REQUEST['t_id'])){
$t_id = $conn->real_escape_string($_REQUEST['t_id']);
//your code
}
Ajax:
$( "#del_t" ).click(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: 'assets/del_timeline.php',
data: 't_id='+$(this).attr('title'),
success: function(data) {
// print here
},
dataType: 'html' // for json response or 'html' for html response
});
What am I doing wrong ? I have jquery var which is storing data, i'm then sending this data to functions.php. But i'm not getting any results from the functions.php page. Any suggestions ?
var data = "&insertPost=1&title=" + title + "&content=" + content;
$.ajax({
type: 'POST',
cache: false,
url: 'functions.php',
data: data,
success: function( data ) {
alert('wooo');
}
});
Then on my functions page.
if ($_POST['insertPost'] == true)
{
$postTitle = $_POST['title'];
$postContent = $_POST['content'];
echo "Inserted";
}
else
{
return "No Data";
}
return $postData;
You are sending a POST data information as if it were GET...
change your data to:
data: {
'insertPost':1,
'title':"'+title+'",
'content':"'+content+'"
}
Try this,
in ajax data part(this is for POST)
data:{insertPost:1,title:title,content:content},
For GET
var data = "insertPost=1&title=" + title + "&content=" + content;
^// no & here
type: 'GET',
url: 'functions.php/'+data,
If you want to send back any data from ajax call, return will not work
return $postData;// this will not work
you have to echo the data in ajax call
echo $postData;
I have two files filter.php and products.php included to index.php and I am using .post submit form without refreshing. I send data to products.php and return it back also i refresh my filter and there is my problem. When i try to var dump post data in filter.php it is empty
Here is my script
function ajaxFilter()
{
var str = jQuery( "form[name=\"filters\"]" ).serialize();
jQuery.post( "/", str )
.done(function( data ) {
var productList = jQuery(data).find(".list_product").html();
var filter = jQuery(data).find(".filters").html();
jQuery(".list_product").html(productList);
jQuery(".filters").html(filter);
});
}
Any ideas how to get POST?
I though about putting my post via script to hidden inputs and return them also as html
If it is bad idea or just wrong start.
try this:
var Data = $("form[name=\"filters\"]").serializeArray();
var URL = "products.php"; // whatever filepath where you send data
jQuery.ajax({
type: "POST",
url: URL,
processData: true,
data: Data,
dataType: "html",
success: function (productList) {
// filter your result whatever you return from products.php
jQuery(".list_product").html(productList);
},
error: function (x, y, z) {
var a = x.responseText;
jQuery(".list_product").html(a);
}
});
Use the full URL.
Provide the return values of .error() if you still have problems.
I am trying to send data to php file and I am using post and get to receive data base on if it is post or get.
The problem is that get is working and I click to receive data through post i do not receive anything.
php code process stops when it gets to GET then I send I POST and it does not respond to it. I can see ajax sends the data but php does not receive it when GET is working in php file.
php code:
if($_POST['id']){ show data}elseif{$_GET['id']{ get data}
jquery ajax:
// Youtube videos:
$(function() {
$('.image').click(function() {
var id = $(this).attr('id');
var msgbox = $("#video_status");
if(id.length > 5) {
$("#Video_status").html('<img src="assets/imgs/loading.gif" alt="loading ... " />');
$.ajax({
type: "POST",
url: "my_video.php",
data: 'id='+ id ,
cache: false,
success: function(msg){
$('#Video_status').html(msg);
if(msg ) {
msgbox.html(msg);
}else{
msgbox.html(msg);
}
}
});
}
return false;
});// End of youtube videos.
$(function() {
var loader = $("#Video_status").html('<img src="assets/imgs/loading.gif" alt=" loading ... " />');
var VideoWrap = $('#VideoWrap');
loader.fadeOut(1000);
$.get('my_video.php', '', function(data, status){
VideoWrap.fadeOut(1000);
VideoWrap.html(data);
VideoWrap.fadeIn();
});
return false;
});
});// get youtube video.
first check using isset
if(isset($_POST['id']))
{
//to show data echo/print something
echo $_POST['id'];
}
elseif(isset($_GET['id']))
{
//get data
}
try this
if($this->getRequest()->isPost()) {
}
if($this->getRequest()->isGet()) {
}
Why not something like this?
$postOrGetVar= $_GET['paramname'] ? $_GET['paramname'] : ($_POST['paramname'] ? $_POST['paramname'] : 'Param not sent via Post nor Get');
Simple, readable and easy.
I have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});