php MVC jquery ajax - php

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.

Related

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 :-)

How to post more than 1 var’s with ajax

I've been googling for a way to do this but everything I have found doesn't help me.
I'm not sure how to post all the below variables, If I select only one of them it'll post just fine as well as putting it into the correct database column.
any help would be much appreciated.
function submit() {
var mm10 = $('#10MM'),
mm16 = $('#16MM'),
mm7 = $('#7MM'),
mm2 = $('#2MM'),
fines = $('#Fines'),
bark = $('#Bark'),
cqi = $('#CQI');
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: ,
success: function(){
$("#successMessage").show();
}
});
};
You can do it in two ways. One using arrays, or two using objects:
function submit() {
var mm10 = $('#10MM').val(),
mm16 = $('#16MM').val(),
mm7 = $('#7MM').val(),
mm2 = $('#2MM').val(),
fines = $('#Fines').val(),
bark = $('#Bark').val(),
cqi = $('#CQI').val();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: [mm10, mm16, mm7, mm2, fines, bark, cqi],
success: function() {
$("#successMessage").show();
}
});
} // Also you don't need a semicolon here.
Also you don't need a semicolon at the end of the function.
Using arrays is easier, if you want more precision, use objects:
function submit() {
var mm10 = $('#10MM').val(),
mm16 = $('#16MM').val(),
mm7 = $('#7MM').val(),
mm2 = $('#2MM').val(),
fines = $('#Fines').val(),
bark = $('#Bark').val(),
cqi = $('#CQI').val();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: {
"mm10": mm10,
"mm16": mm16,
"mm7": mm7,
"mm2": mm2,
"fines": fines,
"bark": bark,
"cqi": cqi
},
success: function() {
$("#successMessage").show();
}
});
} // Also you don't need a semicolon here.
And in the server side, you can get them through the $_POST super-global. Use var_dump($_POST) to find out what has it got.
Kind of like Praveen Kumar suggested, you can create an object. One thing I was curious about, it looks like you're passing jQuery objects as your data? If that's the case, $_POST is going to say something like [object][Object] or, for me it throws TypeError and breaks everything.
var form_data = {};
form_data.mm10 = $('#10MM').val(); // Input from a form
form_data.mm16 = $('#16MM').val(); // Input from a form
form_data.mm7 = $('#7MM').val(); // Input from a form
form_data.mm2 = $('#2MM').text(); // Text from a div
form_data.fines = $('#Fines').text();
form_data.bark = $('#Bark').text();
form_data.cqi = $('#CQI').text();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: form_data,
success: function() {
alert('success');
}
});
}
Then to get those values in your PHP you'd use:
$_POST[mm10] // This contains '10MM' or the value from that input field
$_POST[mm16] // This contains '16MM' or the value from that input field
$_POST[mm7] // This contains '7MM' or the value from that input field
$_POST[mm2] // This contains '2MM' or the value from that input field
And so on...
I tried to put together a jsFiddle for you, though it doesn't show the PHP portion. After you click submit view the console to see the data posted.

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.

jquery.ajax with php

I have just started working on php. It's a very good lang as I'm feeling but some point I get stuck as I'm new to this.
My javascript code
var pv = $("#txtStart").val();
var av = $("#txtStartNextLevel").val();
var au = $("#fileStartPlay").val();
alert(pv+" "+av+" "+au);
var myau = au.split('\\');
$.ajax({
type:"POST",
url:php_url,
data:"{startPoint:"+pv+"nextLevelPoint:"+av+"audioFile:"+myau[myau.length-1]+"}",
contentType:"application/json",
dataType:"json",
success:function(){
alert("done");
},
error:function(){
alert(response);
}
});
My PHP code.
<?php
if(file_exists("Text.txt"))
{
$fileName = "Text.txt";
$fh = fopen($fileName,"a")
$Starts = $_POST["startPoint"];
$NextLevel = $_POST["nextLevelPoint"];
$AudioFileName = $_POST["audioFile"];
$code .=$Starts."*".$NextLevel."_1*".$AudioFileName."\"";
fwrite($fh,$code);
fclose($fh);
}
?>
When I run this it executes but doesn't write the values in the variable
$Starts,$NextLevel,$AudioFileName**.
And further if I write the same ajax procedure in
$.post(php_url,{startPoint:pv,nextLevelPoint:av,audioFile:myau[myau.length-1]},function(data){});
this works fine and write the content in the file.
Also As I'm using post method it should not display the values in Address bar what I'm passing to write. But it's showing those values in both the method.
localhost://myphp.php?txtStart=Start&fileStartPlay=aceduos.jpg&txtStartNextLevel=adfd
Please guide me where I'm lacking...
Replace the value bellow (with quotas)
"{startPoint:"+pv+"nextLevelPoint:"+av+"audioFile:"+myau[myau.length-1]+"}"
to
{startPoint:pv, nextLevelPoint: av, audioFile: myau[myau.length-1]}
Do what Burak TAMTURK said, and also get rid of
contentType:"application/json",
$_POST data should be in content-type application/x-www-form-urlencoded, which is the default.

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

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!

Categories