Wordpress Won't parseJSON when I include a special string - php

I have a system that updates HTML via AJAX when a button is clicked. There is a function that fetches the HTML to be updated (tested and works), a function that sends a JSON encoded array that contains a true or false variable and a string with the updated HTML from the other function and finally the JQuery itself which retrieves the information. The problem is when I try to pass the HTML information through the array there becomes an "Uncaught SyntaxError: Unexpected token <"
JQuery Code That Retrieves and Sends Essential Information
//One of the functions didn't have the data type for testing purposes
(function ($) {
$('.arrow-up').click(function () {
var user_id = $(this).attr('rel');
var my_data = {
action: 'arrow_handler', // This is required so WordPress knows which function to use
move_id: user_id,
arrow_status: 'up'
};
$.post(ajax_url, my_data, function (data) {
var objprase=$.parseJSON(data); // now obj is a json object
if (objprase.true == 'true') {
alert(objprase.true);
} else {
alert(objprase.true);
}
});
});
})(jQuery);
(function ($) {
$('.arrow-down').click(function () {
var user_id = $(this).attr('rel');
var my_data = {
action: 'arrow_handler', // This is required so WordPress knows which function to use
move_id: user_id,
dataType: 'JSON',
arrow_status: 'down'
};
$.post(ajax_url, my_data, function (data) {
var objprase=$.parseJSON(data); // now obj is a json object
if (objprase.true == 'true') {
alert("hello");
} else {
alert(objprase.true);
}
});
});
The Function that retrieves the information sent by the Ajax Post and Sends back an encrypted JSON String
// Finds information and sets $truetest to its value
$htmlreturn = tableReturn(); // tableReturn() gets the new HTML code
$datapasser = array("true" => $truetest, "text" => $htmlreturn);
echo json_encode($datapasser);
die(); // this is required to return a proper result
Post Responce
<table id="blog-table" border="1">
<tr> <td align="center">UserName</td> <td align="center">User ID</td> <td align="center">Order</td> <td align="center"></td> <td align="center">Move Up/Down</td> </tr>
<tr id="1"> <td>Olesiarpm</td>
<td>18</td>
<td id="1">1</td>
<td>
<button class="del_btn" rel="1">Delete</button>
</td>
<td><div class="arrow-down" rel="18"></div> </td>
<tr id="2"> <td>bluice12</td>
<td>16</td>
<td id="2">2</td>
<td>
<button class="del_btn" rel="2">Delete</button>
</td>
<td> <div class="arrow-up" rel="16"></div><br><div class="arrow-down" rel="16"></div> </td>
<tr id="3"> <td>fSnNO4Xvlq</td>
<td>35</td>
<td id="3">3</td>
<td>
<button class="del_btn" rel="3">Delete</button>
</td>
<td> <div class="arrow-up" rel="35"></div><br><div class="arrow-down" rel="35"></div> </td>
<tr id="4"> <td>heklylh5469</td>
<td>13</td>
<td id="4">4</td>
<td>
<button class="del_btn" rel="4">Delete</button>
</td>
<td><div class="arrow-up" rel="13"></div> </td>
</table>{"true":"1","text":""} // The HTML is not shown in the "text" but instead is behind the brace

$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: 'json'
});
Can you pass 'json' as the expected data type and don't don't use the jsonParse.

Try this:
$datapasser=array(
"true"=>utf8_encode($truetest),
"text"=>utf8_encode($htmlreturn)
);
I would change this
if (objprase.true == 'true') {
alert(objprase.true);
} else {
alert(objprase.true);
}
The if is doing the same thing for true and false

The problem is if you echo something it won't return a value, it will only print it out. The only way I found out you can do a for loop inside html is to make a string that contains all the html and concatenate to it. Finally, return the string.

Related

Laravel: Jquery on click function issue

I am trying to alert something but on click function is running only once on the first button. but I have buttons on many rows.
I am fetching Data through Laravel from Database in a table. Only one button runs a function, then nothing happens with other buttons.
Jquery:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
var val = $("#thisr").attr('value');
alert(val);
});
});
View:
<table id="recover-table" class="table" >
<thead>
<tr class="bg-info">
<th>Teacher Name</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($trashs as $trash)
<tr id="thisr" value="{{$trash->id}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap "><button type="submit" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
</tr>
#endforeach </tbody></table>
Right now even alert is not working, but I want to achieve Refresh table after a record is deleted from Table.
Update: Now Alert is working fine, but when I delete a record by pressing a button, only one row is deleting. the function runs once.
Complete Js:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
let teacher_id=$(this).attr('value');
console.log('Restore button clicked!')
e.preventDefault();
$.ajax(
{
url: "/teachers/recover/" + $('#restore-data').attr("value"),
type: 'GET', // Just delete Latter Capital Is Working Fine
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: teacher_id,
success: function (data) {
console.log(data.msg);
console.log(teacher_id);
if(data.msg){
$('#thisr').remove();
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data.msg);
}
},
error: function (xhr) {
console.log("Error Restoring Record");
//console.log(xhr.responseText);
},
});
});
});
You can try to use class 'restore-data'
$(document).ready(function(e) {
$(document).on('click', '.restore-data', function(e) {
var val = $('#thisr').val();
alert(val);
});
});
As id should be unique for each element.
You can try something like
#foreach($trashs as $trash)
<tr>
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" data-trash-id="{{$trash->id}}" class="restore-data">Delete</button>
</td>
</tr>
#endforeach
and JS as
$(document).on('click', '.restore-data', function(e) {
var trash_id = $(this).attr('data-trash-id');
alert(trash_id);
});
Change this line.
var val = $("#thisr").attr('value');
to (since you have value attribute in button):
var val = $(this).attr('value');
or (since you have value attribute td):
var val = $(this).parent('tr#thisr').attr('value')
To remove a row.
$('#restore-data').on('click', function(e) {
var _this = $(this);
...
if(data.msg){
_this.parent('tr#thisr').remove();
....
Also change button type to button.
<button type="button" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
You gave same id to all button and id must be unique of particular button so you can define unique id with key of array and pass it to Function
#foreach($trashs as $key=>$trash)
<tr id="thisr{{$key}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" class="" name="id" value="{{$trash->id}}" id="restore-data{{$key}}" onclick="restoreData({{$key}})">Delete</button>
</td>
</tr>
#endforeach
function restoreData(key){
var val = $("#restore-data"+key).attr('value');
alert(val);
// you can use either
$("#restore-data"+key).closest('tr').remove();
// OR
$('#thisr'+key).remove();
}

How to send multiple same name input fields value via ajax post method

I have two same name multiple input fields. I want to send all fields value from another page using jquery ajax post method but i am not getting all rows input fields value. Please review my code.
Javascript code
<script type="text/javascript">
function getValue()
{
$.post("paidamt.php",
{
paidamt : $('#paidamt').val(),
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Html Code
<div>
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" id="paidamt"></td>
<td><input type="checkbox" name="uid[]" id="uid"
value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<input type="button" name="submit" id="submit"
onclick="getValue(1)" value="Save Amt.">
</form>
</div>
<div id="divShow">
</div>
Try this one
var paidamt = $("input[name=paidamt]").map(function(){
return $(this).val();
}).get().join(",");
var uid = $("input[name=uid]").map(function(){
return $(this).val();
}).get().join(",");
$.ajax(
{
type: "POST",
url: 'paidamt.php',
data:
{
paidamt:paidamt,
uid:uid
}
});
Firstly you have given the input elements the same id which is repeated in the loop. This will end up in your HTML being invalid, you should change the id to class:
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" class="paidamt"></td>
<td><input type="checkbox" name="uid[]" class="uid" value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<button type="submit" name="submit" id="submit">Save Amt.</button>
</form>
To actually send the input values in the AJAX request you can simply serialize() the containing form when the form is submit:
$(function() {
$('form').submit(function(e) {
$.ajax({
url: "paidamt.php",
type: 'POST',
data: $(this).serialize(),
success: function(data) {
$("#divShow").html(data);
});
});
});
});
I suggest to add class instead of id, since identically class can be repeated but id should not.
<script type="text/javascript">
function getValue()
{
var paidamtval = [];
$('#paidamt').each(function(){
paidamtval.push($(this).val());
});
$.post("paidamt.php",
{
paidamt : paidamtval,
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Since you will have many of these, id - needs to be unique, which in your case isn't, so remove "id="paidamt"
<td><input type="text" name="paidamt[]" id="paidamt"></td>
That's your first mistake. And secondly don't use $.post, to submit this form. Either remove AJAX submit, or bind form using something like jQuery Form plugin.
You try this code
$('document').ready(function(){
$('#submit').click(function(){
jQuery.ajax({
type: "POST",
url: "paidamt.php",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html){
try{
$("#divShow").html(data);
}catch (e){
alert(JSON.stringify(e));
}
},
error : function(e){alert("error "+JSON.stringify(e)); }
});
});
});
in you paidamt.php file
$paidamt=$_POST['paidamt'];// its can array values
print_r($paidamt);// result display

How update model after inserting entry to database? And refresh a view

I shyly trying to make friends Angular and backend database.
Simple operations. Get database to angular model. Save entry in database, and delete entry.
I'm stacked on DELETE action. When i delete entry that loaded from database it's ok. But when i delete newly created row by push method, i got error.
This occurs because in the model absent id. After inserting entry to database, i trying repeatedly refresh Angular model from database.($http.get) But in this case, a view didn't refresh (only blinks). I saw new entry only refresh page F5.
Help!
Books
<div ng-app="App" ng-controller="MyCtrl">
<table class="">
<th>
<tr style="font-size: 20px">
<td>ID</td>
<td>Name</td>
<td>Price</td>
<td>Action</td>
</tr>
</th>
<tr ng-repeat="book in books">
<td style="width: 200px">{{book.id}}</td>
<td style="width: 200px">{{book.name}}</td>
<td style="width: 50px">{{book.price |currency}}</td>
<td>
<button ng-click="removeItem($index)">Удалить</button>
</td>
</tr>
<tr>
<td></td>
<td><input type="text" ng-model="name"/></td>
<td><input type="number" ng-model="price"/></td>
<td>
<button ng-click="addBook()">Добавить книгу</button>
</td>
</tr>
</table>
</div>
<script>
var App = angular.module('App', []);
App.controller('MyCtrl', function ($scope, $http) {
$http.get('http://ang:8888/index.php?r=site/api2').success(function (data) {
$scope.books = data;
});
$scope.removeItem = function (index) {
var id = $scope.books[index].id;
$scope.books.splice(index, 1);
$http.post('http://ang:8888/index.php?r=site/del2', {id: id});
}
$scope.addBook = function () {
var newBook = ({name: $scope.name, price: $scope.price});
$scope.books.push(newBook);
$http.post("http://ang:8888/index.php?r=site/post2", {name: $scope.name, price: $scope.price})
.success(function (data, status, headers, config) {
console.log("inserted Successfully");
});
$http.get('http://ang:8888/index.php?r=site/api2').success(function (data) {
$scope.books = data;
});
}
})
The problem is due to async nature of all remote calls. You call the post and get methods in sequence without realizing that both are sync in nature. So your post is immediately followed by get.
Change the code for post to
$http.post("http://ang:8888/index.php?r=site/post2", {
name: $scope.name,
price: $scope.price
}).success(function (data, status, headers, config) {
console.log("inserted Successfully");
$http.get('http://ang:8888/index.php?r=site/api2').success(function (data) {
$scope.books = data;
});
});
In the above code you only do get when post is done.

Knockout Mapping not updating self.users

Trying to display all users from a MySQL database in Knockout and CodeIgniter. I'm getting a json response back from the server but Knockout isn't displaying the Json data.
I keep getting:
Uncaught ReferenceError: Unable to parse bindings.
Bindings value: text: id
Message: id is not defined
Html:
<!-- Users -->
<table class="table table-condensed table-striped table-bordered table-hover">
<thead>
<tr><th>User Id</th><th>Name</th><th>Email</th><th>Role</th></tr>
</thead>
<tbody data-bind="foreach: users">
<tr>
<td data-bind="text: id"></td>
<td><input data-bind="value: name" /></td>
<td><input data-bind="value: email"/></td>
<td><select data-bind="options: $root.roles, value: role, optionsText: 'role', optionsValue: 'role'"></select></td>
<td><a href="#" data-bind="click: $root.removeUser" class='icon-remove'></a></td>
</tr>
</tr>
</tbody>
</table>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
Knockout:
<script type="text/javascript">
function User(data) {
this.name = ko.observable(data.name);
this.email = ko.observable(data.email);
this.id = ko.observable(data.id);
this.role = ko.observaveble(data.role);
}
function UserListViewModel(data) {
// Data
var self = this;
self.users = ko.observableArray([]);
// Operations
self.addTask = function() {
self.tasks.push(new Task({title: this.newTaskText()}));
self.newTaskText("");
};
self.removeTask = function(task) {
self.tasks.remove(task)
};
// Load initial state from server, convert it to Task instances, then populate self.tasks
$.get("/sws/users/index", function(data) {
var mappedUsers = ko.mapping.fromJSON(allData);
self.users(mappedUsers);
});
}
ko.applyBindings(new UserListViewModel());
</script>
Json:
{"users":[{"id":"1","email":"example#gmail.com","password":"tacos","permissions":null,"activated":"1","activation_code":null,"activated_at":"2013-09-23 20:19:42","last_login":"2013-09-23 20:19:42","persist_code":null,"reset_password_code":null,"name":"Chris","created_at":"2013-09-23 04:17:24","updated_at":"2013-09-23 07:16:23"}]}
You're passing allData as an argument to the mapping, but it isn't defined anywhere. You want data.users instead (not data because then ko.mapping.fromJSON will return a single object with one key, users whose value will be an observableArray; you'll confuse Knockout if you try to use that object as the value of another observableArray, namely self.users).
Switching to this .ajax call seemed to resolve the issue.
// Load initial state from server, convert it to User instances, then populate self.users
$.ajax({
url: '/sws/users/index',
dataType: 'json',
type: 'POST',
success: function (data) {
self.users(data['users']);
console.log(data['users']);
}
});

Add row to table after a form submit without refresh - jquery ajax php

I've an ajax form and a table.
This is my ajax code :
$(function () {
$(".submitann").click(function () {
var title = $("#title").val();
var announcement = $("#announcement").val();
var dataString = $('#annform');
if ((title == '') || (announcement == '')) {
alert("Please Fill In The Fields");
} else {
$.ajax({
type: "POST",
dataType: "json",
data: dataString.serialize(),
url: "http://www.domain.com/formprocess.php",
success: function (data) {
//insert table code here
});
}
return false;
});
});
I tried but failed. In the php code, I've done this :
$data = '<tr class="odd gradeX">
<td>
<input type="checkbox" class="checkboxes" value="1" />
</td>
<td><a href="#" class="anntitle" data-type="text" data-pk="'.$id.'" data-original-title="Enter title"
data-name="title">'.$_POST["title"].'</a>
</td>
<td><a class="delete" href="javascript:;">Delete</a>
</td>
</tr>';
echo json_encode($data);
It works with many problems.
Firstly, it goes to the last row.
Second, the x-editables does not work.
How to add a row to the without refreshing the page?
first you need to give the id to your <table id="mytable">.than on success of ajax, add just like this:
var row_data = "";
row_data +="<tr class='odd gradeX'>
<td><input type='checkbox' class='checkboxes' value='1' /></td>
<td><a href='#' class='anntitle' data-type='text' data-pk=''.$id.'' data-original-title='Enter title' data-name='title' >'.$_POST['title'].'</a></td>
<td><a class='delete' href='javascript:;'>Delete</a></td>
</tr>";
$("#mytable").append(row_data);

Categories