I have editable html table of user Information. There are some columns such as user_ID, branch_ID etc. when I am going to change the branch_ID of the user I want to check the particular user has tasked assigned to him or not. If he has tasks then update is not allowed. for that I am using the following java script part.
if(field=='branch_ID'){
$.ajax({
type: 'post',
url: 'check_user.php',
data: {udata: user_id},
success: function (data) {
// message_status.text(data);
}
})
}
In check_user.php
$user_id= $_POST['udata'];
$sql1="SELECT * FROM assign_task WHERE user_ID=$user_id";
$query1=mysqli_query($con,$sql1);
if(mysqli_num_rows($query1)>0){
echo"you can't update";
return false;
}
else{
echo"ok with it".$sql1;
}
The thing is I want the respond from check_user.php as an alert and return false to stop updating the content. As I am new to jQuery please help me.
You can use JSON to pass more complex data:
PHP :
if(mysqli_num_rows($query1)>0){
echo json_encode(array("success" => false));
}
else{
echo json_encode(array("success" => true,
"message" => "ok with it".$sql1));
}
Javascript:
success: function (data) {
var jsonData = JSON.parse(data);
if(jsonData.success){
alert(jsonData.message);
}
}
Remember to do more advanced checking on your variables and types first!
Related
I.m want to pass the values from js to php that is stored in local storage
js
let cartItems = localStorage.getItem("productsInCart");
var jsonString = JSON.stringify(cartItems);
$.ajax({
url:"read.php",
method: "post",
data: {data : jsonString},
success: function(res){
console.log(res);
}
})
php
<?php
print_r($_POST)
?>
on .php im getting just "array ()"
using #reyno's method with all the code in the same file called 'store_user_order.php'
<?php
if(isset($_POST["data"])) {
print_r($_POST["data"]);
} else {
?>
<button>SEND</button><br/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"> </script>
<script>
const cartItems = localStorage.getItem("productsInCart");
const jsonString = JSON.stringify(cartItems);
$("button").click(function() {
$.ajax({
url: 'store_user_order.php',
method: 'post',
data: {
data: jsonString
},
success: function(res) {
$('body').append(res);
},
error: function(err) {
$('body').append(err);
}
});
})
</script>
<?php } ?>
This should work if you have items in the localstorage
While testing, for checking values use method: "get", make sure that your test values aren't huge - you will see submitted values in the address bar.
For testing (php + MySQL) I always use this method:
success ? changes() : errors_list();`
I don't use js, so deal with syntax yourself, please.
on .php im getting just "array ()"
You received an empty $ _POST array - nothing was sent.
Because there was nothing to send, or there was an error sending
I am currently trying to implement a 'Delete' button that clears a MySQL table of all its data. I am finding it much more difficult than the submit button was.
Researched examples all show how to do it by a row, but I just have a single 'Delete' button. I believe I am currently way off, as I was trying to come up with a solution based on the submit Ajax function.
Currently:
HTML
<button class="myButton" id="delete" type="delete">DELETE</button>
JavaScript (This is where my hangup is I think)
function deleteMessage() {
$.ajax({
type: 'POST',
url: 'info_message.php',
async: false,
//data: ,
success: function(response) {
if (response == "success") {
successPopup("Successfully deleted message");
}
else {
alert("Unable to delete message. " + response);
}
}
});
}
PHP (or here???)
if (isset($_POST['deleteMessage'])) {
$message = $_POST['message'];
// Deletes all records in Announcement table
$query = "DELETE from Announcement";
if ($dbc->query($query) === FALSE) {
echo "Error: " . $query . "<br>" . $dbc->error;
}
else {
echo "success";
}
exit();
}
You looking for post data which you're not passing with your ajax call. Specifically you need to add deleteMessage and message which is the 2 post variables you are trying to read in your php script. Something like below
$.ajax({
type: 'POST',
url: 'info_message.php',
async: false,
data: { deleteMessage: true, message:"insert what message you want to pass" } ,
success: function(response) {
if (response == "success") {
successPopup("Successfully deleted message");
}
else {
alert("Unable to delete message. " + response);
}
}
});
}
I'm trying to call an PHP file via POST and retrieve its result back in the calling AJAX code. But unfortunately it doesn't seem to work. After fiddling around with my code I either get "undefined", "a page reload" or "an error in the console that my parameter used in the success function isn't defined"
Here's the ajax code:
function postComment(formdata) {
if (formdata.comment != '') {
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
success: postSuccess(data), // function to handle the return
error: postError // function to handle errors
});
} else {
alert('Empty please write something!');
}
}
function postSuccess(data) {
console.log(data);
$('#commentform').get(0).reset();
displayComment(data);
}
and here is my PHP handler:
$ajax = ($_SERVER['REQUESTED_WITH'] === 'XMLHttpRequest');
$added = add_comment($mysqli, $_POST); // contains an array
if ($ajax) {
sendAjaxResponse($added);
} else {
sendStandardResponse($added);
}
function sendAjaxResponse($added)
{
header("Content-Type: application/x-javascript");
if ($added) {
header('Status: 201');
echo(json_encode($added));
} else {
header('Status: 400');
}
}
this is what added looks like in PHP:
$added = array(
'id' => $id,//integer example: 90
'comment_post_ID' => $story_ID, //integer example: 21
'comment_author' => $author, //String example: Dominic
'comment' => $comment, //String example: This is a comment
'comment_date' => $date); //DateTime/String example: 08/02/2016 1970-01-01 00:00:00
UPDATES
I changed the ajax code to the following:
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
success: postSuccess,
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
error: postError,
});
Now I get the full HTML-Code of the page calling this ajax function
I tried to set aysnc: false in the ajax request but it didn't help, always getting the html code of the source (calling the ajax function).
As for now I´m moving to a different approach which doesn´t need the return data. But thanks for the help
The browser tries execute server response because of
header("Content-Type: application/x-javascript");
change to
header("Content-Type: application/json");
I send an ajax request when the user fills the email input, here is the code:
_email.blur(function(){
$.ajax({
url : base_path("user/register/ajax/email"),
type: "POST",
data: ({ email : _email.val() , }),
success: function(message)
{
alert(message);
},
});
}); // end of email blur
Then the php returns a string on success, and one on failure (CodeIgniter Controller)
if($param == "email")
{
$this->form_validation->set_rules("email", "required | email");
$this->form_validation->set_rules("email", "is_unique[users.email]");
if($this->form_validation->run !== FALSE)
{
echo (json_encode("thanks"));
}
else
{
echo (json_encode("Ranks"));
}
}
PROBLEM: it seems ajax request is successful, but the message it alerts is not appropriate since it alerts an empty string.
i'd look at this:
json_encode("thanks")
I havent coded any PHP for a long time but shouldnt json_encode be for encoding associative arrays? eg
json_encode(array("message" => "thanks"))
as you are using json_encode you could try this after the if else statement
exit(json_encode($respond));
return $this->output->set_output(json_encode($respond));
where $respond is the message you want to display.
_email.blur(function(){
$.ajax({
url : base_path("user/register/ajax/email"),
type: "POST",
data: ({ email : _email.val() , }),
success: function(message)
{
alert(message);
}
});
});
if($param == "email")
{
$this->form_validation->set_rules("email", "required | email");
$this->form_validation->set_rules("email", "is_unique[users.email]");
if($this->form_validation->run !== FALSE)
{
echo "thanks";
}
else
{
echo "Ranks";
}
exit;
}
For resonse in json you should use data type like:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
php code:
json_encode(array("content" => "thanks"));
js code:
success: function(message)
{
alert(message.content);
}
User fills input texts, presses the button Submit. The data sends to the server to be stored and result returned back. Fancybox window with result appears. My question is: how to display the result $res1 in the fancybox?
$.ajax({
type:"POST",
url:"index/success",
async:false,
data:{ name:name, password:password},
success:function ()
{
var html='$res1 from the server should be here instead of this string';//var html=$res1.
$.fancybox(
{
content: html,//fancybox with content will be displayed on success resul of ajax
padding:15,
}
);
}
});
=========================
OK, still doesn't work (returns in the fancybox the whole page+ the word "hello" on top instead of the message "hello"). Below is my update regarding the answers below, that doesn't work properly:
PHP:
<?php
$res1="hello";... // handle logic here
echo $res1; // print $res1 value. I want to display "hello" in the fancybox.
?>
AJAX
$.ajax({
type: "POST",
url: "index/success",
async: false,
data: {
name: name,
password: password
},
success: function (html) {
$.fancybox(
{
content: html,//returns hello+page in the fancybox
//if I use the string below instead of the upper one, the fancybox shows "The requested content cannot be loaded. Please try again later."
// content: console.log(html)
padding:15,
}
});
=============
New update:
Fixed!!! The problem was the data ( "hello" in the example above) was sent to the template in the framework, and template was displayed.
That's why.
Fixed.
Thank you.
Everybody.
Assuming you're using PHP:
PHP:
<?php
... // handle logic here
echo $res1; // print $res1 value
?>
AJAX:
$.ajax({
type: "POST",
url: "index/success",
async: false,
data: {
name: name,
password: password
},
success: function (html) {
// given that you print $res1 in the backend file,
// html will contain $res1, so use var html to handle
// your fancybox operation
console.log(html);
}
});
Enjoy and good luck!
$.ajax({
type:"POST",
url:"index/success",
async:false,
data:{ name:name, password:password},
success:function(html){ // <------- you need an argument for this function
// html will contain all data returned from your backend.
console.log(html);
}
});