jQuery+PHP. Request/Response - php

I would search for the solution, but I don't know what exactly do I have to search.
The task is to grab texts with ID's (#ftext_1,..._2,..._3,..._4) in html file and send them to php file. After some manipulation with texts in php file I have to insert them back into their ID's in html file.
Here is the code:
var text_1_Replace = $('#ftext_1').text();
var text_2_Replace = $('#ftext_2').text();
var text_3_Replace = $('#ftext_3').text();
var text_4_Replace = $('#ftext_4').text();
$('#ID').on('click', function(){
var text= {
ftext_1: text_1_Replace,
ftext_2: text_2_Replace,
ftext_3: text_3_Replace,
ftext_4: text_4_Replace
}
var targetFile = 'ajax/file.php';
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text),
contentType: 'application/JSON'
}).done(function(data) {
console.log(data);
});
});
How do I edit .done function to place new texts in their old ID's(#ftext_1,..._2,..._3,..._4)? The variable with texts array is $result.
so the answer is :
}).done(function(data) {
var text = JSON.parse(data);
var text1 = text.ftext_1;
var text2 = text.ftext_2;
var text3 = text.ftext_3;
var text4 = text.ftext_4;
$('#ftext_1').text(text1);
$('#ftext_2').text(text2);
$('#ftext_3').text(text3);
$('#ftext_4').text(text4);
So, the last update for the topic: The real and nice answer is:
.done(function(data) {
var text = JSON.parse(data);
$.each(text, function(i, val){
$("#" + i).text(val);
});
This code is the solution to my question in this topic. Thank you all, who responded!

The best for you would be send named property that looks like this
$.ajax({
method: 'post',
url: targetFile ,
data: {data: text},
dataType: "json",
success: function(response){
$.each(response, function(element){
$("#"+element.name).text(element.text);
});
}
});
Then in your php you could easily iterate data from post
<?php
$data = $_POST['data'];
$response = [
];
foreach($data as $elementName => $text){
// some text management
$response[] = ['name' => $elementName, 'text' => $text];
}
return json_encode($response);

When you change your received values in php you put them in an array so that you
can call it later easily
PHP
$values = array("one"=>5,
"two"=>"something",
"three"=>$something);
echo json_encode($values);
You need to add
dataType:'json'
in Jquery since you're returning json
JQuery
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text), # or data: {"value1":value,"value2":value2},
contentType: 'application/JSON',
dataType:'json',
success: function(response){
console.log(response.one); #Will console 5
console.log(response.two); #Will console "something"
console.log(response.three); #Will console whatever $something holds in php
}
});
You can call it however you want it (response) or (mydata)...
And then you just type response.yourdata (that you declared in php)

Related

Upate table with AJAX in Laravel 5.3 not working

I trying to use an AJAX PUT request to update a row in my database and I am trying to send the request to my controller. This is my AJAX call:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leased').val();
var truckModel = $('#truck-model').val();
$.ajax({
url: 'editTruck',
type: 'put',
data: {
truckNo: truckNo,
truckOwner: truckOwner,
vehicle_number: vehicle_number,
capacity: capacity,
end_of_insurance: end_of_insurance,
end_of_kteo: end_of_kteo,
truckCode: truckCode,
leased: leased,
truckModel: truckModel
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(){
console.log('success');
},
error: function(){
console.log('something went wrong');
}
});
});
So far so good. If I console.log() my data is seems I can get them from the form. I am using Laravel Collective for the form:
{!!Form::open(array('action' => ['Trucks#editTruck'], 'method' => 'put')) !!}
and my route is the following:
Route::put('/editTruck', 'Trucks#editTruck',function(){ });
Now I am using Request $request in the parameters of the controller but somehow it looks like I cannot get the incoming values. For example the following var_dump will say NULL.
public function editTruck(Request $request)
{
$data = $request->input('truckNo');
var_dump($data);
}
Same happens if I use
$data = $request->truckNo;
instead. So I am wondering how can I get the values that are been sent to my controller with my AJAX call? Why am I getting NULL values?
What I was planning to do is:
public function editTruck(Request $request)
{
$singleTruck = Truck::find($request->truckNo);
$singleTruck->truckNo = $request->input('truckNo');
$singleTruck->truckOwner = $request->input('truckOwner');
........
$singleTruck->save();
}
You can find the answer here:
https://laravel.io/forum/02-13-2014-i-can-not-get-inputs-from-a-putpatch-request
You should change your form method and method inside your js code to "post", and add extra field "_method" = "PUT"
probably it can help.
OK I found it. Looks like the AJAX was malformed. So here is how it should be written:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#vehicle_capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leasing').val();
var truckModel = $('#truck-model').val();
var outGoingData = {
'truckNo': truckNo,
'truckOwner': truckOwner,
'vehicle_number': vehicle_number,
'capacity': capacity,
'end_of_insurance': end_of_insurance,
'end_of_kteo': end_of_kteo,
'truckCode': truckCode,
'leased': leased,
'truckModel': truckModel,
};
var data = JSON.stringify(outGoingData);
$.ajax({
url: 'editTruck',
type: 'POST',
data: data, <!-- The error was here. It was data: {data}-->
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(response){
alert("The data should be "+ response);
},
error: function(){
console.log('skata');
}
});
});

$_Post failing (Sending Ajax)

Can someone please show me the correct way I can add these two lines of code
data: {name: info, me: '<?php echo $me; ?>'},
data: dataString ,
So that I can send them in a $_POST to my action.php , I have tried several ways to do this but cannot get both of them successfully to be passed on to my action_comments.php I understand I'm missing something possible when using data: below or have not correctly formatted my code . I'm a total beginner with very little experience so sorry if I lack good practice but hopefully can be better from my debugging . Thanks to anyone who helps me get passed this .
Here is complete code to give overview what Im doing
<script type="text/javascript">
$(function() {
// call the submit button ref: name
$(".submit_button").click(function() {
declare textcontent
var textcontent = $("#content").val();
//dataString = 'content' globel var
var dataString = 'content='+ textcontent;
declare info
var info = $('#name').val();
// option no text inputted
if(textcontent=='')
{
// show message if no text
alert("Enter some text..");
$("#content").focus();
}
else
{
//display text animation loading
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
//var info equals the string
var info = $('#content').val();
//start ajax call
$.ajax({
type: "POST",
//path to my action.php
url: "actions/action_comment.php",
//Need to undestand how to correctly format these lines so
//they are both succesful when submitted to my action_comment.php
$me is declared (not-shown here it holds integer)
data: {name: info, me: '<?php echo $me; ?>'},
// pass the string from textarea to $_POST
data: dataString ,
// I can get one or the other to work but not both
cache: true,
// feed the success my data
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
I have my $_POST as follows in action_comment.php
echo $me = $_POST['me'];
//DATASTRING FROM TEXTAREA
echo $content= $_POST['content'];
var dataString = 'content='+ textcontent;
$.ajax({
type: "POST",
url: "actions/action_comment.php",
data: {name: info, me: '<?php echo $me; ?>',txt_data: dataString},
....
});
Cannot use data attribute multiple times in same ajax request. Within php file you can access like $_POST['txt_data'] to get textarea content and same way for other parameters;
define data attribute once and pass all the data like as shown above.
if you want to post whole form data you can use this way
var form = $('#my_form');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
..
..
});

PHP Array to jQuery - gmaps.js not creating marker

I'm trying to use a PHP Array to get long and lat values from a database, and put these onto a map using gmaps.js.
So far, I have created the array in PHP, and echoed this onto my page to confirm the correct values are being displayed.
$data = array();
$data['latitude'] = array($lat);
$data['longitude'] = array($lng);
echo json_encode($data);
So $data is the array, with the values I want inside.
I then want to use jQuery to get the data from json encode, put these into the map marker locations and display the markers like so:
$.ajax({
type: "POST",
url: "phppage.php",
dataType: "JSON",
success: function(data) {
$.each(data, function(key, value) {
poi_marker = {
marker: {
lat: data.latitude,
lng: data.longitude,
}
}
}
poi_markers.push(poi_marker);
});
map.addMarkers(poi_markers);
}
});
I get no errors in my console (using firefox and firebug), the map displays but no markers are shown.
I don't think that you're code is actually doing what you think that it is doing. See this fiddle for what is actually happening with your loop.
If you store the array differently on the PHP side, it'll be easier to loop through multiple markers in JS. Also, I don't think gmaps.js needs that extra 'marker' key in the object.
New PHP
$data = array();
$data[] = array(
'latitude' => $lat
,'longitude' => $long
);
echo json_encode($data);
New JS
var poi_markers = []; // make sure you declare this before using it. if you already declare it somewhere else, don't use this line
$.ajax({
type: "POST",
url: "phppage.php",
dataType: "JSON",
success: function(data) {
$.each(data, function(key, value) {
var poi_marker = {
lat: value.latitude,
lng: value.longitude
}
poi_markers.push(poi_marker);
});
map.addMarkers(poi_markers);
}
});
You might be having trouble because you specify dataType: "JSON" but (atleast in the code you posted) you don't change the header on the php side. You may need to add this line to the top of phppage.php
header("Content-Type: application/json", true);
Where I learned everything I know about gmaps.js
I suppose that the data retrieved successfully as needed
$.ajax({
type: "POST",
url: "phppage.php",
dataType: "JSON",
success: function(data) {
$.each(data, function(key, value) {
map.addMarker{
lat: data.latitude,
lng: data.longitude
}
}
}
});
Check This

Sending an array from jquery to PHP and back

I have a list of options (categories) of projects that the user can see. By selecting the categories, the div below should update with the lists of projects matching said categories.
Despite using the following answer, almost verbatim, Send array with Ajax to PHP script, I am still unable to retrieve any results, and yet no errors show up either.
The jquery:
// filter for projects
var $checkboxes = $("input:checkbox");
function getProjectFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.name);
}
});
return opts;
}
$checkboxes.on("change", function(){
var opts = getProjectFilterOptions();
//alert(opts);
var categories = JSON.stringify(opts);
$.ajax({
url: "/web/plugins/projcat.php",
type: "POST",
dataType: "json",
data: {data : categories},
cache: false,
success: function(data) {
$('#projects').html(data);
//alert(data);
}
});
});
the php (still in testing, so not filled out):
<?php
if(isset($_POST['categories'])) {
//echo "testing";
$data = json_decode(stripslashes($_POST['categories']));
print_r($data);
}
?>
Where is the error?
Try this:
JS
...
// dataType: "json", // remove that; you're not sending back JSON string
data: {categories : categories},
cache: false,
...
PHP
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['categories'])) {
//echo "testing";
$data = json_decode(stripslashes($_POST['categories']));
// .. process the $data
print_r($data);
return;
}
?>
Your desired array is in $_POST['data'] and not in $_POST['projcats']. Change data: {data : categories}, to data: { projcats: categories }, to use $_POST['projcats'].

Zend and Jquery (Ajax Post)

I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.

Categories