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;
Related
So what I'm trying to do, is send some jQuery variables to my PHP script using Ajax post. However, for some reason, I cannot set the PHP variables to contain the values of the jQuery variables.
I have tried multiple types of Ajax data, like forms (new FormData();) and arrays.
script.js
$.ajax({
url: 'file.php',
type: 'POST',
data: {
'document_id': document_id,
'section_id': section_id,
'active_state': active_state
},
beforeSend: function () {
console.log('the data is: ' + document_id + section_id + active_state + '...');
},
success: function (response) {
console.log(response + ' is locked!');
},
fail: function (error) {
console.log(error + ' could not be locked');
});
file.php
print_r($_POST);
However, in the success function of the Ajax request, I DO receive an array back with the proper variables. When I check the output of the PHP file, it just returns a blank array.
This is what I eventually need to do:
if(isset($_POST['document_id'])){
$document_id = $_POST['document_id'];
$section_id = $_POST['section_id'];
$active_state = $_POST['active_state'];
// echo back the data to the success function
// proceed with insert into database
} else {
echo 'the data has not been set';
}
Any insights on what I may be doing wrong?
Try to use this to get the response from ajax request
<?php
extract($_POST);
print_r($_POST);
?>
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']);
}
?>
I've build a small CMS in Codeigniter for a website with a couple of forms.
The forms are all submitted with the ajax method in jQuery and passed to the controller. All works fine but I figured it out that I always get a success, no matter if the data is saved in the database or not. The method only checks if the data is passed to the controller properly, i guess. On success there is a message for the user (Saved), this will fire everytime, no matter what happens behind the scenes. How I can force success (or done, or some other callback) to get the "Saved" message only if the data is saved?
Here is the code:
//javascript
$("#save_club").click(function(){
var club_name = $('input[name="club_name"]').val();
var location = $('input[name="location"]').val();
var phone = $('input[name="phone"]').val();
$.ajax({
type: "post",
url: base_url + "/clubs/save_club/",
data: {club_name:club_name,location:location,phone1:phone1},
success:function(data)
{
$('input[type="submit"]').attr("value", "Saved!");
$('input[type="submit"]').css("background-color", "#32c310");
$('input[type="submit"]').css("cursor", "default");
$(".dynamic_content").load(base_url + "/clubs/clubs_list");
}
});
});
//controller
public function save_club(){
$newdata = array();
$newdata['club_name'] = $this->input->post("club_name");
$newdata['location'] = $this->input->post("location");
$newdata['phone'] = $this->input->post("phone");
$this->load->model("model_save");
$this->model_save->save_club_to_db($newdata);
}
You first would need to validate the inputs with PHP. For example:
<?php
$success = 'true';
foreach($_POST as $input) {
if ($input == '') {
$success = 'false';
break;
}
}
echo $success;
?>
Next, check the return with the data var you passed in the success function:
$.ajax({
type: "post",
url: base_url + "/clubs/save_club/",
data: {club_name:club_name,location:location,phone1:phone1},
success:function(data)
//Whatever PHP echoes in the script gets put into the variable data
{
var result = (data ? 'saved!' : 'error!'); //data should either be true or false
$('input[type="submit"]').attr("value", result);
$('input[type="submit"]').css("background-color", "#32c310");
$('input[type="submit"]').css("cursor", "default");
$(".dynamic_content").load(base_url + "/clubs/clubs_list");
}
});
i have this jquery code:
var idd = $(this).attr("id");
var page = $(this).attr("page");
var data = "lastmsg="+idd+"&page="+page;
$.ajax({
type: "POST",
url: "ajax_more.php",
data: data,
success: function(html){
$("ol#live_updates").append(html);
$("#more"+idd).remove(); // removing old more button
}
});
and this is the "ajax_more.php" code:
if(isset($_POST['lastmsg']))
{
$lastmsg = mysql_real_escape_string($_POST['lastmsg']);
$page = mysql_real_escape_string($_POST['page']);
echo $lastmsg . " " . $page;
}
Only ($lastmsg) passed, but any other parameter like ($page) is not passed. Where is the problem ??
i tried ($.post) and ($.ajax) with "POST" type, both not working...
data should be an object.
var data = {lastmsg: idd, page: page};
You need to properly encode all of your ajaxed parameters using encodeURI.
See my answer here for more information. Also, use your browser's console to debug.
I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.