I am not a big Jquery guy but am using a plugin which is an image uploader. It has a button to remove images with correlates with the following code.
function remove_unwanted_file(id,file)
{
if(confirm("If you are sure that you really want to remove the file "+file+" then click on OK otherwise, Cancel it."))
{
var dataString = "file_to_remove=" +file;
$.ajax({
type: "POST",
url: "remove_unwanted_files.php",
data: dataString,
cache: false,
beforeSend: function()
{
$("#vpb_remove_button"+id).html('<img src="images/loadings.gif" align="absmiddle" />');
},
success: function(response)
{
$('div#fileID'+id).fadeOut('slow');
}
});
}
return false;
}
However, none of the code within the PHP file is ever executed. The alert does pop up and asks you if you want to delete the file with the correct file name. The PHP code is what actually deletes the file however the file does not delete from the file system. I have tried putting other code in the PHP file like sending me an email and none of it executes.
Can anyone see anything wrong with this JQuery code?
THIS IS THE PHP CODE
<?php
$to = 'dev#kylevan.com';
$subject = 'the subject';
$message = 'file reached';
$headers = 'From: noreply#mobilehomelist.com' . "\r\n" .
'Reply-To: noreply#mobilehomelist.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
include('ASApiClientServer.php');
include('ASApiClient.php');
$uniquekey=$_SESSION['uniquekey'];
$postFields = array(
'referralCode'=>$uniquekey,
'image'=>strip_tags($_POST["file_to_remove"]),
),
);
$ApiClient = new ASApiClient();
try{
$ApiClient->requestResponse('removePicture', $postFields);
//handle the call
}
catch(Exception $e){
print_r($ApiClient->getRawResponse());
}
if(isset($_POST["file_to_remove"]) && !empty($_POST["file_to_remove"]))
{
$uploaded_files_location = 'uploaded_files/'.strip_tags($_POST["file_to_remove"]);
#chmod($uploaded_files_location,0777);
#unlink($uploaded_files_location);
//Here you can also delete the file from your database if you wish assuming you also saved the file to your database during upload
}
?>
The email stuff at the beginning is in there just trying to get it to do something. THe path to the file is correct.
First I would make sure the AJAX--to--PHP system is working. You can do that test with two small changes:
1) At the very top of your PHP file, just make it echo out a simple string and die. For example:
<?php
die("I got to here");
2) In your AJAX success function, put an alert() to capture/display the output from the PHP file. For example:
success: function(response)
{
alert("AJAX Recd from PHP: " + response);
//$('div#fileID'+id).fadeOut('slow');
}
Doing these two simple changes will immediately show you where the error is. If the error is in your PHP file, then post another question and ask about that (posting the PHP code, of course).
The next test, I would suggest, is (a very slight modification to the first test) to make the PHP file echo back out the data received via AJAX:
<?php
$f = isset($_POST['file_to_remove']) ? $_POST['file_to_remove'] : '';
die('PHP recd from AJAX: ' . $f);
First make sure your url is correct...
And that remove_unwanted_files.php is the correct path, and not something like example/directory/remove_unwanted_files.php
Then...if it is infact a post request....try this..
$.ajax({
type: "POST",
url: "remove_unwanted_files.php",
data: {file_to_remove:file},
cache: false,
beforeSend: function()
{
$("#vpb_remove_button"+id).html('<img src="images/loadings.gif" align="absmiddle" />');
},
success: function(response)
{
$('div#fileID'+id).fadeOut('slow');
}
});
If its not a Post...
Try this...
var dataString = "file_to_remove=" +file;
$.ajax({
type: "GET",
url: "remove_unwanted_files.php",
data: dataString,
cache: false,
beforeSend: function()
{
$("#vpb_remove_button"+id).html('<img src="images/loadings.gif" align="absmiddle" />');
},
success: function(response)
{
$('div#fileID'+id).fadeOut('slow');
}
});
Related
I'm trying to add a file upload option to my page.
And I use Ajax for this purpose that sends the file to the server (where it is saved)
And should get back the file name
Everything works well except that when I print what comes back instead of just getting the array I send from the server I also get extra information.
Does anyone know where this supplement comes from? and how I can get rid of it?
here is my ajax:
$("#upload_file").change(function(input){
console.log(" in upload_file");
var file_data = $('#upload_file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>organizer/save_event_file',
// dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
beforeSend: function(){
$('#progress_spinner').show();
$('body').addClass('disable_body');
},
success: function(response,status){
console.log(response);
},
complete: function(){
$('#progress_spinner').hide();
$('body').removeClass('disable_body');
}
}).fail(function (xhr, status, error) {
alert("error");
});//fail;
});
this is my server function:
enter code here
public function save_event_file(){ // to add check and prommision
$filePath = $_FILES['file']['tmp_name'];
$type=$_FILES['file']['type'];
//adding to the name with the current date in the end
$date = new DateTime();
$name = substr($_FILES['file']['name'],0,strpos($_FILES['file']['name'],'.')). '__' .$date>format('d.m.y').substr($_FILES['file']['name'],strpos($_FILES['file']['name'],'.'));
$data = array('file' => curl_file_create($filePath, $type, $name));
$response = $this->organizer_model->save_file($data); // save the file with the new name
$result = array('alertcode'=>1,'response'=>$response,'name'=>$name);
echo json_encode($result);
}
this is what I expect to be the response:
{"alertcode":1,"response":true,"name":"old db function__21.03.21.txt"}
this is the real response (The other part is the " {"alertcode":1}" in the beginning):
{"alertcode":1}{"alertcode":1,"response":true,"name":"old db function__21.03.21.txt"}
I have no problem cutting this information and then making a parse as follows:
var ans = JSON.parse(response.substring(response.indexOf('{"alertcode',10),response.length));
But I want to understand where this is coming from - in case this addition changes - and then it will cut the string badly.
Would like to ask for a help. I'm having an issue about getting the right data that I wanted. Maybe there's something lack in my code. I always get null.
I didn't received any error on the console tab.
Here's my ajax
$(document).ready(function() {
$(".fsubmit").click(function() {
var emailval = $("#email").val().trim();
$.ajax({
url: '/test.php',
type: 'POST',
dataType: 'json',
data: 'email='+emailval,
success: function(data) {
console.log(data);
return false;
}
});
});
});
Maybe you could help me fix the PHP. Still learning some stuff. Kindly put some details for lesson please.
Here's my PHP code
<?php
$date = new DateTime();
$datelog = $date->format('d.m.Y h:i:s');
$data = $_POST['data'];
$message = '[' . $datelog . '] - email: ' . json_encode($data);
echo($message);
?>
I appreciate your answer!
Not allowed to comment. Here's a little edit to Mohammad's answer. isset() returns true for blank form fields. Use empty() instead.
this runs in my system ..
ajax call
$(document).ready(function(e) {
$(".fsubmit").click(function() {
e.preventDefault();
console.log("whooowww");
var emailval = $("#email").val().trim();
$.ajax({
url: '/arrayfilter.php',
type: 'POST',
dataType: 'json',
data: 'email='+emailval,
success: function(data) {
console.log(data);
return false;
}
});
});
});
html form
<form>
<input type="text" name="user-input" id="email"/>
<button type="submit">Send</button>
</form>
php
if($_POST){
if(!empty($_POST['email']))
echo "$_POST[email]";
}
}
try this:
$(document).ready(function() {
$(".fsubmit").click(function() {
var emailval = $("#email").val().trim();
$.ajax({
url: '/test.php',
type: 'POST',
dataType: 'json',
data: {email:emailval},
success: function(data) {
console.log(data);
return false;
}
});
});
});
then in php:
<?php
$date = new DateTime();
$datelog = $date->format('d.m.Y h:i:s');
$data = isset($_POST['email'])?$_POST['email']:'';
$message = '[' . $datelog . '] - email: ' . json_encode($data);
echo($message);
?>
You should always check for the posted elements if its isset or not.
The JS
I can see - at least - one major flaw in your JS code. You are passing data: 'email='+emailval to the request. This would be fine (well - possibly not, since you are not URL-encoding your message) for a GET, but with the post I'd doubt, that jQuery can make some decent JSON out of email=Some arbitrary text. At least it will make your JS vulnerable to injections. There are answers on how to send JSON to a webservice with jQuery, please see here.
The PHP
$_POST['data'] (if this is correct) will contain a string. But according to the PHP documentation
json_encode — Returns the JSON representation of a value
I don't think that this is what you want to do. You have a string, and you'll probably want to get an object from your JSON string (actually at the moment, I doubt that it's really a JSON string what you are passing). You can achieve this with json_decode, which
json_decode — Decodes a JSON string
I'd suggest the following PHP code, which decodes the JSON into an array and then outputs the value of email
$data = json_decode($_POST['data'], true);
$message = '[' . $datelog . '] - email: ' . $data["email"];
For this to work, $_POST['data'] will have to look like this
{'email': 'Your message'}
or the like.
I have following form processing php script.
<?php
$G['hotel_email']="xxxx#xxxx.com";
$G['hotel_name']="xxx xxx";
$G['language']="en";
$T['lbl_form_sent_successfully']="H";
# Recipients: comma separated
$G['form_contact_mail_recipients'] = $G['hotel_email'];
$G['form_contact_mail_subject'] = $G['hotel_name'] . ' - Contact Weddings [' . $G['language'] . ']';
# CHECK IF FORM SENT. AJAX. RESPONSE IN JAVASCRIPT TO INTERACT IN THE FORM.
if (!empty($_POST)) {
$js = '';
# ALTERNATIVE CAPTCHA, IT MUST NOT BE FILLED
if (!empty($_POST['title'])) { exit; }
# FORM MAIL TO SENT
unset($_POST['title']);
unset($_POST['submit']);
$message = date("l, F j, Y, g:i a")." [GMT] \n\nFORM DETAILS\n\n\n";
foreach ($_POST as $field => $value) {
$message .= ucfirst(str_replace('_',' ',$field)).': '.$value."\n\n";
}
$message .= "\n\n\n";
mail($G['form_contact_mail_recipients'], $G['form_contact_mail_subject'], $message, "From: ".$_POST['email']."\r\n");
echo "success";
}
?>
The form is being submitted using following JavaScript
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("#ba-form-contact form").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
First_Name: "required",
Surname: "required",
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
}
},
submitHandler: function() {
jQuery.ajax({
type: 'POST',
url: '<?=$_SERVER['REQUEST_URI']?>',
data: jQuery("#ba-form-contact form").serialize(),
dataType: 'html'
});
return false;
}
});
});
</script>
The last echo statement does't work and I don't get any error msg.I do get email with all the info alright.I think nothing work after the mail function, I tried like var_dump, but nothing. What could be the error here?
As per your ajax request, you are not using success method here in ajax request, you need to add success method as:
jQuery.ajax({
url: YourURL,
type: "POST",
data: jQuery("#ba-form-contact form").serialize(),
dataType: "html",
success: function(response) {
alert(response); //this will return the response
},
beforeSend: function()
{
// loading if you need before ajax success
}
});
return false;
Here success: function(response) { will return the success message.
You do not know that it is the echo that does not work.
What you do know is that the script executes, and the jQuery function does not issue output. And that's where half the problem is.
jQuery.ajax({
type: 'POST',
url: '<?=$_SERVER['REQUEST_URI']?>',
data: jQuery("#ba-form-contact form").serialize(),
dataType: 'html'
});
The above does not do anything with the output, so logically nothing happens.
Try this:
jQuery.post({
'<?=$_SERVER['REQUEST_URI']?>',
jQuery("#ba-form-contact form").serialize()
}).done(function(retval) {
// Debug (better use console.log actually)
alert(JSON.stringify(retval));
// Do what you want with retval.message (check retval.status also)
alert(retval.message);
});
and in the PHP, which must output nothing else, end with:
header('Content-Type: application/json');
die(json_encode(array(
'status' => 'success',
'message' => 'The mail was sent',
)));
(I have changed from HTML to JSON output since this allows to send more structured data, with negligible additional complexity).
I am extremely bad at AJAX (actually, I just started to learn it).
So, I write whois service on PHP and I want to make it to output the result via AJAX-request.
All I have at the moment is:
my PHP code:
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:application/json");
$res = $whois->getWhois($domain); // Calls the Whois-query function;
echo json_encode($res);
my JS code:
$('#submit').on('click', function() {
e.preventDefault();
var domain = $('#value').val();
});
$.ajax({
url: 'ajax/whois.php',
type: "post",
data: {'domain': domain, 'action': 'whois'},
dataType: "json",
success: function(json) {
$('#whoisResult').html('<h2>Whois Query result for ' + domain + '</h2>');
$('#whoisContent').html(json.html);
},
error: function(xhr, status) {
$('#whoisResult').html('<h2>Sorry, an error occured. Try again later, please!</h2>')
}
});
As HTML I have an input: <input type="text" id="value"> and the submit button.
I searched for the script examples and tried to make something similar, but it does not work at all...
P.S. Guess you won't hit this question a negative rating :)
P.P.S: As requested, this is my response from PHP:
{"domain":"exp.cm","whois":"[Domain]\nDomain: exp.cm\nStatus: active\nChanged: 2014-02-25T12:22:00.957819+02:00\n\n[Holder]\nType: Legal person\nName: Name, Surname\nEmail: email#example.com\nPhone: Phone here\nAddress: Address goes here\nSome other info\n\nUpdated: 2014-03-18T18:12:35.717462+00:00\n"}
In this case you don't need the JSON datatype, just return html.
Additionally, you'll want the ajax request to be inside the click event. In your click event, you also forgot to pass the e parameter.
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:text/html");
$res = $whois->getWhois($domain); // Calls the Whois-query function;
echo $res;
js:
$('#submit').on('click', function(e) {
e.preventDefault();
var domain = $('#value').val();
$.ajax({
url: 'ajax/whois.php',
type: "post",
data: {'domain': domain, 'action': 'whois'},
//dataType: "json",
success: function(html) {
$('#whoisResult').html('<h2>Whois Query result for ' + domain + '</h2>');
$('#whoisContent').html(html);
},
error: function(xhr, status) {
$('#whoisResult').html('<h2>Sorry, an error occured. Try again later, please!</h2>')
}
});
});
I am trying to add a tell a friend section to a website I am making but I am having difficulty trying to send more than 2 variables through a URL with AJAX. This is the code I have at the moment:
jQuery("#tellafriendsubmit").click(function() {
var email = jQuery('#tellafriendemail').val();
var name = jQuery('#tellafriendname').val();
jQuery.ajax({
type: "POST",
url: "http://www.example.co.uk/tell-a-friend-processor-page/?postname=<?php echo $post_name; ?>&name=name&email="+email,
success: function(msg){
alert('Your tell a friend recommendation has been sent. Thank you for recommending us.');
}
});
});
If I remove the '&name=name' part so that I'm only sending the postname and email address, it works fine but I need to send the name as well so I can write 'Dear $name....'
How can I send the extra 3rd variable? Thanks for any help
Edit:
The part I'm using in the tellafriendprocessor page looks like this:
$email = $_POST['email'];
$post_name = $_GET['postname'];
$name = $_POST['name'];
$to = $email;
$subject = "Example - Tell a friend";
$body = "Dear $name http://www.example.co.uk/ads/$post_name";
if (mail($to, $subject, $body, $headers)) {
} else {
}
You could try sending them as part of the POST request body (using the data property) which will ensure that those values are properly encoded:
var email = jQuery('#tellafriendemail').val();
var name = jQuery('#tellafriendname').val();
jQuery.ajax({
type: 'POST',
url: 'http://www.example.co.uk/tell-a-friend-processor-page/?postname=<?php echo $post_name; ?>',
data: { name: name, email: email },
success: function(msg) {
alert('Your tell a friend recommendation has been sent. Thank you for recommending us.');
}
});
On the server side make sure you are reading them from the $_POST hash ($_POST["name"] and $_POST["email"]).
you can send your parameters to a page with AJAX by GET and POST method with this piece of code
data: { id : 'id', name : 'name' }, // multiple data sent using ajax
Here is an example
$.ajax({
type:"GET",
cache:false,
url:"welcome.php",
data: { id : 'id', name : 'name' }, // multiple data sent using ajax
success: function (html) {
$('#add').val('data sent sent');
$('#msg').html(html);
}
});
You will need to move name outside the string. And to add more key-value-pairs you just append them to the query string: &key=value
url: "http://www.example.co.uk/tell-a-friend-processor-page/?postname=<?php echo $post_name; ?>&name="+name+"&email="+email
Try to use object of params like this:
$.post("/tell-a-friend-processor-page/", { name: "John", email: "<?php echo $post_email; ?>", post_name: "<?php echo $post_name; ?>" },
function(data) {
alert("Data Loaded: " + data);
});