I am trying to post some data via ajax to php. The issue i have is the original data is pulled in via some java, like this:
var taskID = jQuery(this).attr('data-id');
var taskTitle = jQuery(this).attr('data-title');
var taskContent = jQuery(this).attr('data-content');
jQuery('.task_title').val(taskTitle);
jQuery('.task_description').val(taskContent);
When i then try and update this content in the browser (via a form), only the original data is getting posted back, and not the updated data.
Here is my ajax to post the data:
$( ".saveTaskEdit" ).click(function(event) {
var ta = $('.task_title').val();
var da = $('.task_description').val();
var taskID = $('.editTaskPanel').attr('data-id');
$.ajax({
type: "post",
url: "task-edit.php?t="+ ta + "&d=" + da + "&id=" + taskID,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
jQuery('p.status').text('Task Saved');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
});
Is there any reason behind this?
You set type as "post" but send data as "get"; change your ajax , update "url" add "data" like this:
$( ".saveTaskEdit" ).click(function(event) {
var ta = $('.task_title').val();
var da = $('.task_description').val();
var taskID = $('.editTaskPanel').attr('data-id');
$.ajax({
type: "post",
data: { "t":ta,"d":da,"id":taskID},
url: "task-edit.php",
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
jQuery('p.status').text('Task Saved');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
});
Related
I've been trying some stuff with Ajax and laravel, I've tried a lot at this point and have no idea what is going wrong. I can't seem to get the form data (that's what this is mainly about). If ANYONE is able to help, it'd be great. Here's the code, and thanks in advance.
$('.bier').on('click', bier);
$('.delete-check-close').on('click', closeDelete);
$('.delete-check-show').on('click', showDelete);
$('.message').on('click', closeMessage);
hideMessage();
$('form.page').on('submit', bier);
function bier() {
var form = $(this);
var url = form.attr('action');
console.log(url);
console.log(form);
console.log('bier');
console.log(form.find('input').serialize());
console.log('/bier');
var wtf = new FormData(form);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'json',
data: form.serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data, textStatus, jqXHR) {
console.log('success');
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
var data = $.parseJSON(jqXHR.responseText);
console.log(data);
if (data.errors) {
console.log(data.errors);
$.each( data.errors, function( key, value ) {
console.log(key);
console.log(value);
if(key.length > 0) {
var $error = $('td.' + key);
$error.removeClass('hidden');
$error.addClass('visible');
$error.html(value);
}
});
} else {
console.log('======================================== error');
console.dir(jqXHR);
console.dir(textStatus);
console.dir(errorThrown);
}
}
});
return false;
}
});
Try the following code:
$('form.page').on('submit', function() {
var form = $(this);
var url = form.attr('action');
console.log(url);
console.log(form);
console.log('bier');
console.log(form.find('input').serialize());
console.log('/bier');
var wtf = new FormData(form);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'json',
data: form.serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data, textStatus, jqXHR) {
console.log('success');
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
var data = $.parseJSON(jqXHR.responseText);
console.log(data);
if (data.errors) {
console.log(data.errors);
$.each( data.errors, function( key, value ) {
console.log(key);
console.log(value);
if(key.length > 0) {
var $error = $('td.' + key);
$error.removeClass('hidden');
$error.addClass('visible');
$error.html(value);
}
});
} else {
console.log('======================================== error');
console.dir(jqXHR);
console.dir(textStatus);
console.dir(errorThrown);
}
}
});
return false;
});
This is the result: [{"apn":"173-76-001"}]
From this code (php):
<?php
require_once('../config.php');
if(isset($_GET['parcel_id'])) {
$db = new ezSQL_mysql(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$data = $db->get_results("select apn from parcels where parcel_id=" . $_GET['parcel_id']);
if($data != null) echo json_encode($data);
//if ($data != null) echo $data;
}
?>
jquery:
$('#searchTable tr').click(function(){
var parcel_id = $(this).attr('id');
alert(parcel_id);
$.ajax({
url: "classes/get-apn.php?id=" + parcel_id,
//timeout: 30000,
type: "GET",
error: function(SMLHttpRequest, textStatus, errorThrown){
alert("An error has occurred making the request: " + errorThrown);
},
success: function(data){
//do stuff here on success
alert(data);
$('#ParcelNumber').val(data);
}
});
});
How do I get the value of apn (173-76-001) into a label??
Im new at all this so thanks for your help in advance!!! :)
EDIT: So I tried the response below but it didn't work. I was told I need to parse using jQuery.parsJSON but it's not working either. I'm so confused. Here's my updated jQuery code:
$('#searchTable tr').click(function(){
var parcel_id = $(this).attr('id');
$('#ParcelId').html(parcel_id);
$.ajax({
url: "classes/get-apn.php?id=" + parcel_id,
//timeout: 30000,
type: "GET",
data: { parcel_id : parcel_id },
dataType: 'json',
error: function(SMLHttpRequest, textStatus, errorThrown){
alert("An error has occurred making the request: " + errorThrown);
},
success: function(data){
//do stuff here on success
var result = $.parseJSON(data);
alert(result.apn);
}
});
});
You perform the ajax request to the server. Server queries the DB and formats output as json. Ajax request hereby succeeded and the following line of code sets the label’s value:
$('#ParcelNumber').val(data);
Label ID here is ParcelNumber. To get the value you probably need to:
$('#ParcelNumber').val(data[0]["apn"]);
Whether ParcelNumber is not “valued” control (e.g. not an input but static div), use .html method:
$('#ParcelNumber').html(data[0]["apn"]);
I've got this script:
<script>
var request;
$("#foo").click(function(event){
request = $.ajax({
url: "/votesHandler.php",
type: "post",
data: "true"
});
request.done(function (response, textStatus, jqXHR){
alert("Voted!");
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert(
"Oops, something went wrong"
);
});
request.always(function () {
alert("Done.");
});
</script>
And what I'm trying to do is send "true" to the server when the #foo element is clicked. I've used AJAX only a few times before and each time it was with forms. The problem is that I need to receive this POST request in PHP (with $_POST['foo']) but this time the input is not the name of a text input. How do I send data into $_POST without a form?
You can specify the key of data when you send to your url.
$.ajax({
data: {foo: 'true'}
});
To retrieve it use
$_POST['foo']
Send it as:
data: 'foo_clicked=1',
or
data: 'foo_clicked=' + somevarname,
On the PHP side:
$recd = $_POST['foo_clicked'];
if ($recd == 1) {
//do what you need to do
}
try this:
$("#form").submit(function (e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
console.log(formURL); //your form action
$.ajax({
url: formURL,
type: "POST",
data: postData,
beforeSend: function () {
//do
},
success: function (data, textStatus, jqXHR) {
console.log('success data');
//whatever
},
error: function (jqXHR, textStatus, errorThrown) {
//if fails
console.log('fail');
}
});
e.preventDefault(); //STOP default action
});
<script type="text/javascript">
function checkQuery()
{
var val = form1.proDown.options[form1.proDown.options.selectedIndex].value;
var txt = form1.proDown.options[form1.proDown.options.selectedIndex].text;
//alert(val+' | '+txt);
<?php $_SESSION['value1']= ?> = txt; <?php ; ?>
}
</script>
I have this code and it does not Work?
Any One have solution for accessing javascript variable into $_SESSION[].
I think you should use xhr(Ajax) to store your data into php session. Following is a simple example to do this
jQuery.ajax({
url: 'storesession.php',
type: 'POST',
data: {
txt: txt,
},
dataType : 'json',
success: function(data, textStatus, xhr) {
console.log(data); // do with data e.g success message
},
error: function(xhr, textStatus, errorThrown) {
console.log(textStatus.reponseText);
}
});
storesession.php
$_SESSION['value1'] = $_POST['txt'];
I have a problem:
I have a JS function which sending data to php script, then PHP script returning JSON data from database QUERY and I want to get values returned from PHP script.
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
"rodzaj_konta": jQuery('#rodzaj_konta').val(),
"miejscowosc": jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somescript.php?action=results',
type: 'GET',
data: myData,
dataType: 'json',
beforeSend: function() {
jQuery('#loading').html('<p>loading...</p><img src="loading.gif" />'); //Loading image during the Ajax Request
},
error: function(xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
}
});
return false;
});
//-->
</script>
The PHP script returning data in proper format using:
header('Content-Type: application/json');
echo json_encode($data);
When I'm trying to alert(data), I get always a null.
How to get this returned JSON data ?
EDITED:
It's strange, because I have changed sending method to POST.
PHP returning JSON:
[{"nazwa":"Test","nazwa_firmy":"Testowa","ulica":null,"numer_domy":"2A","numer_mieszkania":"11","kod_pocztowy":"00-189","miejscowosc":"Warszawa","telefon":"213-123-132","nip":"112-312-31-31","regon":"231232133","adres_www":"http:\/\/www.gogl.epl","rodzaj_uzytkownika":"serwis"}]
But my JQUERY AJAX Script still returning null.
So my script now looks like this:
<script type="text/javascript">
<!--
jQuery('#wysz2').submit(function() {
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
jQuery.ajax({
url: 'http://somedomain.com/skrypt.php?action=wyniki_wyszukiwania',
type: 'GET',
data: myData,
dataType: 'json',
contentType: "application/json; charset=utf-8",
jsonp: "jsoncallback",
beforeSend: function() {
jQuery('#loading').html('<p>ładowanie...</p><img src="loading.gif" />');//Loading image during the Ajax Request
},
error: function (xhr, textStatus, errorThrown) {
alert("Error: " + (errorThrown ? errorThrown : xhr.status));
},
success: function (data) {
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
//-->
</script>
Any ideas ?
you are constructing your variables while sending in a wrong way semicoluns for object names is not there according to definitions
try this
var myData = {
rodzaj_konta: jQuery('#rodzaj_konta').val(),
miejscowosc: jQuery('#miejscowosc').val()
};
and while alerting your json data try
alert(JSON.stringify(your_json_obj));
Try to alert the object of the result...
Means if json in the format {"responseCode":"001","responseMsg":"success"}
Then alert data.responseCode
In success of your ajax function try something like this
var objParams1 = $.parseJSON(data);
console.log(objParams1);
alert(objParams1.Testowa)