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
});
Related
I am trying to get ajax response. But my code does not show anything in alert. Here is my ajax code. my form id is contact_form and my submit button id is submit_btn
$(document).ready(function(){
$('#contact_form').on('submit', function(e){
var form= $("#contact_form").val();
$.ajax({
type : 'POST',
url : 'email.php',
data : form.serialize(),
dataType : 'json',
success: function (response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
//console.log(textStatus, errorThrown);
}
});
e.preventDefault();
});
});
my email.php
<?php
echo "ok";
?>
I think that your problem is because you are trying to use the serialize method in a wrong way.
The .serialize() method will handle all the fields that are inside the selected target form. In the original code, You've used the .val() method to take the values of the form, but this will not work because that method is intended to be used with a single form element and can't handle the whole form.
Change your code in this way:
$(document).ready(function(){
$('#contact_form').on('submit', function(e){
e.preventDefault();
var form = $("#contact_form");
$.ajax({
type : 'POST',
url : 'email.php',
data : form.serialize(),
success: function (response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
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);
}
})
});
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)
I am not sure why but the post to my external PHP file is not working. The post request is not being received by the PHP file as nothing is being outputted.
Here's my jQUery;
$.post("AJAX/get_track_info.php", { url: "uploads/19c9aa51c821952c81be46ca9b2e9056.mp3"}, function(info){
$('#loadInfo').html(info);
});
And in the PHP file is just a
$trackurl = $_POST['url'];
Try something more like this
$.ajax({
type: 'POST',
url: 'AJAX/get_track_info.php',
data: { url: "uploads/19c9aa51c821952c81be46ca9b2e9056.mp3" },
dataType: 'text',
success: function (data, textStatus, jqXHR) { },
error: function (data, textStatus, errorThrown) { }
});
Currently I have this, which works nicely - it's an email signup list which returns a successful response or error, as appropriate.
$.ajax({
type: "POST",
url: "mailing_list/mailing_list_add2.php",
data: dataString,
success: function(response) {
$('#emailform').html("<div id='display_block'></div>");
$('#display_block')
.hide()
.fadeIn(500, function() {
$('#display_block').html(response)
});
}
});
return false;
});
The form is in a div with ID "emailform" and the "display_block" is the response. What I need is for the response to automatically disappear after a short time and for the form to fade back in. I've tried a few things but nothing that has worked yet.
Any help on what to add to the above code would be appreciated.
Assuming your initial html is like,
<div id="emailform">
<form>
...
</form>
</div>
you can proceed like this,
.ajax({
type: "POST",
url: "mailing_list/mailing_list_add2.php",
data: dataString,
success: function(response) {
var backupHtml = $('#emailform').html();
$('#emailform').html("<div id='display_block'></div>");
$('#display_block')
.hide()
.html(response)
.fadeIn(500, function() {
$(this).fadeOut(5000,function(){
$('#emailform').html(backupHtml);
});
});
}
});
There is nothing inside display_block when you fade it in. Its just empty, I changed the code:
$.ajax({
type: "POST",
url: "mailing_list/mailing_list_add2.php",
data: dataString,
success: function(response) {
var backedup = $('#emailform').html(); // Take a snapshot of whats inside the emailform
$('#emailform').html("<div id='display_block'></div>");
$('#display_block')
.hide()
.html(response) // New line!
.fadeIn(500,function (){ // After we finsish the fadeIn
$('#emailform').hide().html(backedup).fadeIn(500); // Reset the old content and fade it in
});
}
});
return false;
});
I created a JSFiddle for you http://jsfiddle.net/XHkWr/1/
To do instead of all mumbo jumbo.
$('#emailform').html("<div id='display_block'></div>");
$('#display_block').hide().html(response).stop().fadeIn(500);
I would say, that this would be a correct solution:
$.ajax({
url: 'mailing_list/mailing_list_add2.php',
type: 'post',
data: dataString,
success: function(data, textStatus, jqXHR) {
var $emailForm = $('#emailform').html();
$('#emailform').html('<div id="display_block"></div>');
$('#emailform').hide().html(data).fadeIn(500).delay(3000).fadeOut(500, function() {
$('#emailform').html($emailForm);
});
return false;
},
error: function(jqXHR, textStatus, errorThrown) {
var $emailForm = $('#emailform').html();
$('#emailform').html('<div id="display_block"></div>');
$('#display_block').hide().html(textStatus).fadeIn(500).delay(3000).fadeOut(500, function() {
$('#emailform').html($emailForm);
});
return false;
}
});
Result here: http://jsfiddle.net/p9URt/2/