I'm trying to post some data to a function that will do a mysql insert. Nothing fancy about that. but I can get the thing to work and my question is where should I be telling jQuery to post to and will it honor php includes?
This is what I have
include_once 'modules/interviews/helper.php';
if($link == 'my_interviews'){
include_once 'modules/interviews/my_interviews.php';
} elseif($link == 'interview_panel'){
include_once 'modules/interviews/interview_panel.php';
}
Above is my index.php, which loads in the page where the form is submitted
$('.addinote').click(function() {
var app = $(this).attr("data-app"),
user = $(this).attr("data-subi"),
txt = $('#' + app).val();
if(txt === ''){
alert('Whoops, did you enter something?');
}else{
var params = {};
params['user_id'] = user;
params['app_id'] = app;
params['inote'] = txt;
params['subinote'] = '1';
$.post('http://localhost/gem/modules/interviews/index.php', params,
function(data){
if(data){
}
else{
alert('Whoops, there was a problem, please try again!');
}
});
}
helper.php contains this...
if(isset($_POST['subinote'])){
$apply->inote();
}
and the class contains this....
function inote(){
$query = "INSERT INTO `app_notes` (`user_id`, `application_id`, `inote`)
VALUES ('{$_POST['user_id']}', '{$_POST['app_id']}',
'{$_POST['inote']}')";
$GLOBALS['DB']->insertQuery($query);
}
Where should I be posting to?
You should be posting to index.php if this is the one reading the $_POST variable.
Also you should be using relative url's for example if helper.php is in the same directory as your html file use ./index.php or simply index.php as your post url. I prefer the former as it states explicitly what you intended.
Related
I was wondering if there is any way to include a php file after an AJAX call and display that included file in my page as response.
For example this is an ajax call:
$('#id').change(function(){
var selected = $(this).val();
$.ajax({
url: "ajax.php",
type: "POST",
data: "select="+selected,
success: function (data) {
$("#here").html(data);
}
});
});
And this is what i tried in php but i got not result displayed on my html:
if(isset($_POST['select'])){
$post= $_POST['select'];
$class = ClassName::find_by_id($post);
$sql = " sp_SQLStoredproc {$class->id} ";
if($class->hasRows($sql)){
include("include.php");
}
}
Is there any way to display my included file in my html?
I tried to change my success response from Ajax $("#here").html(data); to $("#here").load(data); but it returned the whole page.
Any suggestions will help.
UPDATE: Inside the include.php file exist a long html code and some class methods
PS. Please don't mentioned that script is not safe, I know is just an example script.
Thank you in advance
In order to get the success data you need to return the data which you want to be included. And remember php will not work in html except it is action call. You can have php file for this since it has the html support also.
Also you need to remember, before setting the success data to the element it's better to console the value and make sure you are getting the correct data.
if(isset($_POST['select'])){
$post= $_POST['select'];
$class = ClassName::find_by_id($post);
$sql = " sp_SQLStoredproc {$class->id} ";
if($class->hasRows($sql)){
return include("include.php");
}
}
you can set all your "include.php" html in buffers and then you need to echo your content into console.
<?php
if(isset($_POST['select'])){
$post= $_POST['select'];
$class = ClassName::find_by_id($post);
$sql = " sp_SQLStoredproc {$class->id} ";
if($class->hasRows($sql)){
ob_starts();
include("include.php");
$include = ob_get_contents();
echo $include;
}
}
?>
I have passed some values from a page to another using ajax with request method post. But there is one condition that f some one is directly accessing the url, it should be redirected to some other page. Problem is that its not getting redirected (In else condition in img.php) . Can any one tell me what mistake I am committing?
Thanks in advance.
Code:-
imageupload.php:
document.getElementById("submit").addEventListener("click", function(event){
event.preventDefault();
saveImgfunc();
});
function saveImgfunc(){
var form = new FormData(document.getElementById('saveImg'));
var file = document.getElementById('imgVid').files[0];
if (file) {
form.append('imgVid', file);
}
$.ajax({
type : 'POST',
url : 'core/img.php',
data : form,
cache : false,
contentType : false,
processData : false
}).success(function(data){
document.getElementById('msg').innerHTML = data;
});
}
img.php:
<?php
require '../core.php';
$qry = new ProcessQuery('localhost', 'root', '', 'mkart');
$uid = 6;
if($_SERVER["REQUEST_METHOD"] == "POST"){
//Some code here
}
else{
header("Location : ../core.php");
}
See this post https://stackoverflow.com/a/21229246/682754
There's a good chance that you may have some whitespace before you use the header function? Perhaps in the form of a hidden error/warning.
Try the following at the top of your PHP code in img.php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
Would advise removing that once you've found your issue
It works for me removing the whitespace between Location and :
header("Location: ../core.php");
Error found. In the core.php thre is one code which stopping the further execution of code. Its specially coded for uid = 6. Thanks for your time.
Dont use header("Location : ../core.php"); some time it gives error or not working properly so use javascript redirection
like
?>
<script>window.location='../core.php';</script>
<?php
I have actually read all related answers to my question but I need a clear and simple example on how to properly implement my code below.
myHome.php
jquery
var url = "computeArea.php";
var data = $('thisForm').serialize();
$.post(url,data,function(response)); // how do i get the area being returned from
computeArea function? i need to save the
return value to a javascript variable
computeArea.php
function computeArea ($data){ // do i need to parse $data to make it an array?
return $area;
}
im new to jquery and your help is very helpful. thank you!
You can do:
$.post(url,data,function(response){
alert(response)
});
ps: you are missing the . between $ and post.
In your php code you could do that:
echo json_encode($area);
Do a simple teste.
jQuery:
$.post("url/to/file.php",{variable_name: "hello"/*(we'll give this value to variable_name*/)},
function(response){
if(response>0)
alert('Something went wrong');
else
alert(response);
});
Now, on server side:
<?php
if(isset($_POST['variable_name']) && $_POST['variable_name']!=="")
echo $_POST['variable_name'];
else
echo 1;
?>
You are misunderstanding the use of post requests. This will not call the computeArea function in computeArea.php and pass data as its parameter:
var data = $('thisForm').serialize();
$.post(url,data,function(response));
You can do this instead for computeArea.php:
$data = $_POST['watever_you_are_serializing'];
// Do computations, etc.
$area = 123; // Contains computed area
echo $area; // Or json_encode($area);
If you need to call that function from computeArea.php, then you can create a new file for $.post request (eg. computeArea2.php) and include computeArea.php from there. It would be something like this:
include 'computeArea.php';
$data = $_POST['watever_you_are_serializing'];
echo computeArea($data);
Something along the lines of:
var url = "computeArea.php",
data = $('thisForm').serialize(),
new_variable;
$.post(url, data, function(response) {
new_variable = response;
});
Though I presume there's a bit more to your PHP script, as otherwise $area isn't defined anywhere.
I'm beginning to hate AJax, I'm finding it really difficult to get any kind of useful information back when posting with jQuery.
I have a script that adds or removes some info when a button is clicked. The jquery posts to a file which calls a function in a class. This part works, but I cant get a success message back to manipulate the front end. Here is my code.
The php works but I keep getting the error JSON.parse: unexpected character which I have googled, but my json looks ok?
jQuery
$('.fave').click(function(){
var favId = $(this).attr('data-user-fave');
var params = {};
params['fave_id'] = favId;
params['fav_flag'] = '1';
$.post('index.php?link=my_applications', params, function(data){
var data = $.parseJSON(data);
if(data.message === 'success'){
alert(data.flag);
}
else{
alert("Fail");
}
});
code in file that jQuery posts to
$profile = new profile();
if($_POST['fav_flag'] == '1'){
$js = $profile->fave_user();
echo json_encode($js);
}
function in class profile
function fave_user(){
$query = "SELECT * FROM `favourite` WHERE user_id = '{$_SESSION['loginArr']['user_id']}' AND fave_id = '{$_POST['fave_Id']}'";
$nr = $GLOBALS['DB']->num_rows($query);
if($nr >= 1){
//exists so remove
$query = "DELETE FROM `favourites` WHERE user_id = '{$_SESSION['loginArr']['user_id']}' AND fave_id='{$_POST['fave_Id']}'";
$GLOBALS['DB']->deleteQuery($query);
$return["message"]="success";
$return["flag"]="del";
return $return;
}
else{
//not a fave so add
$query = "INSERT INTO `favourite` (user_id, fave_id) VALUES ('{$_SESSION['loginArr']['user_id']}', '{$_POST['fave_id']}')";
$GLOBALS['DB']->insertQuery($query);
$return["message"]="success";
$return["flag"]="ins";
return $return;
}
}
I would suggest using $.ajax method: it is more advanced.
I've got a problem that I'm stuck on for days now...
I'm trying to use a simple ajaxPOST function to send data to a MySQL database (not WP database).
This code is located within "single-post.php" in the theme, because it must be checked before every post.
$.ajax({ url: 'library/functions/admin_checkuser.php',
data: {action: userID},
type: 'post',
success: function(output) {
alert(output);
}
});
I'm simply sending a variable to a "admin_checkuser.php" script which in turn calls another script that take actions on the database.
This is the code for "admin_checkuser":
$userid = $_POST['action'];
echo $userid;//for testing
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
echo $bb;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
}else{
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
But I don't think the calls go through to the script.
These scripts where tested outside of WordPress and did work, so it must be something in WordPress that blocking the ajax call.
BTW, I tried placing the "admin_checkuser.php" in many diffrent folders but nothing worked.
Thanks in advance.
You're much better off using the inbuilt Wordpress AJAX request.
So in your themes functions.php file, add your function to be called, for example:
function checkUser() {
$userid = $_POST['user']; //validation also :)
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
echo $bb;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
} else {
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
}
After that, you add your hook with connects to the inbuilt AJAX System
add_action('wp_ajax_check_user', 'checkUser');
add_action('wp_ajax_nopriv_check_user', 'checkUser');
wp_ajax_nopriv_%s allows it to be called from the front end.
And then, in your javascript file, you just fire off your ajax request.
$.post(ajaxurl, { action: 'check_user', user: userId }, function(output) {
alert(output);
});
If ajaxurl is undefined, you will need to create it in your template file, something like this should work, but there are other ways.
add_action('wp_head','ajaxurl');
function ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
Backend of wordpress does the rest.
It takes the action passed in the AJAX request, looks for the corresponding `wp_ajax(_nopriv)_%s hook and then calls the function that is assigned to the hook.
It will also pass in either the $_POST or $_GET depending on the type of AJAX request.
You can read a little more about using AJAX inside of Wordpress.
You should check your url for your ajax call.
Maybe use the full url instead of the relative one.
It could be because of the location of your theme makes the url incorrect. I'm assuming your ajax code is in your theme folder.
There are some wordpress functions that get the theme directory.
For example if you at this page http://yourwebpage/test/ then the ajax call will go here http://yourwebpage/test/library/functions/admin_checkuser.php. This I assume would be the incorrect location.
This is why you need to add the absolute url to your script. And if it is in your theme, you can use this method get_template_directory_uri() to get the template directory.
See here: http://codex.wordpress.org/Function_Reference/get_template_directory_uri