JQuery Ajax not updating record - php

I have some jquery ajax code to update a record but it's not working as expected.
Here is the code:
function update_records() {
$.ajax({
type: "POST", // Set the type then $_GET['id'] or $_POST['id']
url: "update_record.php",
data: { category: "John", image: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}; //end function
Then the php
<?php
$id = $_REQUEST['id'];
include 'config.php';
$result = mysql_query("UPDATE mytable SET title = 'something' where id=$id");
$result = mysql_query("SELECT * FROM mytable WHERE id = '$id'");
$array = mysql_fetch_row($result);
?>

Example from jQuery.com
http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST", // Set the type then $_GET['id'] or $_POST['id']
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
I can't understand what your query returns.
Maybe you need to select where id = $id;
// $id = $_POST['id'] or $_GET['id'] Where is $id???
$result = mysql_query("UPDATE mytable SET title = 'something' where id=$id");
$result = mysql_query("SELECT * FROM mytable WHERE id = '$id'");
$array = mysql_fetch_row($result);
//You can use mysql_error() function to see the error.
$result = mysql_query("UPDATE mytable SET title = 'something' where id=$id") or die(mysql_error());

I see you have:
$result = mysql_query("UPDATE mytable SET title = 'something' where id=$id");
I don't see where you take the value of $id

u need
$id = $_REQUEST['id'];
I think you forgot to include this line before executing the update query.

Related

How do I send data via AJAX?

I'm working on a social site. When I click the like button it runs the php page called "like.php", and inserts data into the data base BUT it is not receiving the post id, yet it will console log the post id from the jQuery.
here is my jQuery:
<script>
$(document).on('click', '.like_button', function() {
var postId = $(this).data('post-id');
console.log(postId);
$.ajax({
url: 'db/like.php',
type: 'POST',
data: { post_id: postId },
success: function(data) {
$('.like_count[data-post-id="' + postId + '"]').text(data);
console.log(data);
}
})
})
</script>
And here is my PHP:
<?php
session_start();
include("db.php");
$post_id = $_POST['post_id'];
$date = time();
// Get Current Post Likes
$sql = "select * from posts where id = '$post_id'";
$result = mysqli_query($conn, $sql);
$curr_likes = mysqli_fetch_assoc($result);
$new_likes = $curr_likes['likes'] + 1;
// Insert Into Likes table
$sql2 = "insert into likes (userid, postid, date) values ('$_SESSION[id]', '$post_id', '$date')";
mysqli_query($conn, $sql2);
if(isset($post_id)) {
echo "SET";
}else{
echo "NOT SET";
}
From the php page I'm getting "NOT SET"

ajax run mysql query and check whether mysql query was true or false?

I am using the following ajax script to run my MySQL query and then only want the jquery to fade out my div and fade in another if the query returned true otherwise if the query returned false don't do anything.
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "include/fade_to_do_list.php",
data: "theOption=" + $(this).attr("id"),
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("success") >-1 ){
setTimeout(
function() {
$("#to_do_list").fadeOut();
}, 3500
);
setTimeout(
function() {
$("#compliance_list").fadeIn();
}, 500
);
}
}
});
});
</script>
PHP/MYSQL:
<?php
session_start();
include 'config.php';
$query = "SELECT * FROM supplier_stats WHERE complete_count = > 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
if(mysql_num_rows($result)>0) {
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
if($result2) {
$return['res'] = 'success';
} else {
}
}
echo json_encode($return);
?>
Please can someone show me where I am going wrong? I currently get no error and my jquery just doesnt execute. Thanks
mysql_query() always return you something. You need to count number of affected row.
Also problem is with equal to greater then operator it is used as >=
$query = "SELECT * FROM supplier_stats WHERE complete_count >= 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
$total=mysql_affected_rows();
if($total >0) {
$return['res'] = 'success';
} else {
}

ajax send data not working

I tried using ajax to send data from onclick event on image
This is the ajax code
function get_img(name) {
$.ajax({
type: "POST",
url: "img_main.php",
data: "img_name="+name,
success: function(response)
{
alert("main image selected");
}
});
}
This is the img tag where I put the onclick event
while($row = mysql_fetch_array($query))
{
$test = $row['img_name'];
$result .= "<td><img src='".$uploaddir.$row['img_name']."' class='imgList' onclick='get_img(\"".$test."\")' /></td>";
This is the img_main.php
<?php
include("connect.inc.php");
echo "<script type='text/javascript'> alert('test'); </script>";
$img_name = $_POST['img_name'];
$query = "UPDATE upload set status = 1 where img_name = $img_name";
$result = mysql_query($query);
$query2 = "UPDATE upload set status = 0 where img_name != $img_name";
$result2 = mysql_query($query2);
?>
What I want is when I clicked on the image, it update the field status on the database.
The success function in the ajax code give me the alert function but the status field is not updated.
My console returns no error.
Can somebody please help?
try change
data: "img_name="+name,
to
data: {img_name:name},
or
$.ajax({
type: "POST",
url: "img_main.php", or use full url like "http://domain/img_main.php"
data: {img_name:name},
success: function(response)
{
alert("main image selected");
}
});
and img_main.php (add quotes to your query variable)
$query = "UPDATE upload set status = 1 where img_name = '$img_name'";
$result = mysql_query($query);
$query2 = "UPDATE upload set status = 0 where img_name != '$img_name'";
$result2 = mysql_query($query2);
Add quotes to $img_name in the update queries like:
$query = "UPDATE upload set status = 1 where img_name='$img_name'";
$result = mysql_query($query);
$query2 = "UPDATE upload set status = 0 where img_name!='$img_name'";
As you are getting alert as response, I don't think that there is error in ajax call.

Get url parameter and query mysql data with ajax

I want to get a parameter from an url. The url looks like this:
www.example.com/?v=12345
I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){
alert("error occurred");
}
});
As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
<?php
// Connection stuff right here
$myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
echo json_encode($array);
}
?>
The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!
You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Getting the parameter-
v = query_string('v'); // Will return '12345' if url is www.example.com/?v=12345
This needs to be passed as data in the AJAX call.
$.ajax(
{
type: "POST",
dataType: "json",
url: "ajax2.php",
data: "v="+v,
success: function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error: function(jqXHR,textStatus,errorThrown){
//alert(JSON.stringify(jqXHR));
//alert(textStatus);
//alert(errorThrown);
alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
//alert("error occurred");
}
}
);
This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...
And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);
If there is a database error, then it has to be handled.
So do this -
<?php
// Connection stuff right here
header("Content-Type: application/json");
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
$result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
}
echo json_encode($array);
}else{
echo json_encode(Array("error": "No POST values"));
}
?>
So this way, if the query has not executed properly, then you will know what exactly the error is.
Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];

How to Retrieve Values Resulting From AJAX Live Search?

Below is a jQuery function that retrieves 2 textbox values and posts them to another file ("Student Search Results.php"), where a live search is run using the values.
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = Team_Name + '?????' + Teacher;
$.ajax({
type: "POST",
url: "Student Search Results.php",
data: {
query: Search_Data
},
cache: false,
success: function() {
alert('The values were sent');
}
});
});
</script>
Below is the PHP script on the search page ("Student Search Results.php") that makes use of these values.
<?php
include "Connection.php";
if(isset($_POST['query'])){
$searchData = explode('?????', $_POST['query']);
$teamName = $searchData[0];
$teacher = $searchData[1];
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
echo $query;
?>
How would I be able to take variables from the PHP script (such as $result) to the first page, so I can create a result table? Simply including the PHP file does not work, as the file is only included once.
Thank you for your time.
Best option is to serialize to JSON using json_encode
I think best you can do is,
success: function(result) {
alert(result);
}
and Student Search Results.php print result in tabular format.
P.S. : Please follow proper file naming convention
use a proper URL, and send the data (and stop using camelcase for everything) :
$(".search").on('keyup', function() {
var data = {
team_name : $('#TeamName').val(),
teacher : $('#Teacher').val()
}
$.ajax({
type: "POST",
url: "student_search_results.php",
data: data,
cache: false
}).done(function(result) {
console.log(result);
});
});
And in PHP, you have to actually get the result into an array and json_encode it :
<?php
include "Connection.php";
$team_name = !empty( $_POST['team_name'] ) ? $_POST['team_name'] : null;
$teacher = !empty( $_POST['teacher'] ) ? $_POST['teacher'] : null;
if ($team_name && $teacher) {
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );
?>
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = "Team_Name="+'Team_Name'&Teacher='+Teacher;
$.ajax({
type: "POST",
url: "Student_Search_Results.php",
data: Search_Data,
cache: false,
success: function(result) {
$('$output').html(result);
}
});
});
</script>
Here is output div
<div id="output"></div>
On Student_Search_Results.php page get
$tname = $_POST['Team_Name'];
$teacher = $_POST['Teacher'];
//your search query & print data

Categories