Echo PHP message after AJAX success - javascript

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.

Related

Execute PHP code on form submit without text input

I just want to know if it is possible to execute a PHP post request with ajax by click on a form submit button that does not have any text input. Say i have a form
<form action="connecting.php" id="connect" method="post" enctype="multipart/form-data">
<input type="submit" name="userconnect" id="userconnect" value="connect">
</form>
And i want to execute this block of php code on submit button
connecting.php
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['userconnect']))
{
$my_id = htmlspecialchars($_SESSION['log_id'], ENT_QUOTES, 'UTF-8');
$user_id = (int) htmlspecialchars($_SESSION['userid'], ENT_QUOTES, 'UTF-8');
$rand_num = rand();
$hsql =<<<EOF
SELECT COUNT(hash) as count FROM connect WHERE (user_one = '$my_id' AND user_two = '$user_id') OR (user_two = '$my_id' AND user_one = '$user_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1)
{
echo "<script>alert('You are already connected to this user')</script>";
}
else
{
$usql = $db->prepare("INSERT INTO connect (user_one, user_two, hash) VALUES (:my_id, :user_id, :rand_num)");
$usql->bindValue(':my_id', $my_id, SQLITE3_INTEGER);
$usql->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
$usql->bindValue(':rand_num', $rand_num, SQLITE3_TEXT);
$uret = $usql->execute();
if (!$uret)
{
echo "Error connecting";
}
else
{
echo "Connection Sucessful";
}
}
}
This is the ajax request i am trying to use
$("#connect").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "connecting.php",
data: $(this).serializeArray(), //the data is an issue cause of no text input in for
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(response) {
}
});
});
This doesn't work because there is no data in the form for ajax to send but all data are in the PHP file. How do i execute the php file with ajax. Is there any way?
You dont have to send a POST request to a PHP script in order for it to execute. You can send a normal GET to a URL that executes a PHP script and send you back the JSON data you are looking for. That way, you dont have to send data with the post request and you can still run your PHP script.
Edit*
Another thing you can do is add a hidden ID field or some random text and send that with the POST as data. You dont have to do anything with it, it could just be a time stamp, but it will send the POST request. This is of course overhead and not my kind of programming, but an option nonetheless.
Yes it is possible.... you need to harness a click event...
for example if you had a div element like so:
<div id='mybutton'>click me</div>
then you could use code like this to do literally whatever you want when the button is clicked.:
$('#mybutton').on('click',function(){
$.post...
});
BONUS INFO:
You could also hijack the form submit event like so:
$('#form#myform').on('submit',function(e){
e.preventDefault(); //stop before page is reloaded with post headers
$.post...
});
You don't actually need a form event though, you can just $.get to a php url and return the html or json it generates. just check out the jquery documentation on $.get()

Passing JSON object to PHP script

I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);

Receiving data in Ajax for a Div

So this one problem has taken me on a wild goose chase for a week or so now and I am really hoping that the problem will finally be able to be solved tonight. I'm not at all experienced with Ajax or JS so I really struggle here and am still learning. Here is what I hope to achieve...
I have a basic PHP messaging system in messages.php showing all messages between two users within a DIV which automatically adds a scroll bar when you receive more messages. Here is my DIV which does this:
<div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">
<div id="content">
/// PHP MESSAGE SCRIPT
</div>
</div>
When you send a reply, it uses this Ajax script to send that data to be processed on system/reply_system.php if it notices you are talking to an automated account, it will also send the data to system/sars_system.php to be processed, this works fine for adding, and sending back messages...
<script>
setInterval(function() {
$("#content").load(location.href+" #content","");
}, 5000);
</script>
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
// Second ajax
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
}
</script>
The nice gent who helped me with this script has informed me that I need to receive data back from system/sars_system.php and system/reply_system.php which basically look like this:
<?
require 'db.php';
$message = $_POST['message'];
$conversation_id = $_POST['conversation_id'];
$sarssystem = $_POST['sarssystem'];
$user_id = $_POST['user_id'];
$usr_message = str_replace("'","\\'",$message);
mysqli_query($conn,"INSERT INTO ap_messages (message_id, message, sender_id, time_sent, time_read, conversation_id)
VALUES ('','$usr_message','$user_id', NOW(), NOW(), '$conversation_id')");
mysqli_query($conn, "UPDATE ap_conversations SET time = NOW() WHERE conversation_id = '$conversation_id'");
echo json_encode('success');
?>
But I am having a real big problem trying to figure out how to do that or what data I even need to send back or how I go about coding that in to the current script? If this all works, the final aim is to automatically initiate sending the scroll bar to the very bottom of the page every time this Ajax script runs?
The ajax looks right because it is ready to receive data. In the php you can set the data to whatever you need, it could be the results of the database call. Here's a small example of sending some data back to the ajax script.
$data = array(
'status' => 'ok',
'message' => 'Customer account saved',
);
return json_encode($data);
If you know how to get whatever data you need on the server you can encode it and return it to the client.
The success method will run on the ajax object. It is passed the data and you can reference and manipulate/use it. Your code looks like it is already prepared for this:
success: function(data) { // <-- this is the data in json format from the server
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.

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

jQuery.ajax + php 5.3 - always executing error function

(Newb here) I have a PHP function that gets 2 csv files from the server and create a new one with the difference between values contained in those files. This PHP function is inside a separate file test.php and looks like this:
<?php
require_once('libs/parsecsv-for-php-master/parsecsv.lib.php');
$csv1name = $_POST['csv1'];
$csv2name = $_POST['csv2'];
$data1 = 'data/'.$csv1name.'.csv';
$data2 = 'data/'.$csv2name.'.csv';
$csv1 = new parseCSV($data1);
$csv2 = new parseCSV($data2);
$csv = new parseCSV();
$csv->data[0] = array('label','difference');
$j = 1;
for ($i = 0; $i < count($csv1->data); $i++) {
$csv->data[$i+1] = array($j.'d',$csv1->data[$i][$csv1name] - $csv2->data[$i][$csv2name]);
if($i == 0) {$j += 20;}
else {$j += 21;}
}
$csv->save('test.csv');
?>
This function works correctly and produces the expected csv file.
I have a JavaScript function that sits on another page (namely update.html) and calls the aforementioned php function via ajax:
function callPHP() {
$.ajax({
type:"POST",
url:"test.php",
dataType:"json",
data:{csv1: '02-01-2015', csv2: '02-12-2014'},
error: function(requestObject, error, errorThrown) {
alert(error);
alert(errorThrown);
},
});
}
PROBLEM: The error function is always executed, that is, whenever I run callPHP() I get two alerts.
QUESTION: Why is it error always being called?
(Extra: Is it possible to work with the response variable? How can I debug it without having to upload my files to a server every time? Is it guaranteed that when the complete function is called, the $csv->data function was already resolved?)
Thanks for helping!!! :D
UPDATE 1: I changed the code above by removing the complete function from ajax and I added some extra parameters to the error function.
complete is always called no matter its success or error. So you are running into error condition and complete gets called anyway after error is executed. You can add additional params (jqXHR jqXHR, String textStatus, String errorThrown) in error function to figure out what the error is.
Try using success instead of complete, and add a JSON answer to your PHP script for example echo json_encode((object) array('success'=>true)); because your AJAX call has dataType:"json" parameter for a JSON response, so your AJAX call will try to parse a JSON.
PHP code:
header('Content-Type: application/json');
echo json_encode((object) array('success'=>true));
AJAX:
function callPHP() {
$.ajax({
type:"POST",
url:"test.php",
dataType:"json",
data:{csv1: '02-01-2015', csv2: '02-12-2014'},
success: function(response) {
alert(response);
},
error: function(response) {
alert(response);
},
});
}

Categories