jQuery ajax call won't update mysql after pressing back button - php

I have a form that uses ajax to submit data to a mysql database, then sends the form on to PayPal.
However, after submitting, if I click the back button on my browser, change some fields, and then submit the form again, the mysql data isn't updated, nor is a new entry created.
Here's my Jquery:
$j(".submit").click(function() {
var hasError = false;
var order_id = $j('input[name="custom"]').val();
var order_amount = $j('input[name="amount"]').val();
var service_type = $j('input[name="item_name"]').val();
var order_to = $j('input[name="to"]').val();
var order_from = $j('input[name="from"]').val();
var order_message = $j('textarea#message').val();
if(hasError == false) {
var dataString = 'order_id='+ order_id + '&order_amount=' + order_amount + '&service_type=' + service_type + '&order_to=' + order_to + '&order_from=' + order_from + '&order_message=' + order_message;
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php", data: dataString, success: function() { } });
} else {
return false;
}
});
Here's what my PHP script looks like:
<?php
// Make a MySQL Connection
include('dbconnect.php');
// Get data
$order_id = $_GET['order_id'];
$amount = $_GET['order_amount'];
$type = $_GET['service_type'];
$to = $_GET['order_to'];
$from = $_GET['order_from'];
$message = $_GET['order_message'];
// Insert a row of information into the table
mysql_query("REPLACE INTO gift_certificates (order_id, order_type, amount, order_to, order_from, order_message) VALUES('$order_id', '$type', '$amount', '$to', '$from', '$message')");
mysql_close();
?>
Any ideas?

You really should be using POST instead of GET, but regardless, I would check the following:
That jQuery is executing the ajax call after you click back and change the information, you should probably put either a console.log or an alert calls to see if javascript is failing
Add some echos in the PHP and some exits and go line by line and see how far it gets. Since you have it as a get, you can just load up another tab in your browser and change the information you need to.
if $j in your jQuery is the form you should be able to just do $j.serialize(), it's a handy function to get all the form data in one string

Mate,
Have you enclosed your jquery in
$j(function(){
});
To make sure it is only executed when the dom is ready?
Also, I'm assuming that you've manually gone and renamed jquery from "$" to "$j" to prevent namespace conflicts. If that isn't the case it should be $(function and not $j(function
Anyway apart from that, here are some tips for your code:
Step 1: rename all the "name" fields to be the name you want them to be in your "dataString" object. For example change input[name=from] to have the name "order_from"
Step 2:
Use this code.
$j(function(){
$j(".submit").click(function() {
var hasError = false;
if(hasError == false) {
var dataString = $j('form').serialize();
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php?uu="+Math.random(), data: dataString, success: function() { } });
} else {
return false;
}
});
});
You'll notice i slapped a random variable "uu=random" on the url, this is generally a built in function to jquery, but to make sure it isn't caching the response you can force it using this method.
good luck. If that doesn't work, try the script without renaming jquery on a fresh page. See if that works, you might have some collisions between that and other scripts on the page

Turns out the problem is due to the fact that I am using iframes. I was able to fix the problem by making the page without iframes. Thanks for your help all!

Related

Display POST data in HTML element

I need some example to display POST data inside HTML DIV element. Like this: Beeceptor
I make an example using PHP and jQuery.
It works fine but I don't know if there a better solution instead of using SESSIONS and interval function?
The POST data is made by using an external program (not by jQuery itself).
PHP
session_id('13245');
session_start();
$session_id = session_id();
if($data['payload'] !== null)
{
$_SESSION['payload'] = $data['payload'];
$_SESSION['timestamp'] = microtime();
}
else
{
$_SESSION['payload'] = $_SESSION['payload'];
$_SESSION['timestamp'] = $_SESSION['timestamp'];
}
echo json_encode(array('timestamp' => $_SESSION['timestamp'], 'payload' => $_SESSION['payload']));
?>
jQuery
$(document).ready(function () {
var oldTimeStamp = 0;
setInterval(function()
{
$.ajax({
type:"post",
url:"post.php",
datatype:"json",
success:function(data)
{
var obj = jQuery.parseJSON(data)
if(oldTimeStamp != obj.timestamp)
{
oldTimeStamp = obj.timestamp;
$('#displayData').append('timestamp: ' + obj.timestamp);
$('#displayData').append(' rawPayload: ' + obj.payload);
$('#displayData').append('<br />');
}
}
});
}, 1000);//time in milliseconds
});
Any help will be greatly appreciated.
you can go for "then()" or "done()", immediate after finishing ajax call. here is the sample:
$.ajax({
type:"post",
url:"post.php",
datatype:"json",
success:function(data)
{...}
}).then(function (data){
var obj = jQuery.parseJSON(data)
if(oldTimeStamp != obj.timestamp)
{
oldTimeStamp = obj.timestamp;
$('#displayData').append('timestamp: ' + obj.timestamp);
$('#displayData').append(' rawPayload: ' + obj.payload);
$('#displayData').append('<br />');
}
});
You are trying to make a real-time application such as chatting and real-time visualizations. In order to achive this I suggest you to write with NodeJs SOCKET.IO
If you use PHP it will make your server lode more harder than JavaScript programs like socket.io.
Your Question:
It works fine but I don't know if there a better solution instead of using SESSIONS and interval function?
Answer:
Definitely it's a bad practice which trigger the server every seconds even there are no new updates. Let's assume you have 100 users online at the same time so your server will be called 100 times every second which is really a more load to the server.
Example:
https://socket.io/get-started/chat

Multiple Ajax call with same JSON data key calling one php file

I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)

php MVC jquery ajax

Im beginner and have just simple PHP MVC for JQUERY SPA, and just wonnt to use Jquery Ajax to
index.php, like front controller calling RouterControler and class AjaxKontroler with registruj() method...using user model to add new user to MySQL..
class AjaxKontroler
{
public function registrovat()
{
if ($_POST)
{
try
{
$spravceUzivatelu = new SpravceUzivatelu();
$spravceUzivatelu->registruj($_POST['email'],$_POST['heslo'],$_POST['hesloZnovu'],$_POST['jmeno'],$_POST['prijmeni'],$_POST['telefon'],$_POST['ulice'],$_POST['mesto'],$_POST['psc'],$_POST['captcha']);
$spravceUzivatelu->prihlas($_POST['email'], $_POST['heslo']);
}
catch (ChybaUzivatele $chyba)
{
$this->pridejZpravu($chyba->getMessage());
}
}
echo "Registrace proběhla úspěšně";
}
Singup form:
$("#dokoncitregistraci").click(function () {
var email = $("#emailreg").val();
var heslo = $("#hesloreg").val();
var hesloznovu = $("#hesloznovureg").val();
var jmeno = $("#jmenoreg").val();
var prijmeni = $("#prijmenireg").val();
var telefon = $("#telefonreg").val();
var ulice = $("#ulicereg").val();
var mesto = $("#mestoreg").val();
var psc = $("#pscreg").val();
var captcha = $("#captcha").val();
console.log("jedu");
$.ajax({
type: "POST",
url: "../ajax/registrovat",
data: {
"email" : email,
"heslo": heslo,
"hesloznovu" : hesloznovu,
"jmeno" :jmeno ,
"prijmeni":prijmeni,
"telefon":telefon,
"ulice":ulice,
"mesto" :mesto,
"psc" : psc,
"captcha" :captcha
},
dataType: "JSON",
success: function(msg){
alert("msg");
}
But all signup inputs are correctly add ti MySQL like new row. I have no success response to work with. Are there some trick to use success response in MVC?
Browser just doesn't make any JS alert(). Sorry abeout using StackOwerflow, its my first question here ane no best practise for it:)
Your code looks fine overall. As far as I know, you don't need the double quotes in "email":email. It can be email:email, but that shouldn't be the problem.
My instinct tells me to double check your ajax url:. Relative urls are tricky, as you have to make them relative to the page running the execution, not what the browser shows. I'd switch to absolute urls like http://www.example.com/ajax/registrovat/ until you are certain what the problem is. The last slash after registrovat is important for differentiating between a controller name and a value.
You can also add an error: function() {} to get more information about what is going on.

How to reset ckeditor save event

On a previous ajax call I get all articles for a selected Page.
Then I display them and bind this function - on click - to each of them. This is working only one time.
When I want to change a second or third article the article id inside the ajax call keeps holding its first value.
CKEDITOR.replace( 'editor1' );
function editArticle(article){
// id changes for each article as it is supposed to
var id = article.attr('data-id');
var text = article.html();
$('#ckModal').modal();
$('.modal-title').text('Editing Article: '+id+' on Page: '+pageTitle);
CKEDITOR.instances.editor1.setData(text);
CKEDITOR.instances.editor1.resize('100%', '350', true);
CKEDITOR.instances.editor1.on('save', function(e){
e.cancel();
var html = CKEDITOR.instances.editor1.getData();
if(html){
$.ajax({
type: 'POST',
url: '/admin/nodes/edit',
cache: false,
data: {'html' : html,
'articleId' : id }
}).done(function(msg){
// next two lines did not work
//CKEDITOR.instances.editor1.fire('save');
//CKEDITOR.instances.editor1.stop('save');
// id stays the same
console.log(id);
// I echo an 'ok' string when update worked from php
if(msg === 'ok'){
article.html(html);
$('#ckModal').modal('hide');
}else{
//alert(msg);
}
}).fail(function(xhr, status, error){
console.log(JSON.stringify(xhr));
console.log("AJAX error: " + status + ' : ' + error);
});
}
});
}
I had to cancel the save event to get and set Data and perform the ajax call.
But how do I restart or reset the 'save' event - if this is what is causing the problem. I am not so shure anymore ....
Got it working by destroying editor instance in ajax done function and creating a new one after it.
function editArticle(article){
var id = article.attr('data-id');
var text = article.html();
//CKEDITOR.replace( 'editor1' );
$('#ckModal').modal();
$('.modal-title').text('Editing Article: '+id+' on Page: '+pageTitle);
CKEDITOR.instances.editor1.setData(text);
CKEDITOR.instances.editor1.resize('100%', '350', true);
CKEDITOR.instances.editor1.on('save', function(e){
e.cancel();
var html = CKEDITOR.instances.editor1.getData();
if(html){
var title = $('.modal-title').html()
$('.modal-title').prepend(spinner);
$.ajax({
type: 'POST',
url: '/admin/nodes/edit',
cache: false,
data: {'html' : html,
'articleId' : id }
}).done(function(msg){
//console.log(id);
$('.modal-title').html(title);
if(msg === 'ok'){
article.html(html);
$('#ckModal').modal('hide');
CKEDITOR.instances.editor1.destroy();
CKEDITOR.replace( 'editor1' );
}else{
//alert(msg);
}
}).fail(function(xhr, status, error){
console.log(JSON.stringify(xhr));
console.log("AJAX error: " + status + ' : ' + error);
});
}
});
}
You are assigning multiple event listeners on your editor instance 'editor1', one for each article. What happens is when you click save, the first listener (the first article assigned) called cancels all others with e.cancel().
I see you achieved what you wanted by destroying your editor. Doing this removes event listeners, and solves your problem. You could achieve the same with calling e.removeListener() in the handler, this way removing itself after the first run and avoiding the need to recreate the editor. Also note that destroying editors and recreating them is leaking memory (some versions worse than others #13123, #12307), so one should probably avoid doing that if possible.
Both solutions make the save button unusable after a save; of course it will work after another article is chosen for editing. So my suggestion is to remove all previous listeners from your save command before assigning a new one, like this:
// ... in function editArticle ...
CKEDITOR.instances.editor1.resize('100%', '350', true);
CKEDITOR.instances.editor1.getCommand('save').removeAllListeners();
CKEDITOR.instances.editor1.on('save', function(e){
// ...

Load only new data with ajax

I need to load only new data into my div with ajax. At the moment I'm currently loading all data, because if I delete a record in the database it also removes it from my chat div.
Here is my js code:
var chat = {}
chat.fetchMessages = function () {
$.ajax({
url: '/ajax/client.php',
type: 'post',
data: { method: 'fetch', thread: thread},
success: function(data) {
$('.chat_window').html(data);
}
});
}
chat.throwMessage = function (message) {
if ($.trim(message).length != 0) {
$.ajax({
url: '/ajax/client.php',
type: 'post',
data: { method: 'throw', message: message, thread: thread},
success: function(data) {
chat.fetchMessages();
chat.entry.val('');
}
});
}
}
chat.entry = $('.entry');
chat.entry.bind('keydown', function(e) {
if(e.keyCode == 13) {
if($(this).val() == ''){
} else {
chat.throwMessage($(this).val());
e.preventDefault();
}
}
});
chat.interval = setInterval(chat.fetchMessages, 8000);
chat.fetchMessages();
I have had a look around and some say that if you pass a timestamp to the server and load new content that way, but I can't seem to get my head around that. If you need php let me know.
Right, so the timestamp thing makes the most sense. You'll need to do a few things:
On the back end, you need to make client.php accept a timestamp parameter in the querystring. When returning data, instead of just returning all of it, make it return everything since the time stamp, if given. Otherwise return everything.
The very first time you load the chat client, the first thing you should do is make an Ajax call to a new PHP file that returns the current server timestamp. Store the value of that in a Javascript variable as a Number.
During chat.fetchMessages(), increment the value of the timestamp variable by however long it's been since the last fetch (looks like 8000 milliseconds), and feed that to client.php, like url: '/ajax/client.php?timestamp=' + latestFetchTimestamp,
Instead of replacing all HTML content, append instead.

Categories