jquery ajax post request is successive but still not working - javascript

I want to do a simple ajax post request to another page, with the same code I've another time, but this time it does not seem to work, even though the alert I put at success works. The variables do not seem to transfer, but even disregarding the variables and used putting a simple request on the other page does not seem to help. This is my code now:
<script>
$(function(){
$('.sortable').sortable({
stop:function()
{
var ids = '';
$('.sortable div').each(function(){
id = $(this).attr('id');
if(ids == '')
{
ids = id;
}
else
{
ids = ids+','+id;
}
}),
$.ajax({
url:'<?php $_SERVER["DOCUMENT_ROOT"]. "inhoud/dashboard/change_order.php"?>',
data:{ids: ids, user_id: '<?php echo $user_id; ?>'},
type:'POST',
success: alert('yay')
});
}
});
});
</script>
Everything in the script seems to work. The ids array fills exactly how it is supposed to be, and also the user_id is rightly defined. I have tried every way to link to the document, but every way seems to fail. What is supposed to happen is that the call to the other page gets made, where the data given in the post requested is handled, but even though almost exactly the same code works in multiple other scenarios, this time it seems to fail.

You need to add a function inside the success
like this ->
success: function(){ alert('yay'); // do something }

Related

Refresh page when value is = 1

Hello im trying make a system for when on value on my datebase is 1 my index page refresh. this is my code!
All PHP code works, only my index.php not refresh.
index.php
<script>
inverval_timer = setInterval(function update() {
$.get("base_de_dados/update/loadMensagens.php", function(data) {
$("#numseiCategoria").html(data);
window.setTimeout(update);
})
}, 5000);
</script>
loadMensagens.php
<?php
include_once '../bdados.php';
$fila = $conn->query("SELECT * FROM tickets_update");
while($Filas = $fila->fetch_assoc()){
$condicao = $Filas['condicao'];
}
if($condicao == 1){
$condicao = 0;
$queryAtualizar = $conn->query("UPDATE tickets_update SET condicao='$condicao'");
echo "
<div id='a'></div>
<script>
$.ajax({url:'updateMensagens.php', success:function(result){
$('#a').html(result)
}});
</script>";
}
?>
updateMensagens.php
<script>
$(document).ready(function(){
location.reload();
});
</script>
At a glance there are a couple of reasons your page isn't reloading. Firstly, the reload method being wrapped in that .ready() probably prevents it from being called, as I believe the ready event only fires when the DOM first loads.
$(document).ready(function(){
location.reload(); // Will never fire if script is added to DOM after initial load.
});
But I think there's another issue as your code simply appends this HTML...
<div id='a'></div>
<script>
$.ajax({url:'updateMensagens.php', success:function(result){
$('#a').html(result)
}});
</script>";
...onto the end of #numseiCategoria's inner text, which probably doesn't make the browser execute the script anyway (I'm assuming that jQuery's .html() is basically an alias for innerHTML here, I can't be bothered to go and check).
But, in terms of good practices, there's more to it than that...
updateMensagens.php seems to be incredibly redundant, unless there's more to it than you're showing. Let's have a think about how you intended it to work, ignoring the fact that your method of adding scripts to the page is incorrect.
You have your main script in index.php, which sends a get request to loadMensagens.php, which does some database stuff. So far so good...
Your PHP script then echoes some JS, which your main script appends to the page. This JS tells the client to send another get request, this time to updateMensagens.php, and to once again append the result to the page.
This second request returns only a script telling the browser to reload the page. And now we've run into problems.
This is a really awkward and long-winded way to go about this, especially once you try to scale the approach up to larger projects. You're trying to do certain things with PHP which are much more easily done with JS. I'll briefly highlight a couple of things for you.
Firstly, echoing HTML back to the client like that is not great, it gets very unwieldy very quickly. It's much cleaner to return any necessary data to the front end as JSON (or a similar format) and handle generating HTML with JS. jQuery makes generating complex documents rather easy, as you're already using it I'd recommend that approach.
Secondly, this system of using ajax requests to fetch a script from the server to append to the page to perform a simple action with JavaScript is diabolical. Please see my untested, 4AM alternative.
index.php
<script>
inverval_timer = setInterval(function update() {
$.get("base_de_dados/update/loadMensagens.php", function(data) {
let res = JSON.parse(data);
if(res.condiciao === true) {
location.reload();
}
});
}, 5000);
</script>
loadMensagens.php
<?php
$return = [];
include_once '../bdados.php';
$fila = $conn->query("SELECT * FROM tickets_update");
while($Filas = $fila->fetch_assoc()){
$condicao = $Filas['condicao'];
}
if($condicao == 1){
$return['condicao'] = true;
$condicao = 0;
$queryAtualizar = $conn->query("UPDATE tickets_update SET
condicao='$condicao'");
} else {
$return['condicao'] = false;
}
echo json_encode($return);
As an addendum, you seem to be using setTimeout wrong. On one hand I'm quite sure the method is supposed to take 2 arguments, but on the other hand I'm not sure why it's being used at all.
Goodnight.

AJAX returning current page when trying to execute separate PHP query

Okay so, I'm a bit stuck... Here's my problem. So, what I'm trying to achieve is I have a JS calendar and what I want it to do is when I click on a date, it fetches the times available for that day and displays it and then changes depending on what day you click on WITHOUT refreshing the page. Now, looking around, the only way I can seem to do this is with AJAX (suggestions welcome) although I have never touched AJAX before so have no idea what I'm doing here.
So I've currently got my .HTACCESS files setup on my webserver to use dynamic subdomains.
It's sort of like a multi-step form, and I'm collecting data in the SESSION as I go. Now what I'm guessing the way to do is here, to send a AJAX query with a JS variable with the date and then that runs an SQL query and gets the times and displays them. Here's what I have so far.
Update Session
<div class="output"><?PHP echo $_SESSION["outputTimes"]; ?></div>
<script>
$("#clickme").click(function(e) {
e.preventDefault();
$.ajax({
type:'POST',
url:'data.php',
data: { date: '2020-07-04'},
success:function(response){
alert(response);
}
});
});
</script>
data.php
<?php
//Start Session
session_start();
//Include Database Config
include ("config.php");
//POST
$requestDate = $_POST["date"];
//Define SQL Query
$app_get_sql = "SELECT * FROM cc_av WHERE date=$requestDate";
//Run Query
if($result = mysqli_query($db_connect, $app_get_sql)){
while($row = mysqli_fetch_assoc($result)){
$_SESSION["outputTimes"] = '<li>'.$row["time"].'</li>';
}
}
?>
Currently, when I run this, I get the response in the alert() as the current code of the page I'm on. Hence why I noted about my HTACCESS although I can include() it just fine using the same root. Also, from the results of the data.php, how would I output the code sort of update what would be there at the moment.
Here's what I'm trying to create...
https://drive.google.com/file/d/1bgxSUxN6j2IOZcQBuAOo-PeCsuRgdmZ-/view?usp=sharing
Thanks in advance.
So, I've managed to work out what was going wrong. Because my HTACCESS file is creating SubDomains, it was also redirecting the Paths so in the AJAX code I used a URL to the code instead and then added a header to my PHP code on the file that needed to be requested.
header("Access-Control-Allow-Origin: (URL NEEDING TO BE REQUESTED)");
Final AJAX Code
var scriptString = 'THISISMYSTRING';
$('#clickMe').click(function(){
$.ajax({
method: 'get',
url: '(URL)/data.php',
data: {
'myString': scriptString,
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});

Posting a variable to a PHP File with Ajax to delete a row from Mysql - doesn't work

here's my Ajax function.:
$( document ).ready(function(){
$("#deletebutton").click(function(){
var del_id = $(this).attr('name');
var answer = confirm ("Are you sure?");
if (answer)
$.ajax({
type: "POST",
url: "deletescript.php",
data:'delete_id='+del_id,
success: function(data)
{
alert("Done!");
}
});
});
});
And here's the affected button:
echo'<input type="button" name="'.$id.'" id="deletebutton" value="delete">'
Here's my PHP Script called deletescript.php:
$id = $_POST['delete_id'];
$query = "DELETE from items where id = '$id'";
$result = $mysqli->query($query);
Even when I get "Done!" as an alert - my Item still exists. I also checked with Firebug that the correct ID is succesfully sent to the deletescript.php file. What do I have to do? I also tested the SQL-Query manually on my Databse and it worked. Searched for similar questions and found some, sadly even their solutions didn't help. I don't know what to do...
Thank you!
Let print your full query and execute this in your database management tool. So you can see exactly which query it is.
Generally, I will say a couple of things to you:
For deletion, send a DELETE request instead of POST
Don't put variables between quotes
Sanatize query parameters to prevent sql injection
Better alternative and solution for you:
Soft deleting
Add state field to your table
You can have active state and non active state (deleted)
Do you want to delete record? Set state to non active
Default read out the active items
try jquery $.post:
$( document ).ready(function(){
$("#deletebutton").click(function(){
var del_id = parseInt($(this).attr('name'));
var answer = confirm ("Are you sure?");
if (answer){
$.post('deletescript.php',{id:del_id}, function(callback){
if(callback){
alert("Done!");
}
});
}
});
});
The PHP file will get access to the id with $_POST['id']
The callback will contain whatever ur PHP file will echo/show

Minor difficulties with Ajax and PHP interaction

I working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make immediately react, when it is changed:
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
$data['people'] = $this->database->listPeople($_POST['val']);
exit;
}
After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
$('#container').text('<div>' + eval(res).name + '</div>');
});
But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.
Hi the skinny is you need 3 parts to make ajax work,
serverside code to generate the page
ajax ( clientside ) to make the call and respond
seperate serverside to receive it.
Also it will be easier to replace the table completely then to pick out elements. But that is up to you.
So say we have the page with our ajax call
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
</script>
Now you seem to have some json response I'll assume you get this from the alert above;
[{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]
I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );
It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
Header("Content-Type: application/json");
echo json_encode( ....
You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that. Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
alert(v.id);
alert(v.name);
});
});
});
</script>
This should loop through all the data and do 2 alerts, first the id then the name, right. Next it's a simple matter of replacing the content using .text() or .append()
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
$('#test').append('<p>'+v.id+'</p>');
});
});
});
</script>
<p id="test" ></p>

JS variable to PHP variable without buttons or refresh

I've searched for over an hour and tried many examples but none do what I need. From JavaScript I can display the necessary variable in PHP or HTML with <b id="citynm"></b> but I need to make citynm $citynm. I've tried looking in AJAX for the first time but could only get it to work with a button click or page refresh.
I need to run the JavaScript to get citynm and then make it into $citynm for PHP use on any page without running the JS again. The JS is only run once upon entering the site. But the $citynm will be run on several pages in different needs (such as echo "You live in ".$citynm).
The best way is to store the value you want for citynm into a session variable as below:
$_SESSION['citynm'] = $citynm
You have to do this either at page load, or by ajax. Then, you can use $_SESSION['citynm'] in any pages you want since its global.
USECASE 1: via user input
in your html document:
<input type="text" name="citynm" id="citynm" value="Brussels">
inside your javascript file (using jquery here for readability):
(function(){
$('#citynm').on('blur',function(){
// when the input value has changed, post its value to server.
var citynm = $(this).val();
$.post('http://domain.com/path/to/your/php/file.php',{citynm: citynm},function(data){
// if the request is successful, the following script will be executed.
alert("server said: "+data);
});
});
})(jQuery);
And inside the file.php file:
<?php
session_start();
if(isset($_POST['citynm']) && strlen($_POST['citynm'])>0){
$_SESSION['citynm'] = $_POST['citynm'];
}
echo "citynm is ". $_SESSION['citynm'];
?>
USECASE 2: no userinput
var cityname = city.short_name;
if (status == google.maps.GeocoderStatus.OK) { document.getElementById("citynm").innerHTML = cityname; }
(function(){
$.post('http://domain.com/path/to/your/php/file.php',{citynm: cityname},function(data){
// if the request is successful, the following script will be executed.
alert("server said: "+data);
});
})(jQuery);

Categories