Want to send a ajax request to php to create a new table dynamically. I have the following code:
Javascript:
var file = $('#'+option_file_name.id).prop('files')[0];
var form_data = new FormData();
form_data.append('file', file);
form_data.append('column_name', option_file_name.id.slice(12));
send_ajax_request(form_data);
function send_ajax_request(pdata){
console.log(pdata);
$.ajax({
url: "set_points_data.php",
data: pdata,
contentType: false,
processData: false,
dataType: "json",
type: 'post',
success: function (data) {
console.log(data);
},
error: function(a,b,c){
alert("something went wrong");
}
});
}
php script:
in the data.php file i connect to the database and have all the supporting functions.
<?php
include 'data.php';
$data = null;
if(isset($_FILES)){
$data = $_FILES;
$type = (string)$_POST["column_name"];
create_table($conn, $type);
return_ajax("succes");
}else{
return_ajax("error");
}
function create_table($conn, $name){
send_sql($conn, "CREATE TABLE `".$name."` (
options varchar(255));"
);
}
?>
UPDATE:
it turns out that if i change the following code to this the error disappears. see the new code below:
send_sql($conn, "CREATE TABLE testTable (
options varchar(255)
);");
but this is not what i want i need to create tables dynamically.
when ever i run run the ajax request i get the error something went wrong.
But when i run the php script without the ajax call it works fine.
and when i run the php script from the ajax call but without the create table function it also works fine. So i am not sure what is happening here.
Hope this is clear if not let me know.
After doing some testing i figured out that ajax is trying to return some data after doing the create table statement. Resulting in a error. if you change it to the following.
if(isset($_POST)){
$data = $_FILES;
$db_name = $_POST["tblname"];
return_ajax(create_table($conn, $db_name));
}else{
return_ajax("error");
}
function create_table($conn, $name){
send_sql($conn, "CREATE TABLE `".$name."` (
options varchar(255)
);");
return "database created";
}
This wil work. not sure what exactly happens but this fixes the ajax error.
Related
This might be a dumb question. I'm fairly new to PHP. I am trying to get a look at some echo statements from a page I'm posting to but never actually going to. I can't go directly to the page's url because without the post info it will break. Is there any way to view what PHP echos in the developer console or anywhere else?
Here is the Ajax:
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
imgurl = 'url';
filepath = 'path';
$.ajax({
url: imgurl,
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
error: function(data) {
console.log(data);
}
});
}
And here is the php file:
<?php
$image = $_FILES['image']['name'];
$uploaddir = 'path';
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo $uploadfile;
} else {
echo "Unable to Upload";
}
?>
So this code runs fine but I'm not sure where the echos end up and how to view them, there is more info I want to print. Please help!
You already handle the response from PHP (which contains all the outputs, like any echo)
In the below code you have, url will contain all the output.
To see what you get, just add a console.log()
$.ajax({
...
success: function(url) {
// Output the response to the console
console.log(url);
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
...
}
One issue with the above code is that if the upload fails, your code will try to add the string "Unable to upload" as the image source. It's better to return JSON with some more info. Something like this:
// Set the header to tell the client what kind of data the response contains
header('Content-type: application/json');
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo json_encode([
'success' => true,
'url' => $uploadfile,
// add any other params you need
]);
} else {
echo json_encode([
'success' => false,
'url' => null,
// add any other params you need
]);
}
Then in your Ajax success callback, you can now check if it was successful or not:
$.ajax({
...
dataType: 'json', // This will make jQuery parse the response properly
success: function(response) {
if (response.success === true) {
var image = $('<img class="comment_image">').attr('src', path + response.url);
$('#summernote').summernote("insertNode", image[0]);
} else {
alert('Ooops. The upload failed');
}
},
...
}
If you add more params to the array in your json_encode() in PHP, you simply access them with: response.theParamName.
Here is a basic example...
HTML (Form)
<form action="script.php" method="POST">
<input name="foo">
<input type="submit" value="Submit">
</form>
PHP Script (script.php)
<?php
if($_POST){
echo '<pre>';
print_r($_POST); // See what was 'POST'ed to your script.
echo '</pre>';
exit;
}
// The rest of your PHP script...
Another option (rather than using a HTML form) would be to use a tool like POSTMAN which can be useful for simulating all types of requests to pages (and APIs)
Ok, I am officially stumped. I have been trying to find why my calls for specific items in a PubMed xml data file are not working... I can execute this one with my current coding:
$test = (string)$id_json->PubmedArticle->MedlineCitation->PMID;
but if I try to get a variable that is in a deeper array, it does not return a value. I have even tested with console.log(data) and I get my PMID returning but not my other, deeper values in the XML file. For example;
$test = (string)$id_json->PubmedArticle->MedlineCitation->Article->Journal->ISSN;
returns nothing for data in console.log(data)
Here is my function in wordpress:
function get_abstract(){
$id = $_POST['abstractid'];
$pubmed_api_call = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=abstract&id='.$id;
$id_wpget = wp_remote_get($pubmed_api_call, array('timeout' => 20));
if( is_wp_error( $id_wpget ) ) {
echo "Error Contacting PubMed, please refresh page and try again";
die();
}
$id_xml = wp_remote_retrieve_body($id_wpget);
$id_json = simplexml_load_string($id_xml);
$test = (string)$id_json->PubmedArticle->MedlineCitation->Article->Journal->ISSN;
if($test === ""){
echo "NOTHING";
die();
}
echo $test;
die();
}
and here is my javascript AJAX call:
jQuery(document).ready(function() {
jQuery('.reference_header').click(function(e) {
jQuery(this).find("i").toggleClass("arrow-down arrow-up");
jQuery(this).nextUntil('.reference_header').slideToggle('fast');
var abstractid = jQuery(this).data("id");
e.preventDefault();
jQuery.ajax({
url: get_abstract.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
abstractid: jQuery(this).data("id"),
action: 'get_abstract'
},
success : function(data){
jQuery('.'+abstractid).html("TESTING: "+data);
console.log(data);
}
});
});
});
I cannot find out why it doesnt work... any help is greatly appreciated.
So I figured out the solution to the issue... you need to pass the string text as a json object to AJAX for it to read properly...
working code:
PHP:
echo json_encode(array("result" => "$test"));
die();
AJAX:
success : function(data){
jQuery('.'+abstractid).html("TESTING: "+data.result);
console.log(data.result);
}
I am new to $.ajax and don't know so much and i have following button to delete user post by article ID
<button type="button" onclick="submitdata();">Delete</button>
When click this button then following $.ajax process running.
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
var datastring='post_id='+post_id;
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:datastring,
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
And delete.php is
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_GET['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
This code not working post not deleted. Please how do I do?
You likely want to not only match the "GET" you use in your PHP but also add the ID to the button
<button class="del" type="button"
data-id="<?php echo $userIdRow['post_id']; ?>">Delete</button>
using $.get which matches your PHP OR use $.ajax({ "type":"DELETE"
$(function() {
$(".del").on("click", function() {
$.get("delete.php",{"post_id":$(this).data("id")},
function(html) {
alert(html);
}
);
});
});
NOTE: Please clean the var
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
Using ajax DELETE with error handling
$(function() {
$(".del").on("click", function() {
$.ajax({
url: "delete.php",
method: "DELETE", // use "GET" if server does not handle DELETE
data: { "post_id": $(this).data("id") },
dataType: "html"
}).done(function( msg ) {
$( "#log" ).html( msg );
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
In the PHP you can do
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
$id = $_REQUEST["post_id"] ....
}
since you're sending a post request with ajax so you should use a $_POST iin your script and not a $_GET
here is how it sould be
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_POST['post_id']) && is_numeric($_POST['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_POST['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
for the JS code
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:{"post_id":post_id},
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
here i've supposed thqt the give you the real id post you're looking for !!
The reason is pretty simple. You should change your request type to GET/DELETE instead of POST. In PHP you expect GET request but in AJAX you send POST request
Change:
type:"POST",
url:"delete.php",
data:datastring,
to
type:"DELETE",
url:"delete.php?" + datastring,
in PHP
if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && !empty($_REQUEST["post_id") {
$id = $_REQUEST["post_id"];
// perform delete
}
DELETE is actually the only valid method to delete objects. POST should create an object and GET should retrieve it. It may be confusing at first time but it's good practicet specially used in REST APIs. The other one would be UNLINK if you wanted to remove relationship between objects.
Follow #roberts advise and also:
You should have a way to handle errors eg.
to your ajax code add this:
error:function(e){
alert(e.statusText)// if you like alerts
console.log(e.statusText)// If you like console
}
You should also check your error logs. Assuming you use apache2 and linux
execute this in terminal:
tail -f /var/log/apache2/error.log
This gives you a very elaborate way to code. You also eliminate the problem of trial and error.
i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).
I've been trying to save some data to a .json file with ajax and php.
At the moment I'm receiving an error and my data is not being saved and can't figure out why.
This is my .js file:
var data = {
"test": "helloworld"
}
$.ajax({
url: "save.php",
data: data,
dataType: 'json',
type: 'POST',
success: function (data) {
$("#saved").text("Data has been saved.");},
error: function (data){
$("#saved").text("Failed to save data !");}
});
And here is my php file:
$json = $_POST['data'];
if(json_decode($json) != null){
$file = fopen('web/js/data_save.json', 'w+');
fwrite($file, json_encode($json));
fclose($file);
}else{
print("<pre>Error saving data !</pre>");
}
When I'm trying to save the ajax error is getting triggered:
error: function (data){
$("#saved").text("Failed to save data !");
}
I hope someone can guide me in the right direction :)
this works fine for me
.js:
$(document).ready(function() {
var json_object = {"data": "helloworld"};
$.ajax({
url: "../tests/save.php",
data: json_object,
dataType: 'json',
type: 'POST',
success: function(json_object) {
console.log(json_object);
$("#saved").text("Data has been saved.");
},
error: function(json_object) {
console.log(json_object);
$("#saved").text("Failed to save data !");
}
});
});
.php
$post_data = $_POST['data'];
if (!empty($post_data)) {
$file = fopen('data_save.json', 'w+');
fwrite($file, json_encode($post_data));
fclose($file);
echo json_encode('success');
}
if you do a var_dump on the $_POST you ll see that your variable is sent as an array in php. also you need to echo a json string for the callback success
You do not have any key data in your request.
You need to parse the whole request body as JSON with http_get_request_body or something to get the raw body in order to get the result you want.
EDIT: As it seems that there has been some confusion, here are some further explanations.
When sending a JSON POST request to PHP, you cannot use the $_POST variable as you would with a normal request.
curl -H 'Content-Type: application/json' -d '{"foo": "bar"}' myhost/foo.php
with foo.php defined as bellow will print an empty array, try it yourself if you want.
<?php
print_r($_POST);
When you need to get JSON from the body of the POST request, you need to get all the body, and then parse it from JSON.
You can do this in several ways, one of which being the one I wrote before editing.
You can also get the whole body without using any extension by using
file_get_contents('php://input')
The result should be the same.
So with the code bellow you should get what you want.
<?php
$json = json_decode(file_get_contents('php://input'), true);
print_r($json);