Pass string through Jquery and ajax to PHP - javascript

I've been struggeling with this problem for a while now and I still can't understand why it's not working. I've tried multiple possibilites but none of them worked, so can someone please help me with how to pass var superstr = $( "#savelyric" ).text(); through Ajax and into my database? This is what I've been experimenting with:
function saveinPHP() {
//alert("Came here");
var lyr = $( "#savelyric" ).text();
var superstr = { lyricsave:lyr }
//var superstr = 'lol';
//var hashString = "lol";
//var data = { yoururl:'hmm'}
$.ajax({
type: "POST",
url: "includes/sendlyrics.php",
data: superstr,
success: function(data){
alert("***DATA***"+data+"***MSG***");
alert("Settings has been updated successfully." + data + "~~~" + hashString);
//window.location.reload(true);
}
});
}
And as you can see, I've tried with multiple ways of doing it, but it just never works. I don't understand how on earth you do this. And the PHP file goes like this:
<?php
include ('db_connect.php');
$data = $_POST['data'];
$query = "UPDATE song SET time='".$data."' WHERE id='1'";
mysqli_query($query);
?>
And yes, I'm fully aware that my database is vulnerable for SQL injections, and I will fix that as soon as I get this working.
This is what I've tried, but I can do things completely different if you think that is necessary.
Right now I got the JS:
function saveinPHP() {
var superstr = $( "#savelyric" ).text();
$.ajax({
type: "POST",
url: "includes/sendlyrics.php",
data: {superstr: superstr},
success: function(data){
alert("***DATA***"+data+"***MSG***");
alert("Settings has been updated successfully." + data + "~~~");
//window.location.reload(true);
}
});
And PHP
<?php
include ('db_connect.php');
$data = $_POST['superstr'];
$query = "UPDATE song SET lyrtime='".$data."' WHERE id='1'";
mysqli_query($query);
?>

Only change this line:
var superstr = { lyricsave:lyr }
with
var superstr = { data:lyr }

You are trying to pass var superstr = $( "#savelyric" ).text(); as your question states, but in your code you are actually assigning:
var superstr = { lyricsave:lyr }
Change it to:
var superstr = $( "#savelyric" ).text();
UPDATE (per Kevin B's comment)
You also need to change the following:
data: {superstr: superstr},
and in your PHP:
$data = $_POST['superstr'];
Also, why are you tring to set it to the time column? I have not seen your tables, but a wild guess will tell me that time is a different datatype (TIMESTAMP/DATETIME maybe?) and is rejecting your data. Don't you want to set it to a column named data or lyrics or anything which contains text?

Related

Update image after it's been clicked, without reloading page

I'm making this Flag/Unflag system, and it works okay. The only thing I'm struggeling with is how to update the Flag_icon, after it's been clicked? It's should be so it just changes after it's been clicked, and if it's clicked again then it changes back. Right now I have to click the flag, and then reload the page manually, and then it's changed.
$FlagStatus[$count] has the value YES/NO, from my database, and $testjobids[$count] is a unique ID from db table. I've been looking at some Ajax and Javascript to do this, but i can't seem to wrap my head around how to implement it right. I just need to be pointed into the right direction, because I'm a bit stuck.
Index.php
if ($FlagStatus[$count] == ('YES')) {
echo'<img class="Unflagging" onclick="changeImage('.$testjobids[$count].')" id="'.$testjobids[$count].'" data-id = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagMarked.png">';
} elseif($FlagStatus[$count] == ('NO')){
echo'<img class="Flagging" onclick="changeImage()" id="'.$testjobids[$count].'" data-id2 = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagUnmarked.png">';
}
Flagging.php / Almost same as Unflagging.php
<?php
require("../resources/MysqliHandler.class.php");
require("../resources/layoutfunctions.php");
require("GetData.php");
$ICON_DIMENSION = "16px";
// Used to connect the right server Testreportingdebug or Testreporting
$db = ServerConn();
// -------------------------------------
$MysqliHandler = new mysqliHandler($db);
$MysqliHandler->query("SET NAMES UTF8");
$receiver = $_POST["FlagID"];
$MarkYes = "UPDATE `testreportingdebug`.`testjob` SET `FlagStatus` = 'YES' WHERE id = $receiver";
$query = $MysqliHandler->query($MarkYes);
?>
Ajax
echo'
<script type="text/javascript">
$(document).on("click", ".Unflagging", function(){
var FlagID = $(this).data("id");
$.ajax({
method: "post",
url: "unflagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
$(document).on("click", ".Flagging", function(){
var FlagID = $(this).data("id2");
$.ajax({
method: "post",
url: "flagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
</script>
';

AJAX Post values not received in PHP

Below is my ajax file. Here I passed all my text box values.
And I post that values to edu.php. There I want to update two tables like details and test.
But nothing is updating in my database.While I checked the value with var_dump the string seems to be empty.But while passing from ajax I checked it with an alert it shows all the values in text box. So I believe problem is happening while posting from ajax to php.
AJAX Code
$('#edubackgroundsubmit').click(function (event) {
event.preventDefault();
alert("Hello");
var per_email = $('#per_email').val();
var master_overall = $('#master_overall').val();
var master_pass_year = $('#master_pass_year').val();
var master_college = $('#master_college').val();
var master_univ = $('#master_univ').val();
var data1 ="master_qual="+master_qual+"&master_overall="
+master_overall+"&master_pass_year="+master_pass_year+"&master_college="+master_college+"&master_univ="+master_univ
+"&edu_flag="+edu_flag;
alert(data1);
$.ajax({
type:"POST",
url: "edu.php?per_mobile="+per_mobile,
dataString1: data1
}).done(function( dataString1 )
{
alert(dataString1);
$('#edu_alert').append(
'<div class="alert alert-success text-center">' +
'<button type="button" class="close" data-dismiss="alert">' +
'×</button>' + dataString1 + '</div>');
});
});
PHP File
if (isset($_POST['pass_year_12'])) {
$pass_year_12 = $_POST['pass_year_12'];
} else {
$pass_year_12 = "";
}
$l1 = "UPDATE test
SET edu_flag='$edu_flag'
WHERE per_mobile='$per_mobile'";
$l2 = "UPDATE details
SET master_qual='$master_qual',
master_overall='$master_overall',
master_pass_year ='$master_pass_year ',
master_college='$master_college'
WHERE per_mobile='$per_mobile'";
$exec = mysqli_query($link, $l1);
if (mysqli_query($link, $l2)) {
echo "Education Details Updated Successfully";
} else {
echo "Error updating record: " . mysqli_error($link);
}
This is wrong. What's this bit:
dataString1: data1
You need to change it as:
data: data1
The function $.ajax() POSTs only those given in the data attribute.
Problem with your code is hat you are sending the data at edu.php?per_mobile
so you need to add isset condition before the code... like this
if(isset($_REQUEST['per_mobile'])){ //write your code here }
and also replace datastring to data.
and then try.
Hope it may help.
For instance you can also use jQuery get or post method, that is more reliable and easy to learn.

Get a new Sql id after submition by Ajax

After submission a comment of a post with ajax, comment.php display new comment with its own SQL auto increment id. like:
// Here $id comes from SQL after submit data
<div class="comment'.$id.'"><ul>
// new comment
</ul></div>
Now, how to get this new id in Ajax complete: function(data) from comment.php to show it post.php page into .
I tried this code which not working:
complete: function(data){
var ID = $(this).attr('id').replace('comment','');
$(".comment"+ID).append(data.responseText);
$(".comment"+ID).fadeIn(2000);
}
complete code:
$(".repfrm").click(function(){
error.fadeOut();
if(checkForm()){
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var img = inputImg.attr("value");
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$.ajax({
type: "POST", url: "comment.php", data: "action=insert&author="+ author + "&replycom="+ replycom + "&url="+ url + "&img="+ img + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
error.fadeOut();
var ID = $(this).attr('id').replace('comment','');
$(".comment"+ID).append(data.responseText);
$(".comment"+ID).fadeIn(2000);
});
}
});
}
else //alert("Please fill all fields!");
error_message();
});
It helps to describe exactly how your code isn't working, but I think I found it:
var ID = $(this).attr('id').replace('comment','');
should be
var ID = $(this).attr('class').replace('comment','');
I suppose you need this:
This is used to get the last insert id, ID of last record inserted
Send this into your ajax call back and append as the ID.
Let us know if you want to know how to send this from comment.php
your attribute is not id it is class so use something like this:
var ID = $(this).attr('class').replace('comment','');
$(".comment"+ID).append(data.responseText);
$(".comment"+ID).fadeIn(2000);
see this for sample:
<script>
$( document ).ready(function() {
var ID = $('div').attr('class').replace('comment','');
alert(ID);
});
</script>
</head>
<body>
<div class="comment1"></div>
</body>

Inserting a data on a database using AJAX/JSON/Jquery

I'm trying to create a small chat application but for the sake of minifying the bytes being transferred is there any other way on writing this javascript that is less heavy than this code?
Here is my javascript:
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = AjaxRetrieve();
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
Can this also be done on a JSON format too? because I think some says that json is lighter.. not sure though
here is my php code
$con = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt=$con->prepare($sql);
$stmt->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt->execute();
foreach($stmt->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$text=$_POST['message'];
$sql4 = "INSERT INTO $tblname2(msgid,username,message_content,message_time,recipient)VALUES(:aid,:a,:b,NOW(),:c) ";
$stmt5 = $con2->prepare($sql4);
$stmt5->bindParam(':aid',$tblpre,PDO::PARAM_STR);
$stmt5->bindParam(':a',$_POST['name'],PDO::PARAM_STR);
$stmt5->bindParam(':b',$text,PDO::PARAM_STR);
$stmt5->bindParam(':c',$usern,PDO::PARAM_STR);
$stmt5->execute();
As user2401175 saies. Why not use a framework, thats what they are here for.
jQuery is really simple and easy to understand.
You could try adding this, just before your "" tag.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Under this include of jQuery, you may now use the jQuery Post method to do your ajax request.
In html Use
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
then Create javascript object like this
var changePacket = {
date1:value1,
data2:value2
}
And send Ajax request
$.ajax({
url: "phpFile.php",
dataType: 'json',
type: 'POST',
data: {json:JSON.stringify(changePacket)},
success: function(response) {
alert('hip hip hurray');
},
error: function(response) {
alert('some thing wrong happend');
}
});
In php
$json = $_POST['json'];
$data = json_decode($json);
now user your variable like this $date->data1 and $date->data2

Pass Array FROM Jquery with JSON to PHP

hey guys i read some of the other posts and tried alot but its still not working for me.
when i alert the array i get all the results on the first site but after sending the data to php i just get an empty result. any ideas?
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
window.location = "foo.php";
});
});
Php
$data = json_decode($_POST['data']);
THANK YOUU
my array looks something like this when i alert it house/flat,garden/nature,sports/hobbies
this are a couple of results the user might choose (from checkboxes).
but when i post it to php i get nothing. when i use request marker (chrome extension) it shows me something likethat Raw data cats=%5B%22house+themes%22%2C%22flat+items%22%5D
i also tried this way-- still no results
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
alert(cats);
$.ajax({
type: 'POST',
url: "foo.php",
data: {cats: JSON.stringify(cats)},
success: function(data){
alert(data);
}
});
});
window.location = "foo.php";
});
});
php:
$json = $_POST['cats'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
echo "<pre>";
print_r($data);
its drives me crazy
Take this script: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
so now your code is
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
// window.location = "foo.php"; // comment this by this page redirect to this foo.php
});
});
//and if uou want toredirect then use below code
-------------------------------------------------
$.post('foo.php',{data:st},function(data){
window.location = "foo.php";
});
---------------------------------------------------
Php
$data = json_decode($_POST['data']);
var ItemGroupMappingData = []
Or
var ItemGroupMappingData =
{
"id" : 1,
"name" : "harsh jhaveri",
"email" : "test#test.com"
}
$.ajax({
url: 'url link',
type: 'POST',
dataType: "json",
data: ItemGroupMappingData,
success: function (e) {
// When server send response then it will be comes in as object in e. you can find data //with e.field name or table name
},
error: function (response) {
//alert(' error come here ' + response);
ExceptionHandler(response);
}
});
Try this :-
$data = json_decode($_POST['data'], TRUE);
I think you should move the "window.location = " to the post callback, which means it should wait till the post finshed and then redirect the page.
$.post('foo.php', {
data : st
}, function(data) {
window.location = "foo.php";
});

Categories

Resources