Converting JavaScript function argument to php variable - javascript

I have a js function, which is passed a fileid to delete by a php script.
I don't know how to convert the javascript parameter from JavaScript to PHP variable.
Here is what I have done so far:
<script>
function deleteFile(file)
{
var r = confirm("Are you sure you want to delete this file?");
if (r === true)
{
<?php
$idfile = file; // How to convert it??
unlink(mysql_result(
mysql_query("SELECT filepath FROM
file where idfile='$idfile'"), 0, 0))
or die("Could not delete file");
mysql_query("DELETE FROM file WHERE fileid=$idfile")
or die("Cannot delete file");
echo "File has been deleted successfully.";
?>
}
}
</script>
I have a button also:
echo "<button onclick=\"deleteFile($fileid)\">Delete</button>";
UPDATE
function deleteFile(file)
{
var r = confirm("Are you sure you want to delete this file?");
if (r === true)
{ // doesn't go to deletefile.php
$.ajax({
url: "/deletefile.php",
method: 'POST',
data: {
id: file
}
});
}
}

That won't work. JavaScript and PHP are totally separate entities that execute at different times.
PHP is a server-side language. The PHP code executes on your server and returns a response to the web browser.
JavaScript is a client-side language. It executes when the user is interacting with the page in their browser, after the PHP code has executed.
You'll need to write a separate PHP script that takes the ID of the file to delete, then use AJAX to send the request to delete it with the specified file ID.

You can’t put a Javascript variable in PHP, but you can make an AJAX to send $id_file:
$.ajax({
url: "/action.php",
method: 'POST',
data: {
id: file,
}
});
Then in the PHP action you can use the $_POST['id'] and make the query.

It would be better to use AJAX for example with jQuery. Code you created can't work, that way. Try this.
Generating button with id
<?php
echo '<button class="delete_button" data-id="'.$id.'">delete me!</button>';
?>
Download jQuery from here, save it into your project folder.
Sending post request using jQuery
<script type="text/javascript" src="/path/to/jquery.min.js">
<script type="text/javascript">
$(".delete_button").click(function() {
var id = $(this).data("id");
$.post( "handler.php",{del: id}, function( data ) {
if(data)
{
alert("deleted successfully!");
window.location = "/your/desired/url"; // redirect after success
}
}
}); </script>
deleting in handler.php
if(array_key_exists("del", $_POST))
{
// delete in mysql
}

function deleteFile(file)
{
var r = confirm("Are you sure you want to delete this file?");
if (r === true)
{ // doesn't go to deletefile.php
$.ajax({
url: "/deletefile.php",
method: 'POST',
data: {
id: file
}
})
.done(function( data ) {
console.log(data);
});
}
}
Php
<?php
$idfile = $_POST['id']; // How to convert it??
unlink(mysql_result(
mysql_query("SELECT filepath FROM
file where idfile='$idfile'"), 0, 0))
or die("Could not delete file");
mysql_query("DELETE FROM file WHERE fileid=$idfile")
or die("Cannot delete file");
?>
doesn't go to deletefile.php ? maybe the url is not the correct

Related

How to fix success problem while getting data from php to javascript file?

I have used before these jquery-ajax and php codes. Everything was fine but know there is a problem that success function not working. However, php codes are working, I can add data to mysql database, but I couldn't post info back to javascript file again by use "echo" or any way. Is this problem could originate because of server? I need your support.
I have checked php file is working or not and there was no problem about php. In javascript file in ajax codes, I have tried beforeSend and complete functions, everything were fine. But success function not working.
JS codes:
var userCookie = 1;
var question_txt = document.getElementById("question_txt").value;
var category_slct = document.getElementById("category_slct").value;
$.ajax({
type: "POST",
url: websitePHP + "ask.php",
data: {
user : userCookie,
quest : question_txt,
cat : category_slct
},
beforeSend: function(){
},
success: function(data){
alert(data);
if(data == 'ok'){
alert('Question added');
}
}
})
PHP codes:
include("ayar.php");
$userID = $_POST['user'];
$categoryID = $_POST['cat'];
$question_txt = $_POST['quest'];
$askedTime = time();
$addQuestion = $vt->prepare("INSERT INTO ".$QUESTIONS." (userID, categoryID, question, image, link, sight, pinned, bestAnswerID, askedTime, publishedTime, published)
VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$addQuestion->execute(array(''.$userID.'',''.$categoryID.'', ''.$question_txt.'', '', '', 0, 0, '', ''.$askedTime.'', '', 0));
echo 'ok';
exit();
I need to get back response from php to js by success function in ajax.
Thanks for your help,
Best regards.
Can you try
return 'ok'; instead of echo 'ok'; and removing exit(); function

Update a DIV tag from PHP

I'm a new developer. I've read a lot of question all around about my topic, and I've seen a lot of interesting answers, but unfortunately, I cannot find a way to resolve mine.
I have a simple form in HTML and <div id="comment"></div> in it (empty if there is nothing to pass to the user). This DIV is supposed to give updates to the user, like Wrong Username or Password! when it's the case. The form is treated via PHP and MySQL.
...
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
header("Location: ../main.html");
} else {
//Please update the DIV tag here!!
}
...
I tried to "read" PHP from jQuery (with AJAX), but whether I didn't have the solution, or it cannot be done that way... I used this in jQuery (#login is the name of the form):
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
$("#comment").replaceWith(data); // You can use .replaceWith or .html depending on the markup you return
},
error: function(errorThrown) {
$("#comment").html(errorThrown);
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
But I'd like to update the DIV tag #comment with some message if the credentials are wrong. But I have no clue how to update that DIV, considering PHP is treating the form...
Can you help please ?
Thanks in advance ! :)
In order for AJAX to work, the PHP must echo something to be returned from the AJAX call:
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'good';
} else {
//Please update the DIV tag here!!
echo 'There is a problem with your username or password.';
}
But this will not show up in error: function because that function is used when AJAX itself is having a problem. This text will be returned in the success callback and so you must update the div there:
success:function(data) {
if('good' == data) {
// perform redirect
window.location = "main.html";
} else {
// update div
$("#comment").html(data);
}
},
In addition, since you're calling the PHP with AJAX, the header("Location: ../main.html"); will not work. You will need to add window.location to your success callback dependent upon the status.
To begin, your pretend is using Ajax to send form data to PHP. So your client (HTML) have to communicate completely via Ajax. After you do authenticate, you need send an "Ajax sign" to the client.
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'true';//it's better for using json format here
// Your http header to redirect won't work in this situatition
// because the process is control by javascript code. Not PHP.
} else {
echo "false";//it's better for using json format here
}
//the result is either true or false, you can use json to send more details for client used. Example: "{result:'false', message:'wrong username'}";
// use PHP json_encode(Array(key=>value)) to convert data into JSON format
Finally, you have to check the "Ajax sign" in your js code:
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
// You can use `data = JSON.parse(data)` if the data format is JSON
// Now, data.result is available for your checked.
if (data == 'true')
window.location.href = "main.html";
else
$("#comment").html('some message if the credentials are wrong');
},
error: function(errorThrown) {
$("#comment").html('Other error you get from XHTTP_REQUEST obj');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});

Returning html as ajax response

I have web page that submits a form via AJAX in codeigniter, submission works great, and the php script works as well, but when php is done it return an HTML view as a response to Ajax so it repopulates a div but instead of repopulating it try's to download the file. Chrome console shows
Resource interpreted as Document but transferred with MIME type application/text/HTML
has me confused because I use the same code in another page and it works fine.
This is my Jquery script
$("#addpaymentform").submit(function (event) {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
data: formdata,
url: baseurl + 'sales/add_payment',
success: function (data, status, xhr) {
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
$('#paymets').html();
$('#payments').html(data);
$('#addpaymentform').each(function() { this.reset() });
}
if (ct.indexOf('json') > -1) {
$("#Mynavbar").notify(
data,
{position: "bottom center"}
);
$('#addpaymentform').each(function() { this.reset() });
}
}
});
event.preventDefault(); // this will prevent from submitting the form.
});
and this is my controller
function add_payment()
{
$this->form_validation->set_rules('fpay', 'Type of payment', 'trim|required|alpha');
$this->form_validation->set_rules('payment', 'Payment', 'trim|numeric');
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run() == FALSE) { // validation hasn't been passed
header('Content-type: application/json');
echo json_encode(validation_errors());
} else {
$fpay = filter_var($this->input->post('fpay'), FILTER_SANITIZE_STRING);
$payment = filter_var($this->input->post('payment'), FILTER_SANITIZE_STRING);
if(isset($_SESSION['payments'][$fpay]))
{
$temp = $_SESSION['payments'][$fpay] + $payment;
$_SESSION['payments'][$fpay] = $temp;
header('Content-type: application/html');
echo $this->_loadpaymentcontent();
}
}
}
function _loadpaymentcontent() {
$this->load->view('payment_content');
}
Hope someone can point me in the right direction I've been stuck on this for 2 days.
Thanks everyone.
I had the same problem and i successfully solved it by putting an exit; after the value which is returned to the ajax call in the controller method.
In your case it will be:
echo $this->_loadpaymentcontent();
exit;
What exit does here is it limits the returned value to the value which should be returned to the ajax call and exits before the html is appended to the returned value.
This is what is obvious per the effect it produces.
Yo need to set up your AJAX.
$.ajax({
type : 'POST',
url : baseurl + 'sales/add_payment',
dataType : 'html', // Will set the return type of the response as AJAX.
... Keep rest of the code same.

Cannot call external function using ajax [duplicate]

This question already exists:
Deleting a specific node based on dropdown selection in XML [duplicate]
Closed 7 years ago.
Here's my jquery code
<script>
$(function () {
$('#deleteform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'delete.php',
success: function () {
alert('Worked');
}
});
});
});
</script>
And my PHP code (I'm just trying to test it out, so I added a simple function)
<?php
header("Location: http://www.google.com/");
?>
And nothing happens when I click the button (when the form submit) except that "Worked" alert box. But whatever I put in that PHP file (delete.php), nothing happens. What am I doing wrong? My "delete.php" file will have a script to delete data in a XML file, just in case it changes something. (for now Im trying with a simple php line)
EDIT
The real PHP code that will go in the PHP file is this :
<?php
$xml = simplexml_load_file("signatures.xml");
$name = $_POST['nom'];
$signs = $xml->xpath('//Signature[Nom = "'.$name.'"]');
$xml -> SignaturesParent -> removeChild($signs);
?>
Nothing happens when I try that.
Try this.
The ajax call now alerts whatever is sent to it from the delete.php
The ajax call does a POST and not a GET so that it matches the fact that you are using $_POST[''] and send some data i.e. smith you are going to have to change that to something that actually exists in your XML file
The delete.php actually returns something
The delete.php saves the changed xml document back to disk to a file with a different name, so you can see if it actually did anything. just while you are tesing.
<script>
$(function () {
$('#deleteform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'delete.php',
data: {nom:"smith"},
success: function (data) {
alert(data);
}
});
});
});
</script>
<?php
$xml = simplexml_load_file("signatures.xml");
$name = $_POST['nom'];
$signs = $xml->xpath('//Signature[Nom = "'.$name.'"]');
$xml -> SignaturesParent -> removeChild($signs);
$result = $xml->asXML("signatures2.xml");
echo $result ? 'File Saved' : 'File Not Saved';
?>

From a running PHP Code, how to update status in DIV tag

I have a web Page, in which i an downloading data one after another in a loop. After each data download is finished i want to update the status to a DIV tag in the Web Page. How can i do this. Connecting to server and downloading data via php code and the div tag is within the .phtml page.
i have tried
echo "
<script type=\"text/javascript\">
$('#tstData').show();
</script>
";
But the echo statement update will happen at the end only. Refreshing of DIV tag need to happen at the end of each download.
Use jQuery load()
$('#testData').load('http://URL to script that is downloading and formatting data to display');
$("#save_card").submit(function(event) {
event.preventDefault();
var url = "card_save.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
dataType:"json",
data: $("#save_card").serialize(), // serializes the form's elements.
success: function(data)
{
console.log(data);
if(data.msg=="success")
{
$("#submit_msg").html("Thank You !!!");
console.log("Record has been Inserted Successfully!!!");
}
else
{
$("#submit_msg").html(data.er);
console.log("There Is Some Error");
}
$("#submit_msg").show();
setTimeout(function() { $("#submit_msg").hide(); }, 5000);
$("#save_card").get(0).reset();
}
});
return false; // avoid to execute the actual submit of the form.class_master
});
Use This Ajax function to call PHP function to get data. Here
#save_card = Id of the form that you want to submit.
url = action for the form or the location to the php file from where your data is coming.
data: $("#save_card").serialize() = it is sending all the data of the form in serialize form. Data can be created manually to do this repalce this line with data: {'name':name,'year':year}
function(data) = here data is returned from the php code in json formate.
data.msg = It is a way to access different field from data.
$user_email = $_REQUEST['user_email'];
$cat_id = $_REQUEST['category'];
$title = $_REQUEST['title'];
$country = $_REQUEST['country'];
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO project(title, user_email, cat_id, country, start_date) VALUES ('$title','$user_email','$cat_id','$country', '$date')";
if (mysql_query($sql)) {
$project_id = mysql_insert_id();
echo json_encode(array('project_id' => $project_id, 'msg' => 'Successfully Added', 'status' => 'true'));
} else {
echo json_encode(array('msg' => 'Not Added', 'status' => 'false'));
}
PHP code to send data in json format

Categories