Cannot call external function using ajax [duplicate] - javascript

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';
?>

Related

load() function won't allow scripts on page to execute

I have a php script which has a select box which allows user to filter some data.And I have used change event on select box to trigger jquery's load function to load a div of another page which will show that filtered data.Now the problem is I have a javascript function which is being called from that page upon some check in php , and this is resulting in that javascript function not getting called at all.Is there any work around in this scenario?I tried using $.get() but I'm not sure if it will allow me to load only part of page.
This is the load() function's call
$('document').ready(function() {
$('#topic-filter-select').on('change' , function(e) {
$.ajax({
type: 'GET',
url: templateUrl+"/ajax/custom_ajax_functions.php",
data : {
functionName : 'load_topic_filter',
topic_id : e.target.value
},
success: function(result) {
for(var i=0;i<result.length;i++)
result[i] = parseInt(result[i]);
result = JSON.stringify(result);
$('#activity-container').empty();
$('#activity-container').load("/topic-filter-template?result="+result+" #topic-page");
},
error: function(error) {
$('#post-0').empty();
$('#post-0').append("<div id='filtered-activities'><h4>Something went wrong , please try again.</h4></div>");
}
});
});
});
And the php check which gives call to javascript function is
<?php $result = has_user_voted($poll_id , $current_user_id);?>
<?php if($result[0] == true) :?>
<?php echo '<script type="text/javascript">animatePollEffect('.json_encode($result).','.$poll->ID.')</script>';?>
<?php endif; ?>
there your question and code snippet creating a lots of confusion. Please, correct it properly to understand what you want exactly.

Send php request onclick via ajax

I know this question have been asked alot but none of the answer are related to my case ,I have a button ,onclick it should call a javascript function send it a php variable,and ajax would call a php file via post and send that vriable and the php file updates my table
so here is the onclick event first
<button class="button button6 " onclick="incrementclicks('<?php echo $id; ?>');">increment</button>
it should send a variable called $id to the javascript function
<script type="text/javascript">
function incrementclicks(id) {
$.ajax({
url: "increment.php",
data: "id=" + id,
type: "POST"
});
}
</script>
and the php file increment.php (I'm 100% sure it connects to the server just fine )
<?php
require_once 'dbconnect.php';
$db_handle = new DBController();
$id=$_POST["id"];
$q="UPDATE clicks SET linkclicks = linkclicks + 1 WHERE id = '".$id."'";
$result = mysql_query($q);
?>
it doesn't increment, I don't understand what did i do wrong here
First of all you can debug your code on the php by doing
echo $id;
exit();
My quess is that your are missing something there..
Use this method of ajax to check the issue.And if error found check in console for the issue
$.ajax({
url: "increment.php",
type: "post", //send it through post method
data: {
id:id
},
success: function (response) {
alert("success");
},
error: function (xhr) {
//Do Something to handle error
alert("some error found");
}
});
NB:Try to add type="button" to your button for not to reload
<button class="button button6 " onclick="incrementclicks(5);" type="button">increment</button>
I just want to answer this if anyone have future problems like this
The problem is I forgot to add script src at the beginning
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
after adding this my code worked just fine :)

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

How do i send parameter in ajax function call in jquery

I'm creating an online exam application in PHP and am having trouble with the AJAX calls.
I want the questions to be fetched (and used to populate a div) using an AJAX call when one of the buttons on the right are clicked. These buttons are not static; they are generated on the server (using PHP).
I'm looking for an AJAX call to be something like this:
functionname=myfunction(some_id){
ajax code
success:
html to question output div
}
and the button should call a function like this:
<button class="abc" onclick="myfunction(<?php echo $question->q_id ?>)">
Please suggest an AJAX call that would make this work
HTML
<button class="abc" questionId="<?php echo $question->q_id ?>">
Script
$('.abc').click(function () {
var qID = $(this).attr('questionId');
$.ajax({
type: "POST",
url: "questions.php", //Your required php page
data: "id=" + qID, //pass your required data here
success: function (response) { //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page. Here you will have the content of $questions variable available
},
error: function () {
alert("Failed to get the members");
}
});
})
The type variable tells the browser the type of call you want to make to your PHP document. You can choose GET or POST here just as if you were working with a form.
data is the information that will get passed onto your form.
success is what jQuery will do if the call to the PHP file is successful.
More on ajax here
PHP
$id = gethostbyname($_POST['id']);
//$questions= query to get the data from the database based on id
return $questions;
You are doing it the wrong way. jQuery has in-built operators for stuff like this.
Firstly, when you generate the buttons, I'd suggest you create them like this:
<button id="abc" data-question-id="<?php echo $question->q_id; ?>">
Now create a listener/bind on the button:
jQuery(document).on('click', 'button#abc', function(e){
e.preventDefault();
var q_id = jQuery(this).data('question-id'); // the id
// run the ajax here.
});
I would suggest you have something like this to generate the buttons:
<button class="question" data-qid="<?php echo $question->q_id ?>">
And your event listener would be something like the following:
$( "button.question" ).click(function(e) {
var button = $(e.target);
var questionID = button.data('qid');
var url = "http://somewhere.com";
$.ajax({ method: "GET", url: url, success: function(data) {
$("div#question-container").html(data);
});
});

Converting JavaScript function argument to php variable

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

Categories