ajax and php pettition satuts cancelled after x attempts [duplicate] - javascript

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
im making and update in mysql table when button click, the problem is ajax jquery not working sometimes. It works fine and somehow after x attempts it stop working and stars cancelling my petitions
the problem is after x number of attempts the success part of ajax object is not being used and im getting the STATUS (canceled) from network.

Pass these values to hidden fields. These fields are called through ajax to send data to next-page to update.
<input type='hidden' value="<?echo $costo_sem;?>" class="costosemanal">
<input type='hidden' value="<?echo $fi;?>" class="fechai">
<input type='hidden' value="<?echo $ff;?>" class="fechaf">
echo "<script>
var r = confirm('OK to update, CANCEL to do nothing');
if(r === false){
document.location.href = 'costos.php';
}else{
var costosemanal=$('.costosemanal').val();
var fechai=$('.fechai').val();
var fechaf=$('.fechaf').val();
$.ajax({url:'UpdatePage.php?costosemanal='+costosemanal+'&fechai='+fechai+'&fechaf='+fechaf,cache:false,success:function(result){
alert('Updated');
}});
}
</script>";
Add one UpdatePage.php to update your query.
UpdatePage.php
<?
$costosemanal=$_GET['costosemanal'];
$fechai=$_GET['fechai'];
$fechaf=$_GET['fechaf'];
$update = "UPDATE tbl_costos SET costo_semanal = '$costosemanal' WHERE fechai = '$fechai' AND fechaf ='$fechaf' ";
//Write Mysql Command To Update This Query
?>

$('.removeItem').click(function (event) {
if (confirm('Are you sure you?')) {
$.ajax({
url: 'myUrl',
type: "POST",
data: {
// data stuff here
},
success: function () {
// does some stuff here...
}
});
}
});
Use above code inside url there must be php page url...

Related

Last chance at jQuery AJAX Toggle

I posted this question ealier today, however I recieved a fix (thank you) that works great against my RequestBin endpoint for testing, however when submitting to my AJAX script, its a different story.
Problem: I cant submit my jQuery toggle values to my PHP AJAX script because there is no form name associated with the POST request (so db never updates). I proven this by making a HTML form with the field names and the database updated right away. However this is not the case with this JS toggle method.
jQuery code
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: {
value: $this.hasClass("switchOn") ? 'pagination' : 'infinite'
},
success: function(data) {
console.log(data);
}
});
});
});
HTML
<div class="wrapper-toggle" align="center">
<label>
<div class="switch"></div>
<div class="switch-label">Use <b>Paged</b> results instead (Current: <b>Infinite</b>)</div>
</label>
</div>
PHP AJAX script
if (array_key_exists('pagination', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'pagination' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
} else if (array_key_exists('infinite', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'infinite' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
}
I cant figure out how to assign a field name to this, as it is not a traditional post form. This is driving me nuts. So the previous solution was applying hasClass() and calling var $this outside of $ajax(), great (and RequestBin receives both requests), but when submitting to PHP its a dead end (no form names).
Given the code above fixed and revised twice, where do I even start without a form ??
We need:
name="pagination"
name="infinite"
But this toggle JS doesn't allow for this. prop() has been removed to get toggle submitting values over (just not my AJAX script).
Any solution appreciated. Thank you again.
You can set your values as Form Data. So the PHP Function will get it just like a traditional form submission:
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
var formdata = new FormData();
$this.hasClass("switchOn") ? formdata.append('pagination', 'name') : formdata.append('infinite', 'name');
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: formdata,
success: function(data) {
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
More info on JS Form Data: https://developer.mozilla.org/en-US/docs/Web/API/FormData

$_SESSION var no passed [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
I have php page which contains two javascript functions like this:
function PregledDokumenta(id)
{
var info = id.split('-');
var vrdok = info[0];
var brdok = info[1];
$.ajax({
type: "POST",
url: "../Php/Dokument/Pregled.php",
data: { vrDok: vrdok, brDok: brdok },
success: function(returnedData)
{
document.getElementById('Content').innerHTML = returnedData;
<?php
$_SESSION['vrDok'] = vrdok;
$_SESSION['brDok'] = brdok;
?>
<?php
$a = $_SESSION['vrDok'];
echo("alert($a);");
?>
}
});
}
function UnosNoveStavke()
{
var vrdok = <?php echo($_SESSION['vrDok']);?>;
var brdok = <?php echo($_SESSION['brDok']);?>;
<?php
$a = $_SESSION['vrDok'];
echo("alert($a);");
?>
$.ajax({
type: "POST",
url: "../Php/Dokument/IzborRobe.php",
data: {vrDok: vrdok, brDok: brdok},
success: function(returnedData)
{
document.getElementById('Content').innerHTML = returnedData;
}
})
}
So when i load page and press button i run PregledDokumenta(id) function. In there i pass some values from id of element and then i echo back some other text and buttons as you can see i alert $_SESSION['vrDok'] to see if it is assigned and it returns value. Then when i click button (about 10 sec after running first function) that i echoed back from first function i run second UnosNoveStavke function. There you can see I again alert to see if $_SESSION return value but it return undefined. Why is that happening?
You are very confused regarding how JavaScript and PHP communicate with each other!
For example, with the following code, you are effectively trying to assign JavaScript variables, which you get from an AJAX request, into PHP sections:
<?php
$_SESSION['vrDok'] = vrdok;
$_SESSION['brDok'] = brdok;
?>
This can't work, because all PHP expressions are evaluated before the page even loads.
If you need to save these values in PHP sessions, you have to do it either in the file the AJAX request is sent, in your case Pregled.php, or a PHP file that you include in it.

Javascript Output using PHP [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to execute the below code which perfectly returns me an output from database.
<?php if(isset($_POST['submit']))
{
$email = $_POST["Email_i"];
$checkRe = mysql_query("select * from contact_form where email='$email'",$con);
if(mysql_num_rows($checkRe)>0)
{
$check = 1;
}
?>
I am trying to call a function using onSubmit event as follows;
<form action="#" method="post" name="myForm" onSubmit="return CheckForm()">
<input type="submit" name="submit">
</form>
<script type="text/javascript">
function CheckForm()
{
var calc =1;
var Checkre = "<?php
$check="";
echo $check; ?>";
if(calc == Checkre)
{
alert('phone number exists');
return false;
}
}
</script>
the above function does not set the value of $check hence not resulting into its execution.
instead of HTML FORMS, try to use and utilize jQuery AJAX.
Sample Code (where data is passed as object [or named array], dataType is declared for your api.php response, timeout is included for network error, error + success + complete functions):
$(document).ready(function(){
$("#btnSubmit").click(function(){
var x = $("#textbox").val();
$.ajax({
type: "POST",
url: "url-to-php-api",
data: { reference:x },
dataType: "HTML-or-JSON-or-JSONP",
timeout: 30000, //1 sec = 1000 ms
error: function(x, t, m) {
if (t === "timeout") {
alert("Network Connection Delayed.");
//this is for network error i.e.: connection delays
}
//and some other codes for other errors~
//error function runs when there is some error with the jQuery AJAX syntax
},
success: function(retData) {
alert("PHP RESPONSE: " + retData);
//success function runs when the js successfully communicated, passed the values to PHP, gets result and back
},
complete: function() {
alert("jQuery AJAX Function Complete.");
//complete function runs after the process is completed, regardless of being error of successful
}
});
});
});
this code is of course, as far as my personal coding is concerned

Is this piece of jquery ajax code correct?

I am making a simple web chat application using ajax,php,javascript and mysql.
What I am trying to do here is to avoid fetching the whole database after an interval of 1 sec(which is normally done in basic chat application ) but rather I want to fetch and display(by appending) also those chats which have been newly entered into the database by any user.
To implement this ,First when the user first opens the chat screen the whole database is loaded in the chat window(not shown in this code snippet),and then I am using the variable msgid to fetch the latest value of MSg_ID (which is the auto-increment primary key in my chat table) through an ajax request to the page 'Msg.php' which returns the required value of msg_id.
Now using this value of msgid and comparing it with the max value of Msg_ID every second in the database through the ajax request to the page 'Chat3.php'.
If the Max value of Msg_ID has changed the required rows are returned . After this I m updating the value of 'msgid' using the same earlier ajax request to the page 'Msg.php'
The pages Msg.php and Chat3.php are working perfectly ,as I have tested them thoroughly.
My question here is what is the problem in my code , why is not working?
Can we use an ajax request inside a ajax call back function or not?
What else can be a probable source of error?
Any input will be valuable :)
If you have any problem in understanding the code,leave a comment.
'#yyy' and '#zzz' are random div elements which i am using to test the data value of ajax callback function.
I can even post the rest of the code if it helps.
<script type"text/javascript">
$(document).ready(function() {
var dept = '<?php echo $deptId; ?>';
$.ajax({
url: 'scripts/php/Msg.php',
data: {dept:dept},
success: function(data) {
$('#yyy').html(data);//this displays the correct value
var msgid=data;
}
});
var interval = setInterval(function() {
$.ajax({
url: 'scripts/php/Chat3.php',
data: {dept:dept,msgid:msgid},
success: function(data) {
if(data!='bad'){
//$('#messages').prepend(data);
$('#zzz').html(data);//does not display any value although Chat3.php is returning the correct value.
//below ajax request to update the value of msgid
$.ajax({
url: 'scripts/php/Msg.php',
data: {dept:dept},
success: function(data) {
var msgid=data;
$('#zzz').html(data); //not displaying anything although above one is was displaying
}
});
}
}
});
}, 1000);
});
</script>
Here is my Msg.php
<?php
require '../../includes/database/connect.db.php';
function get_msg($dept){
$query= "SELECT Msg_ID,Sender, Message ,Time_stamp FROM chat WHERE Dept_ID='$dept' ORDER BY Msg_ID DESC" ;
$run=mysql_query($query);
$messages =array();
while($message=mysql_fetch_assoc($run)){
$messages[] =array('msgid'=>$message['Msg_ID'],
'sender'=>$message['Sender'],
'message'=>$message['Message'],
'time_stamp'=>$message['Time_stamp']);
}
return $messages;
}
$dept=$_GET['dept'];
$messages = get_msg($dept);
$x=count($messages);
if($x){
foreach($messages as $message) {
if($x==count($messages)){
echo $message['msgid'];
}
$x--;
}
}
?>
Here is my Chat3.php
<?php
require '../../includes/database/connect.db.php';
function get_msg($dept,$msgid){
$query1= "SELECT MAX(Msg_ID) as msg_id FROM chat" ;
$run1=mysql_query($query1);
$row = mysql_fetch_assoc($run1);
$result =$row['msg_id'];
$messages =array();
if($result>$msgid)
{
$query= "SELECT Sender, Message ,Time_stamp FROM chat WHERE Dept_ID='$dept' AND Msg_ID>'$msgid' ORDER BY Msg_ID DESC" ;
$run=mysql_query($query);
while($message=mysql_fetch_assoc($run)){
$messages[] =array('sender'=>$message['Sender'],
'message'=>$message['Message'],
'time_stamp'=>$message['Time_stamp']);
}
return $messages;
}
else
{
return $messages;
}
}
$dept=$_GET['dept'];
$msgid=$_GET['msgid'];
$messages = get_msg($dept,$msgid);
if(count($messages)){
foreach($messages as $message) {
echo '<strong>'.$message['sender'].' Sent</strong><br>';
echo $message['message'].' <i><small><div align="right">'.$message['time_stamp'].'</i></small></div>';
}
}
else {
echo 'bad';
}
?>
The problem is the msgid
In your first AJAX Request you are setting the variable var msgid=data; which is in local scope.
I think you are trying to access that variable in the second AJAX request while sending the datas
url: 'scripts/php/Chat3.php',
data: {dept:dept,msgid:msgid}, // Trying to access the local variable of previous ajax request
EDIT:
Try removing the var from var msgid=data; in your first AJAX request. Removing var will make the variable GLOBAL, Although its not good to pollute the global scope, but you can definitely try out this for the time being

How to call php function from JavaScript function? [duplicate]

This question already has answers here:
Javascript and PHP functions
(7 answers)
Closed 9 years ago.
In my index.php file, I have a php function "InsertTheRecord" which gets a parameter and insert it into the database. It return 1 if that parameter is inserted successfully otherwise 0.
I have following JavaScript function "InsertRecord" in same index.php from where I want to call php InsertTheRecord function. How can I call php function from JavaScript function?
My JavaScript function:
function InsertRecord() {
var myParameter = 40;
var result = ////call InsertTheRecord(myParameter) //I don't know how to do this?
if result == 1 { //do something}
else { //show error message}
}
php server side scripting language and javascript is client side scripting language
you can do this by ajax call(Jquery)
<div id="yourdiv"></div>
var data ="hello world";
var data2="hello all";
function run(){
$.ajax({ url: 'myscript.php',
data: {'q': data,'z':data2},
type: 'post',
success: function(output) {
alert(output);
document.getElementById("yourdiv").innerHTML += output; //add output to div
}
});
}
myscript.php
<?php
myfun();
function myfun(){
$myvar2 = $_POST['z'];
$myvar = $_POST['q']."how are you?";
echo $myvar."\n";
echo $myvar2;
}
?>
this alert "hello world how are you?"
Try
var result = <?php echo InsertTheRecord(myParameter); ?>
updated after OP's comment
$.ajax
function InsertRecord() {
$.ajax({
type: "POST",
url: "your_php_page.php",
data: "arg1=id&arg2=name",
success: function (data) {
var myParameter = 40;
var result = data;
if result == 1 {} else {}
}
});
}
PHP is serverside,
JS is clientside,
So the PHP works first, after that the JS works dynamically in the browser.
You cannot call the PHP function in runtime. But you can use AJAX which can do that. Check this out: http://www.w3schools.com/ajax/ajax_aspphp.asp
What if you echod the myParameter to a hidden input field and then grabbed it with javascript:
HTML/PHP file:
<input type="hidden" id="myParameter" value="<?php echo InsertTheRecord(myParameter); ?>"/>
In Javascript:
function InsertRecord() {
var myParameter = 40;
var result = document.getElementById("myParameter").value();
if result == 1 { //do something}
else { //show error message}
}
It is not possible
Javascript is client side scripting language where PHP is server side scripting language
But, you can try AJAX methods to get similar results where you can pass variables same as function
as function myfunction(var1, var2 ,....){return var1*var2}
using ajax, you can run a php script externally on button click
$.ajax({key:var},function(result){alert(result)});
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
http://www.tutorialspoint.com/ajax/

Categories