My update with php and jQuery Ajax its not working - php

I have this "Read More" link:
echo '<p>'.$readNewsResult['content'].'<a class="test" href="#fancybox'.$readNewsResult['id_news'].'">Read More</a></p>';
When I click in this link, my goal is to update views column of my news table.
So I have a jQuery where Im passing id of my news, and it is working fine, when I click on "Read more" link I get an alert message saying: "action=update&update=311", where 311 is id of my clicked news.
My jQuery until now:
$(function(){
var read = $('.news');
read.on('click','.test',function(){
var updateid = $(this).attr("id");
var updatedata = "action=update&update="+updateid;
alert(updatedata);
$.ajax({
data: updatedata,
beforesend: '',
error: '',
success: function(updateR)
{
alert(updateR);
}
});
});
});
But now with php, Im trying to get update action and id, and do update on my news table, but its not working, because it seems that I never enter in my switch condition.
I tried to give some "echos" inside my case, and when I click on my "Read more" link my echo never appears.
Do you see where might be the problem??
$action = $_POST['action'];
switch($action)
{
case 'update':
$id = $_POST['id'];
$updateViews = $pdo->prepare("UPDATE news SET views=:views WHERE id=:id");
$updateViews->bindValue(':views', '1');
$updateViews->bindValue(':id', $id);
$updateViews->execute();
break;
}

At the very least you are trying to work with $_POST['id'] in your PHP but you are actually creating an URL parameter called update which contains the ID in your JavaScript.
The actual issue is that you are lacking an URL argument to your $.ajax call.
You are also naming your var udpdatedata on this line:
var udpdatedata = "action=update&update="+updateid;
but are referencing updatedata in the $.ajax call:
data: updatedata,
As such your query parameters are never added to the non-existent URL.
An extra one:
sucess: function(updateR)
Is actually spelled success, note the double c.

Where is your ajax controller url, I mean url and also type of call type,
$.ajax({
type: 'POST',
url: '/url/myphpfunction',
data: updatedata,
beforesend: '',
error: '',
sucess: function(updateR)
{
alert(updateR);
}
});
Here is the tutorial http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php

You had a few things wrong with your ajax function. The first was that you should be passing through an object of values instead of a string. Then you need to specify a method of getting to your script. Then you need to set the URL to your script. See the comments below:
$(function(){
var read = $('.news');
read.on('click','.test',function(){
var updateid = $(this).attr("id");
// pass data as a JS object
var udpdatedata = {action:'update', update:updateid};
alert(udpdatedata);
$.ajax({
// set the method to post
type: "POST",
// the URL to your PHP script
url: "pathtoscript/script.php"
data: updatedata,
beforesend: '',
error: '',
success: function(updateR)
{
alert(updateR);
}
});
});
});
Your PHP also had an error, you're passing through 'update', not 'id':
$action = $_POST['action'];
switch($action)
{
case 'update':
// you're passing through 'update', not 'id'
$id = $_POST['update'];
$updateViews = $pdo->prepare("UPDATE news SET views=:views WHERE id=:id");
$updateViews->bindValue(':views', '1');
$updateViews->bindValue(':id', $id);
$updateViews->execute();
break;
}

Related

AJAX request delete column base on their id.

Good day. I'm working on a admin page basically it is a content management system. I want to delete the data based on their id. But unfortunately i've encounter a error on the htpp request. here is the error.
Request URL: admin/ajax_delete
Request Method:POST
Status Code:500 Internal Server Error
Remote Address:144.76.136.165:8181
VIEW FILE:
<span class="glyphicon glyphicon-trash"></span>
$("#delete_tpi").click(function() {
alert("Are you sure you want to delete?");
var tpi = $('.datatpi').val(); //package includes
var did = $('#data-id').val();
$.ajax({
url: '<?php echo site_url('admin/ajax_delete'); ?>',
type: 'POST',
datatype: 'html',
data: {id: did, tpi: tpi},
success:function (b){
if (b == 'Success') {
$('.#data-id').val('');
$('.datatpi').val('');
location.reload();
}
}
});
});
$('body').on('click','.edit-content-modal',function(){
var id = $(this).attr('data-id');
$('#data-id').val(id);
});
Controller file:
public function ajax_delete(){
$did = $this->input->post('id');
$ptpi = $this->input->post('tpi');
$update = $this->products_model->row_delete($did,$ptpi);
var_dump($update);
echo ($update)?'Success':'Fail';
}
MODEL FILE:
function ajax_delete($did,$ptpi){
$this->db->where('id',$did);
$this->db->delete('products',$ptpi);
return $this->db->affected_rows() > 0;
}
Because <a></a> element does not expect a value tag. You can get the ID of the clicked #delete_tpi link by using attr():
var did = $("#delete_tpi").attr('data-id');
Your POST request to admin/ajax_delete returns 500 Internal Server Error. This is a server-side error. If you use codeigniter, take a look at application/logs/*.log files that will give you detail information about the error.
I think, your problem is calling a non-existing function from model:
In your controller, you have:
$this->products_model->row_delete($did,$ptpi);
But your model, contains:
function ajax_delete($did,$ptpi){
....
}
Do you have row_delete() function in your model?
Once again, i suggest you to look at logs file, because many problems can result in server-side error.

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.

Form submission using ajax and page view moderation after the submission

At this moment I am using laravel. In this context I am having a form which is successfully submitted by using ajax to a controller. and that controller make it to the database. But the problem is as the ajax is doing its job the whole page remain unmoved / unchanged after the submission even the database is updated.
Now what I want
I want to give feedback to the user that your post is successfully submitted there. or what I want to do in further, I want to refresh the section in which the post is collected from the database as this post can be retrieved from there. But by using ajax only.
So there is no need to collect the whole page or refresh.
here is my form structure
`
{{ Form::open(array('route' => array('questions.store'), 'class' => 'form-horizontal' )) }}
blah blah blaaa .......
<script type="text/javascript">
$(".form-horizontal").submit(function(e){
$(this).unbind("submit")
$("#ask").attr("disabled", "disabled")
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
</script>
{{ Form::close() }}
`
As it is very much visible that the post is updated through a route & controller I want to have another dive and a success message at this script to be displayed after the success of posting. I am looking for some professional structure using what there is minimal need to have interaction with the server side and give user a better page viewing experience.
Thanks a lot for helping me in this research.
I am not sure if I understand you well, but if you want to notify the user about the result of an ajax-called db update you need to have
a route for the ajax save db call - it should point to a method that does the db update.
the db update method should return some value indicating the success/failure of update (for example OK or FAIL)
the only result of calling the method will be just plain text page with OK or FAIL as body
fetch the result by ajax and inform user accordingly (after form submit button)
check out the below code for ajax call itself (inside the form submit handler) to see what I mean
var db_ajax_handler = "URL_TO_YOUR_SITE_AND_ROUTE";
var $id = 1; //some id of post to update
var $content = "blablabla" //the cotent to update
$.ajax({
cache: false,
timeout: 10000,
type: 'POST',
tryCount : 0,
retryLimit : 3,
url: db_ajax_handler,
data: { content: $content, id: $id }, /* best to give a CSRF security token here as well */
beforeSend:function(){
},
success:function(data, textStatus, xhr){
if(data == "OK")
{
$('div.result').html('The new Question has been created');
}
else
{
$('div.result').html('Sorry, the new Question has not been created');
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
alert("Error 500: "+xhr.status+": "+xhr.statusText);
} else {
alert("Error: "+xhr.status+": "+xhr.statusText);
}
},
complete : function(xhr, textStatus) {
}
});
EDIT: as per comment, in step 2 (the method that is called with AJAX) replace
if($s)
{
return Redirect::route('questions.index') ->with('flash', 'The new Question has been created');
}
with
return ($s) ? Response::make("OK") : Response::make("FAIL");
EDIT 2:
To pass validation errors to the ajax-returned-results, you cannot use
return Response::make("FAIL")
->withInput()
->withErrors($s->errors());
as in your GIST. Instead you have to modify the suggested solution to work on JSON response instead of a plain text OK/FAIL. That way you can include the errors in the response and still benefit from the AJAX call (not having to refresh the page to retrieve the $errors from session). Check this post on the Laravel Forum for a working solution - you will get the idea and be able to fix your code.

Ajax update table with php content

How to make an animated table only animate when a new record is added to the database.
Ajax/Js (in index.php):
$.ajax({
url : 'Not sure what goes here?',
data : {Not sure what goes here?},
dataType : 'application/json', // Is this correct?
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
var newitem = function(response){
var item = $('<div>')
.addClass('item')
.css('display','none')
.text(response)
.prependTo('#scroller')
.slideDown();
$('#scroller .item:last').animate({height:'0px'},function(){
$(this).remove();
});
}
My php (latest.php):
include ('db.php');
$sql2 = "SELECT * FROM `feed` ORDER BY `timez` DESC";
$res2 = mysql_query($sql2) or die(mysql_error());
while($row3 = mysql_fetch_assoc($res2)){
$user = $row3['username1'];
$action = $row3['action'];
$user2 = $row3['username2'];
echo ''.$user.''.$action.''.$user2.'<br>'; // Needs to be a json array?
I can't get this to work, here's how the table operates http://jsfiddle.net/8ND53/ Thanks.
$.ajax({
url : your_php_file.php',
data : {data you'r going to send to server}, // example: data: {input:yourdata}
success: function(response) {
$('#table_id').append('<tr>'+response+'</tr>'); // response is the date you just inserted into db
}
});
in your_php_file.php:
add the item into db
echo that inserted data # if you echo, then you can catch this with ajax success function then you append it into your table.
try to fill as below:
$.ajax({
type: "post"
url : 'locationOfphpCode/phpCode.php',
data : {data you want to pass}, //{name: "dan"}
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
in your php code you need to receive the data you have passed from the ajax call:
<?php
$name = $_POST['name'];
...
?>
you may add some validations in your php code.
hope this will help you.
the example you have given is using setInterval(newitem, 2000)
so you have to call ajax function on some fixed interval.

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