Empty $_POST when posting from jquery.ajax - javascript

I am doing some Add, Edit, and Delete for my project in school. The codes in the add module went well, in fact I've added few records. Then, here comes the Edit module, at first it was quite good, similar codes was used from the add module. But as I try and try, the post in the edit module was empty.
here's my edit codes:
$(".careersEdit").click(function () {
var careersTableSelect = encodeURIComponent($("input:radio[name=careersTableSelect]:checked").val());
if (careersTableSelect > 0) {
$(".careersEditForm_load").show();
$(".careersEditForm_error").hide();
$(".careersEditForm").hide();
var dataStringCareersEdit = 'careersTableSelect=' + careersTableSelect;
$.ajax({
type: "POST",
url: "admin/careers/process/careersEditGet.php",
data: dataStringCareersEdit,
beforeSend: function(){
alert(dataStringCareersEdit);
},
success: function () {
setTimeout("", 5000);
fetchResult();
},
error: function () {
alert("Post Error");
}
});
function fetchResult() {
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "POST",
dataType: "json",
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result['position']);
$("input#careersEditCompany").val(result['company']);
$("input#careersEditLocation").val(result['location']);
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
}
} else {
$(".careersEditForm").hide();
$(".careersEditForm_load").hide();
$(".careersEditForm_error").show();
}
});
Here's the careersEditGet.php:
<?php
include('connect.php');
error_reporting(0);
$careersTableSelect = $_POST['careersTableSelect'];
//$careersTableSelect = $careersTableSelect + 1;
//echo $careersTableSelect;
$query = "SELECT * FROM atsdatabase.admincareers WHERE refNum ='" . $careersTableSelect . "' LIMIT 0 , 30";
$runQuery = mysql_query($query);
if (!$runQuery) {
die('Could not enter data: ' . mysql_error());
}
$result = mysql_fetch_row($runQuery);
$array = array(
'position' => "" . $result[1] . "",
'company' => "" . $result[2] . "",
'location' => "" . $result[3] . "",
);
echo json_encode($array);
mysql_close($connection);
?>
Yes, the code is ugly/wrong/crap, I'm quite new to jquery stuffs, about 3-4 days. To those that will help, please do correct me. I wanna learn this jquery ajax stuff. Gracias

Maybe try passing data in more common way:
change
data: dataStringCareersEdit,
to
data: { "careersTableSelect" : careersTableSelect },

Call your ajax function once like,
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "POST",
dataType: "json",
data: {careersTableSelect: careersTableSelect},
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result.position);// json not array
$("input#careersEditCompany").val(result.company);// json not array
$("input#careersEditLocation").val(result.location);// json not array
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});

Thanks guys for all the effort to answer this question, I've consulted to a friend who's a web developer, taught me how to properly use ajax in jquery. ;)

You are doing something fundamentally wrong when u are posting Data from jQuery.Ajax..
The data should be an object and the key should be the name of the server side POST variable which will be used later in the PHP ...
Example :
data : {"server_side_vriable" : "Your_data_to_Post" }
......
var dataStringCareersEdit = 'careersTableSelect=' + careersTableSelect + "&careersTableSelect=" + careersTableSelect;
$.ajax({
type: "POST",
url: "admin/careers/process/careersEditGet.php",
data: {"careersTableSelect" : dataStringCareersEdit},
beforeSend: alert(dataStringCareersEdit),
success: function () {
alert("Fetching Result");
setTimeout("", 3000);
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "GET",
dataType: "json",
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result['position']);
$("input#careersEditCompany").val(result['company']);
$("input#careersEditLocation").val(result['location']);
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
},
error: function () {
alert("Post Error");
}
});

Related

Making clickable result list from Bootstrap typeahead and JSON

I want to make the result list for my Bootstrap typeahead list clickable and if the user clicks on any of the items in the dropdown list it will be redirected to the url [on my site, not external links] of the selected item. I made my changes regarding this Stackoverflow topic: jquery autocomplete json and clickable link through
The problem is, that I'm not into JS and Jquery and I can't tell why I get this error (Firefox Firebug Console output). I get this error everytime I enter any letter in my input textbox:
TypeError: it.toLowerCase is not a function bootstrap3-typeahead.min.js (1. line, 3920. column)
I see that the results of my PHP seems okay, so it must be something in the jQuery statement...
This is my result from the PHP:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
This is my JQuery code:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
This is my PHP code:
<?php
require_once('../config/config.php');
require_once('../functions/functions.php');
require_once('../config/db_connect.php');
$query = 'SELECT name_desc FROM tbl_name ';
if(isset($_POST['query'])){
$query .= ' WHERE LOWER(name_desc) LIKE LOWER("%'.$_POST['query'].'%")';
}
$return = array();
if($result = mysqli_query($conn, $query)){
// fetch object array
while($row = mysqli_fetch_row($result)) {
$array = array("name" => $row[0], "url" => "/" . normalize_name($row[0])."-some-url-postfix");
$return[] = $array;
}
// free result set
$result->close();
}
// close connection
$conn->close();
$json = json_encode($return);
print_r($json);
?>
Can someone please help me what could be the problem here?
Thank you very much!
The problem was that the displayText wasn't defined:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});

Sending PHP values with AJAX

I am trying to delete images with Ajax and all the php seems to work except when I try to send variables to another php document.
Php that shows and grabs neccessary values.
// show images
$image_display = "";
foreach(glob($pathimages.'*') as $filename){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$name_only = basename($filename, ".".$ext);
$image_display .= "<img src=\"images/" .$targetID."/" .$name_only.".".$ext. "\" width=\"30\" />
<a onclick=\"DeleteImage('".$name_only."','".$ext."','".$targetID"'); return false;\" href=\"javascript:;\">X</a>
<br />";
}
.JS document, I get the sent and the success messages when pressing the X
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
delete_imgs.php document
include('session_check.php');
$name_only = $_POST['name_only'];
$ext = $_POST['ext'];
$targetID = $_POST['targetID'];
$pathimages = "images/$targetID/";
unlink($pathimages . $name_only .".". $ext);
echo "Deleted";
Any thoughts are more than welcome since I have banged my brain out of my head by now ...!
Cheers!
Try with async:false
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
async : false,
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
Maybe that can help

How to tell PHP which comments to show under the article with AJAX?

I am building a news page for my website but I'm stuck displaying the right comments with ajax...
commentsLoad.php
<?php
include('config.php');
$newsid = $_GET['newsid'];
$comments=array();
$commentsQuery = "SELECT * FROM comments
where fk_news like ".$newsid;
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments[]=array('id' => $row['id'], 'name' => $row['cnick'], 'text' => $row['ctext'], 'date' => $row['cdate']);
}
}
//header('Content-type: application/json');
echo json_encode($comments);
exit;
?>
I dont know how to pass the right 'NEWSID'.
Website picture: http://prntscr.com/8nwy8k
How I want to pass that ID to the SQL Query
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
data:{newsid:'1'},
success: function(comments){
//console.log(komentarji);
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
So right now if I change the line data:{newsid:'1 or 2 or 3...'} I get the comments I want, but I dont know how to get that ID into a variable.
You can use onClick event for this.
Explanation:
Comment link will look as follows
Comments
Then you can have a fucntion in your JQuery code to pass it to PHP file.
function getComments(article_id)
{
var artid = article_id;
$.ajax({
type: 'POST',
url: commentsUrl,
dataType: "json",
data:{newsid: artid},
success: function(comments){
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
}
Try set onclick function in the comment link.
<a href="javascript:void(0)" onclick='myfunction <?php echo newsid ?>'Comment</a>
Get the newsid form the link.
<script>
function myfunction(newsid){
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
data:{newsid:newsid},
success: function(comments){
//console.log(komentarji);
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
}
</script>
Get the newid from commenntsUrl page.

How to keep all JS together for my all notification

Here I read about many types of notification system like push, web socket, nodejs etc. But those all so complex for me. So as a easy way (In my preliminary step) I am going to use Below method to make a notification(new friend, new like, new comment/reply, new mail etc). So I used particular JS and php for a particular notification.
Now I want to implement keep all together in a JS to minimize my scripts. Here I faced a problem that is every notification have different sent data and php page and different result div. So how to keep them together?
A additional Question please(I knew stackoverflow rules): Can it make my server too many connection problem?
new mail notification JS:
function addrep(type, msg){
// do here with result
}
var name = '<?php echo $username; ?>';
function waitForMail(){
$.ajax({
type: "GET",
url: "/server/mail.php",
cache: false,
data: {name : name
},
timeout:15000,
success: function(data){
addrep("postreply", data);
setTimeout(waitForMail, 15000 );
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(waitForMail, 15000);
}
});
}
$(document).ready(function(){
waitForMail();
});
new post notification JS:
function addpost(type, msg){
// do here with result
}
var name = '<?php echo $username; ?>';
var profileid = '<?php echo $profileid; ?>';
function waitForPost(){
$.ajax({
type: "GET",
url: "/server/post.php",
cache: false,
data: {name : name, profileid : profileid
},
timeout:15000,
success: function(data){
addpost("postreply", data);
setTimeout(waitForPost, 15000 );
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(waitForPost, 15000);
}
});
}
$(document).ready(function(){
waitForPost();
});
And all php file like as
while (true) {
if($_GET['username']){
$res = mysqli_query(// here) or die(mysqli_error($dbh));
$rows = mysqli_fetch_assoc($res);
$id = $rows['id'];
//etc all
//do something
$data['id'] = $id;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
}
sleep(5);
}
mysqli_close($dbh);
Well, I am not sure is this comfortable with your application design. Anyway it seems obvious that if you have to fetch notifications with the same interval it is better to have one ajax that checks everything. Something like:
$.ajax({
type: "GET",
url: "/server/notification.php",
cache: false,
data: {name : name, profileid : profileid
},
timeout:15000,
success: function(data) {
/**
* backend should return now single object for all notification types
* something like
* {
* newpost: { ... },
* mail: { ... },
* somethingelse: { ... }
* }
*/
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(waitForPost, 15000);
}
});
If you can not do it for some reasons you can keep all urls and their callbacks in object and create ajax requests in array. Something like:
// list of ajax request names and their callbacks
var reqs = {
mail: function(data) { doSomethingWith(data);},
post: function(data) { doSomethingWith(data);}
};
// this function will send ajax by given type
function fetchNotification(type, callback) {
$.ajax({
type: "GET",
// ajax url, for example /server/mail.php
url: "/server/" + type + ".php",
cache: false,
data: {name : name, profileid : profileid},
timeout: 15000,
success: function(data) {
// run callback. In this example execute doSoemthingWithData
callback(data);
// in 15 seconds repeat this reqest
setTimeout(function() {
fetchNotification(type, callback);
}, 15000)
},
error: function(req, status, err){
// something went wrong, try again in 15 seconds
setTimeout(function() {
fetchNotification(type, callback);
}, 15000);
}
}
}
for (var i in reqs) {
// init first ajax for each type and its callback from reqs object
fetchNotification(i, reqs[i]);
}

AJAX/ json returning null open cart

Hi Im attempting a simple ajax request but I keep getting a null value for json.
Here is my javascript...
<script>
$(document).ready( function() {
$('#donate-box-submit').on('click', function() {
var donate_code = $('#charity-campaign-code').val();
var donate_amount = $('#charity-campaign-amount').val();
$.ajax({
url: 'index.php?route=donate/donatenow',
type: 'post',
data: {
donate_code: donate_code,
donate_amount: donate_amount
},
dataType: 'json',
beforeSend: function() {
},
complete: function() {
},
success: function(json) {
console.log(json);
alert(json['test']);
},
error: function() {
}
});
});
});
</script>
and my php...
public function donatenow() {
$json = array(
'test' => 'Output this text'
);
$this->response->setOutput(json_encode($json));
}
I have also tried echo json_encode($json); just to rule out any issues with that OpenCart function, but the same issue is still there.
The problem is the route you are using to call the method. Not sure on exactly what class you are using as the controller, but there should be three parts to the route: route=aaa/bbb/donatenow where as you've got aaa/donatenow

Categories

Resources