I have a PHP CODE:
if(isset($_POST['id'])){
$id = mysqli_real_escape_string($link,$_POST['id']);
$query = "SELECT * FROM `tb_cform` WHERE `ID`='$id'";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_assoc($result)){
$message = '<div><h4>Subject: </h4><h5>'.$row['subj'].'<h5></div>';
$message .= '<hr><br>';
$message .= '<div><b>Message:<br>'.$row['message'].'</b></div>';
}
echo $message;
}
I need to pass the value from my AJAX code to the aforementioned code:
$('#messageModal').on('show', function(){
$.ajax({
type: "POST",
url: "viewmessage.php",
datatype: "html",
data:"data-id=" +id ,
success: function(r){
$('#messageBody').html( r );
}
});
});
The link that I am using is using a data-id="73" to pop open a model and populate the information.
My issue is, the value is not being passed and the body of the Modal is not being populated. Can anyone let me know why or what I did incorrect?
Check that your db returns something, so that $result is not null. Otherwise your $message will be empty.
If your query actually returns something and $message is still empty - try changing datatype to json:
JS
$.ajax({
type: 'POST',
url: 'php/server.php',
datatype: 'JSON',
data: {
dataId: someArbitraryId
},
success: function(data) {
var message = JSON.parse(data).message;
$('#message').html(message);
}
});
PHP
if (isset($_POST['dataId'])) {
$message = '';
// Some code
$result = array(
'message' => $message
);
echo json_encode($result);
}
Now even if the $message is empty or null - server should return array with empty string.
in js
data:{dataId : id}, // I'm sure this will work but data:"data-id=" +id, may work as well
in php
$_POST['dataId'] // instead of $_POST['id']
If this not work with you there are some steps you need to do
1- alert(r) on ajax success function and check for errors
2- I don't know what is id and where you get it from so try to alert(id) and see if it output an expected value or not
3- you may need to use shown.bs.modal instead of show take a look at here
4- in js try to get the a data-id by using $(a[data-target="#messageModal"]).data('id') instead of id
so your code should looks like
in js
$('#messageModal').on('shown.bs.modal', function(){
$.ajax({
type: "POST",
url: "viewmessage.php",
datatype: "html",
data:{ dataId : $(a[data-target="#messageModal"]).data('id')},
success: function(r){
$('#messageBody').html( r );
}
});
});
and also in php use $_POST['dataId'] instead of $_POST['id']
So i figured out the issue, it is now displaying the results, however, $(a[data-target="#messageModal"]).data('id'); will not pass the value, i had to use: var id = $("#messageID").attr("data-id");. This is working, but becuase there are multiple instances of #messageID listed, it is only showing the first result becuase you cannot have duplicate ID tags with the same information.
My question is how can i assign or get a value added after #messageID like an array using[ ] to assign a value and have it look for that then get the data-id value to pass?
Related
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.
This is a process that I use for other ajax update functions, but for this specific instance, it doesn't want to work. I don't know if I'm missing something in my code, or if the fact that part of the query string is a url and needs to be encoded before the AJAX plugin (don't know this and couldn't find any info on it, just brainstorming).
When I access the php script directly and echo out the query, then run it in console mode, it works fine. When I try to access it with AJAX, I get the success response, but the entry is not updated in the DB, so I assume that means the script did not run properly.
Here is my code:
AJAX
jQuery('#nl-details').on('click','#d-cl-change', function(){
var mls = jQuery('#d-mls').val(),
cl = jQuery('#d-cl-input').val(),
url = 'scripts/forms/cl/clchange.php?mls='+mls+'url='+cl;
jQuery('#test').html(url); //This is just for me to view the URL
jQuery.ajax({
url: url,
dataType: 'json',
success: function(data){
jQuery('#d-cl-save').fadeIn('200').delay('800').fadeOut('800');
jQuery('#d-cl-url').html('Go to Listing');
},
error: function(){
jQuery('#d-cl-fail').fadeIn('200').delay('800').fadeOut('800');
}
});
});
PHP
//Generic include for MYSQL Credentials
define('INCLUDE_CHECK',true);
require('../../c.php');
$url = mysqli_real_escape_string($link,urldecode($_GET['url']));
$mls = mysqli_real_escape_string($link,$_GET['mls']);
$query = "UPDATE `nht_actprop`
SET CLLINK = '".$url."'
WHERE MSTMLSNO = '".$mls."'";
$result = mysqli_query($link,$query);
echo $query;
mysqli_close($link);
On this line of yor code you are missing a &
url = 'scripts/forms/cl/clchange.php?mls='+mls+'url='+cl;
I think it's supposed to be like this
url = 'scripts/forms/cl/clchange.php?mls='+mls+'&url='+cl;
I see that you have chosen a best answer already but I would just like to share with you how I would tackle this task.
I would recommend using AJAX's type option to send data via GET like this:
jQuery('#nl-details').on('click','#d-cl-change', function(){
var url = 'scripts/forms/cl/clchange.php';
jQuery('#test').html(url); //This is just for me to view the URL
jQuery.ajax({
url: url,
type: 'GET',
data: {
mls: jQuery('#d-mls').val(),
url: jQuery('#d-cl-input').val()
},
dataType: 'json',
success: function(data){
jQuery('#d-cl-save').fadeIn('200').delay('800').fadeOut('800');
jQuery('#d-cl-url').html('Go to Listing');
},
error: function(){
jQuery('#d-cl-fail').fadeIn('200').delay('800').fadeOut('800');
}
});
});
And the best part is that you don't have to change your PHP at all
Good luck! Let me know your thoughts
i have setup some ajax, which i am just testing now, pretty much the idea behind it is to send some data from dropdown boxes to a php script, do some calculations and then return the result, it does it well and returns the result, but now rather than just sending back one result and outputting that, i want to send back multiple results and output them, i am able to send multiple data to the php script, so i am sure i can send multiple back.
Anyway it only sends the first result back and not the rest.
Here is the AJAX
<script>
$("document").ready(function (){
$(".add_extension").change(function(){
var m = document.getElementById('meter_square');
var meter_square = m.options[m.selectedIndex].value;
var s = document.getElementById('story_height');
var story_height = s.options[s.selectedIndex].value;
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
statusCode: {
200: function (result, result2)
{
$("#expected_gain").html(result.value);
$("#house_price").html(result2.value2);
}
}
});
})
});
</script>
And here is the php script
<?php
$meter_square = $_GET["meter_square"];
$story_height = $_GET["story_height"];
$result = $meter_square + $story_height;
$result2 = $meter_square * $story_height;
echo json_encode(array("value" => $result, "value2" => $result2));
?>
You can see that i have already tried to give it a go from what i thought might work, if you need any other code or want me to remove the code i added which doesn't work, then let me know.
Thanks for all and any help
You're only going to receive one response object:
function (response) {
$("#expected_gain").html(response.value);
$("#house_price").html(response.value2);
}
Try this. Think it will help. No need to use status codes if u gonna use only success case
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
success: function(data){
$("#expected_gain").html(data.value);
$("#house_price").html(data.value2);
}
});
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.
Hi i have this simple code:
var datastring="123";
$.ajax({
url: 'actualizarimagen.php',
type: 'post',
dataType: 'text',
data: datastring,
cache: false,
success: function(response){
$('.msg1').html(response);
},
error: function(response){
$('.msg1').html(response);
}
});
And in actualizarimagen.php:
$desc_larga = print('<pre>') & print_R($_POST) & print('</pre>');
$insertSQL = sprintf("INSERT INTO prueba (texto) VALUES ($desc_larga)");
I get the success message, but in the database always saves 1. I tried changing everything, the dataType, the success, error, complete functions but it doesn't work. I was searching but any answers couldn't help me.
Thanks.
Edit: Added response
Your datastring should contain data encoded as application/x-www-form-urlencoded
e.g.: var datastring="foo=123";
It is better not to pass a string to jQuery at all. Pass it an object and let it handle the encoding for you.
e.g.: data: { "foo": "123" }
data
Object, String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
You are just sending up 123 to the server.
It should be something like
var datastring="myField=123";
or
var datastring = {"myField" : 123 };
and with the PHP you would read it
$_POST["myField"]
to send the data, there are format to be followed.
Like
var datastring="var1=123&var2=abcd";
or
var datastring=[{name:'var1',value:123},{name:'var2',value:'abcd'}];
The second format (array of object name value) is like <input type="text" name="var1" value="123"> where html input element has name and value to be posted.
Then, you can get the value by :
$_POST['var1']
or
$_POST['var2']
An example to achieve this easily could be:
JS:
var datastring="123";
$.post('actualizarimagen.php', { datastring:datastring }, function(data){
if(data != 0){
$('.msg1').html('correcto');
} else {
$('.msg1').html('error');
}
});
In your actualizarimagen.php:
if($_POST() && isset($_POST['datastring'])){
/* Connect to DB */
$link = mysql_connect('server', 'user', 'pwd');
if (!$link) {
// No connection
print(0);
exit();
}
$db = mysql_select_db('db', $link);
if (!$db) {
// DB selection error
print(0);
exit();
}
/* Sanitize the value */
$datastring = mysql_real_escape_string($_POST['datastring']);
// I don't understand here what you tried to do with $dec_larga but this is what I thought
$desc_larga = "<pre>".$datastring."</pre>";
/* Insert to DB */
$sql = "INSERT INTO prueba (texto) VALUES ('$desc_larga')";
if(mysql_query($sql,$link)){
// Everything is Ok at this point
print(1);
} else {
// Error happened in your SQL query
print(0);
}
}
In the ajax call:
data: my_var : datastring,
in the php:
$desc_larga = '<pre>'.$_POST['my_var'].'</pre>';
try replacing
type: "post",
with
type: "POST",
and your datastring should be like this :
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1
as explained here:
http://api.jquery.com/serialize/
var datastring = "123";
$.ajax({
url: 'actualizarimagen.php',
type: 'post',
dataType: 'text',
data: {data : datastring},
cache: false
}).always(function(response) {
$('.msg1').html(response);
});
And in actualizarimagen.php:
$desc_larga = '<pre>'.$_POST['data'].'</pre>';
$query = '"INSERT INTO prueba (texto) VALUES ('.$desc_larga.')"';