The best way passing value from jQuery to PHP - php

I wonder how I can pass value from Jquery to PHP. I found similar codes but not even one of them work.
Everytime alert shows value of variable but when I open site there is not any. Var_dump shows that $_POST is null. I am ran out of ideas do you have any?
jQuery code:
$("#password-button").click(function(){
var password="";
var numbers =[0,0,0,0,0,0];
for(var i=0;i<=5;i++){
numbers[i] = Math.floor((Math.random() * 25) + 65);
password += String.fromCharCode(numbers[i]);
}
$(".LoginError").text("Nowe haslo: " + password);
$.ajax({
type: 'post',
url: 'dzialaj.php',
data: {'password': password},
cache:false,
success: function(data)
{
alert(data);
console.log(result)
console.log(result.status);
}
});
});
PHP:
if(isset($_POST['password'])){
$temp = $_POST['password'];
echo $temp;
}

Since it looks like you are new on ajax, let's try something more simple ok? Check this js:
<script>
var string = "my string"; // What i want to pass to php
$.ajax({
type: 'post', // the method (could be GET btw)
url: 'output.php', // The file where my php code is
data: {
'test': string // all variables i want to pass. In this case, only one.
},
success: function(data) { // in case of success get the output, i named data
alert(data); // do something with the output, like an alert
}
});
</script>
Now my output.php
<?php
if(isset($_POST['test'])) { //if i have this post
echo $_POST['test']; // print it
}
So basically i have a js variable and used in my php code. If i need a response i could get it from php and return it to js like the variable data does.
Everything working so far? Great. Now replace the js mentioned above with your current code. Before run the ajax just do an console.log or alert to check if you variable password is what you expect. If it's not, you need to check what's wrong with your js or html code.
Here is a example what i think you are trying to achieve (not sure if i understand correctly)
EDIT
<script>
var hash = "my hash";
$.ajax({
type: 'post',
url: 'output.php',
data: {
'hash': hash },
success: function(data) {
if (data == 'ok') {
alert('All good. Everything saved!');
} else {
alert('something went wrong...');
}
}
});
</script>
Now my output.php
<?php
if(isset($_POST['hash'])) {
//run sql query saving what you need in your db and check if the insert/update was successful;
// im naming my verification $result (a boolean)
if ($result) echo 'ok';
else echo 'error';
}
Since the page won't redirect to the php, you need a response in you ajax to know what was the result of you php code (if was successful or not).
Here is the others answers i mentioned in the coments:
How to redirect through 'POST' method using Javascript?
Send POST data on redirect with Javascript/jQuery?
jQuery - Redirect with post data
Javascript - redirect to a page with POST data

Related

Deleting comments from database using php

I am making a forum webpage where I'll put delete this buttons under each comment. Now when you press this button, I send the ID of the comment to PHP file using ajax which looks like this:
function Deletethis(index) {
var result = confirm("Want to delete?");
if (result==true) {
$.ajax({
url: "deletepost.php",
type: "POST",
data: index,
success: function(){
location.reload();
}
});
} else return false;
}
Now the problem is I can't receive it from the PHP end. I've used the debugger and saw that the index value is right. My PHP looks like this:
<?php
$con = mysqli_connect("localhost", "root", "123", "test") or die("DIE");
if (isset($_POST['index'])) {
$SoonToBeDeletedComment = $_POST['index'];
};
$index = intval($SoonToBeDeletedComment);
mysqli_query($con, "DELETE FROM commentsbox WHERE commentsbox.`ID` = $index");
echo "Post Deleted...";
mysqli_close($con);
?>
My code doesnt give any errors but it doesn't delete the post either. When I do the same process manually on navicat, it is working so I thought maybe the index is a string and it should be an integer. So I used intval but it didnt solve the problem either. Any ideas to help me improve my code is appreciated. Thanks in advance
In jQuery's .ajax call, the data property needs to be an object, not a string (string only it it's a full GET query string, actually, but it's not what you need here).
So, try this:
$.ajax({
url: "deletepost.php",
type: "POST",
data: {id: index},
success: function(response){
alert(response);
// location.reload();
}
});
And then in PHP, get it as:
$_POST['id']
UPDATE
Sanity checklist:
is your Deletethis function actually receiving the index?
is your ajax calling the right script?
is ajax data property an object, like I explained above?
what is the output of the PHP script?
what are the contents of $_POST?
is the id inside the $_POST array ($_POST['id'])?
does the row with that id exist in the db?
These questions should help you pinpoint the problem more accurately.
You send param to your PHP code without define his name : data: { index: index } // param : value
function Deletethis(index)
{
if ( confirm("Want to delete?") )
{
$.ajax({
url: "deletepost.php",
type: "POST",
data: {
index: index
},
success: function(){
window.location.reload();
}
});
}
}
Check also if your PHP code is working by calling page directly with param.

Is this true way to send request

i wonder if this is true and safe way to send request via ajax json type to php file or not ?!
note : it return success result ..
but my question if to keep them like this or change it to another safe method ?!
Html Code
<span class="clickable" data-bind={"name":"master","tag":"1"}>click</span>
Javascript Code :
$(".clickable").livequery('click touchstart', function (e)
{
var bind = $(this).data("bind");
$.ajax({
type: "POST",
url: "page.php",
data: bind,
dataType: 'json',
success: function (response)
{
alert(response)
}
});
e.stopImmediatePropagation();
});
PHP File :
$name= mysql_real_escape_string(trim(htmlentities(strip_tags($_POST['name']))));
if(!isset($name) || $name == '' || $name != 'master') {
echo 'Error: Invalid Action';
exit;
}else{
// Do Something
}
Basicly whenever you use ajax to post to a page, anyone with a developer console in their browser is able to see that request. And alter it as they like. Just like they can alter the data-bind attribute by using something like firebug.
You should implement checks on the POST variables in your page.php to make sure the input is not something you want inserted into your PHP code.

Identifying what is returned when submitting a form using jquery

Is it possible to identify what a page returns when using jquery? I'm submitting a form here using jquery like this:
$("#sform").submit(function() {
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
url: "user_verify.php",
success: function(data) {
$("#form_msg").html(data);
}
});
return false;
});
​
The user_verify.php page does its usual verification work, and returns error messages or on success adds a user to the db. If its errors its a bunch of error messages or on success its usually "You have successfully signed up". Can I somehow identify using jquery if its errors messages its returning or the success message. So that way if its errors I can use that data in the form, or if its success, I could close the form and display a success message.
Yes, it's this:
success: function(data) {
$("#form_msg").html(data);
}
You can manipulate data in any way you want. You can return a JSON (use dataType) encoded string from server side and process data in the success function
success: function(data) {
if(data->success == 'ok'){
// hide the form, show another hidden div.
}
}
so user_verify.php should print for example:
// .... queries
$dataReturn = array();
$dataReturn['success'] = 'ok';
$dataReturn['additional'] = 'test';
echo json_encode($dataReturn);
die; // to prevent any other prints.
You can make you php return 0 if error so you do something like this inside
success: function(data) {
if(data==0){
//do error procedure
}else{
//do success procedure
}
}
Hope this helps
You can do and something like this:
$.ajax({
type:"POST", //php method
url:'process.php',//where to send data...
cache:'false',//IE FIX
data: data, //what will data contain
//check is data sent successfuly to process.php
//success:function(response){
//alert(response)
//}
success: function(){ //on success do something...
$('.success').delay(2000).fadeIn(1000);
//alert('THX for your mail!');
} //end sucess
}).error(function(){ //if sucess FAILS!! put .error After $.ajax. EXAMPLE :$.ajax({}).error(function(){};
alert('An error occured!!');
$('.thx').hide();
});
//return false prevent Redirection
return false;
});
You can checke the "data" parameter in "success" callback function.
I noticed that there is a problem in your code. Look at this line :
data: $(this).serialize(),
Inside $.ajax jquery method, "this" is bind to the global window object and not $('#sform')

Wordpress - fetch user info using jQuery ajax POST request

I am working in Wordpress trying to use an ajax request to fetch user data by passing the user id.
I can see that the user id sends correctly via AJAX POST but I am getting an internal error message and I don't know why.
At first I thought it was because I was trying to fetch some custom fields that I had added to the user profile but even when I simplified my script I am still getting the error message.
Any help is much appreciated!
Front End
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
type: 'POST',
url: 'wp-content/themes/twentyeleven/author_info.php',
data: {id: id},
dataType: 'html',
success: function(data) {
$('#author-bio').html(data);
}
});
return false;
});
author_info.php
$user_id = $_POST['id'];
$forename = get_the_author_meta('user_firstname', $user_id);
$output = $user_id;
echo $output;
Error Message
500 (Internal Server Error) jquery.min.js:4
Mathieu added a hackable approach to intercepting a request and redirecting it, which is fine. I prefer to build out AJAX responses that return json_encoded arrays.
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
url: 'http://absolute.path/wp-admin/admin-ajax.php',
data: {'action' : 'ajax_request', 'fn': 'getAuthorMeta', 'id': id},
dataType: 'json',
success: function(data) {
//We expect a JSON encoded array here, not an HTML template.
}
});
return false;
});
Now we build out the function to handle our ajax requests.
First, we need to define our ajax add_action method ->
add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_ajax_request', 'ajax_handle_request');
We need to use both add_action lines here. I won't get into why. You'll notice the _ajax_request here. This is the 'action' that we sent over in our AJAX function data: {'action' : 'ajax_request'}. We use this hook to validate our AJAX request, it can be anything you'd like.
Next, we'll need to build out or function ajax_handle_request.
function ajax_handle_request(){
switch($_REQUEST['fn']){
case 'getAuthorMeta':
$output = ajax_get_author_meta($_REQUEST['id']);
break;
default:
$output = 'That is not a valid FN parameter. Please check your string and try again';
break;
}
$output = json_encode($output);
if(is_array($output)){
return $output;
}else{
echo $output;
}
}
Now let's build our function to actually get the author meta.
function ajax_get_author_meta($id){
$theMeta = get_the_author_meta([meta_option], $id);
return $theMeta;
}
Where [meta_option] is a field provided by WP's native get_the_author_meta function.
At this point, we'll now go back to our success:function(data) and (data) is a reference to the json_encoded array we've returned. We can now iterate over the object to get our fields and output them into the page as you'd like.
You are not in a POST at that moment because you are calling a specific page of your template that probably doesn't correspond to any article in your blog.
Instead, create a pluggin that will do this:
add_action('template_redirect', 'my_author_meta_intercept');
function my_author_meta_intercept(){
if(isset($_POST['getAuthorMeta'])){
echo get_the_author_meta('user_firstname', $_POST['getAuthorMeta']);
exit();
}
}
This will short circuit the request to the same page as before when you call it using:
http://mysite/mycurrenturl?getAuthorMeta=testMetaKey
So calling that post normally will return the article as usual, but if you pass in ?getAuthorMeta, it will stop the template from being selected and simply return the exact content you want it to return.
In your page, you just have to change your javascript to:
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
$.ajax({
type: 'POST',
url: window.location.href,
data: {getAuthorMeta: id},
success: function(data) {
$('#author-bio').html(data);
}
});
return false;
});
Just make sure you adapt the concept to what you need!
I would rather recommend you to use WP AJAX action method.
As in your case, add the following to your functions.php file.
add_action('wp_ajax_get_user_info', 'ajax_get_user_info');
add_action('wp_ajax_nopriv_get_user_info', 'ajax_get_user_info');
function ajax_get_user_info() {
//Handle request then generate response using WP_Ajax_Response or your html.
}
then in javascript tag.
$('.author').click(function() {
var id = $(this).attr('id');
var temp = id.split('-');
id = temp[1];
jQuery.post(
ajaxurl, /* if you get error of undefined ajaxurl. set it to "http://example.com/wordpress/wp-admin/admin-ajax.php"*/
{
'action':'get_user_info',
'user_id':id
},
function(response){
alert('The server responded: ' + response);
}
);
});
I would recommend you to read the 5 tips for using AJAX in WordPress.
p.s; Code above is not tested, it may have errors. but you get the idea.

jQuery.AJAX post() - a few questions and issues

I'm making a site where a user spams a button and increases their score in doing so.
I don't want the page to refresh when the button is clicked, so I wanna use AJAX to send the data to the server. Here's what I have so far:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#update").click(function() {
$.ajax({
type: "POST",
url: "update.php",
data: "increase",
dataType: "Boolean",
success: function(update) {}
});
});
});
</script>
<button id="update" type="button">Button</button>
<div id="counter"></div>
It's not much at all, I know, but I'm very new to this stuff. The main problem I'm having is with the syntax that you're supposed to use. I want the server to return a Boolean variable if the request is successful, so would I have Boolean in the 'Data Type' in inverted commas, apostrophes or what?
Also, I'm struggling with grasping how the ajax script knows whether it's successful. Is there gonna be something in the 'update.php' script that will return a 'TRUE' or 'FALSE' value?
Finally, the data that's gonna be sent to the php file is supposed to tell the php to update the mysql table with the new score. How should I go about telling the php to update the mysql if it receives the data that the ajax is sending?
Thanks a lot
Something along the lines of this should work:
$.ajax({
type: "POST",
url: "update.php",
data: {"action":"increase"},
success: function(response) {
if(response.error) {
alert(response.error);
return;
}
if(response === 'true') {
//do something
} else {
//do something else
}
}
)};
On the PHP end, your code would likely look like this:
<?php
if(!isset($_POST['action'])) {
echo '{"error": "You must provide a action"}';
exit;
}
$action = $_POST['action'];
if(!in_array($action, array('increase', 'decrease')) die('{"error":"invalid parameters"}');
$action = ($action == 'increase') ? ' + 1' : ' - 1';
//$db is assumed to be a live mysqli object from here on out...
$result = $db->query("UPDATE someTable SET fieldname = fieldname {$action} LIMIT 1;");
echo ($result->affected_rows > 0) ? 'true' : 'false';
?>
The dataType attribute is one of json, xml, html, jsonp, text, or script. Boolean isn't one of the expected types. In this case, you don't want to pay attention to those expected types. jQuery makes an intelligent guess about the type if you pass nothing in based on the MIME type returned by your server.
What you want to do is create a function that will be called by the success callback.
$.ajax({
type: "POST",
url: "http://www.server/path/to/update.php",
data: "increase",
success: function(data, status, xhr) {
functionToProcess(new Boolean(data));
}
)};
The function that is given as an argument to success (an anonymous function, in this case) is called when the Ajax call is complete with a 200 value. Because Ajax is asynchronous (that's what the A is), returning things will do you no good. What you want to do is call another function that will process your boolean value. This I've called functionToProcess in my sample code. For more information, check out the jQuery docs on .ajax().
You can learn about what String values in Javascript produce true versus false boolean values here.
This syntax should work
$(document).ready(function(){
$("#update").click(function(){
$.ajax({type: "POST",
url: "update.php",
data: "increase",
success: function(update) {
if(update)
$("#anyelement").html("Thanks");
else
$("#anyelement").html("Try again !");
}
});
});
});
You can ignore the datatype, because you can parse from any direction
how the ajax script knows whether it's successful
If I understand your point, as far as there is a return to the ajax function the process is success, it is upto you to parse the return and implement the logic.
from you php you do like this:
if(you logic is correct){
//update you database and ... other login goes here
return true;
}else{
return false;
}

Categories