I have two checkboxes with some values like this:
<label for="hotel_boutique"><input id="hotel_boutique" name="hotel_boutique" value="test" type=checkbox />test</label><br />
3
and I get these values with an Ajax call like this:
<script>
jQuery("input[type='checkbox']").change(function(){
if (jQuery('input#hotel_boutique').is(':checked')) {
var hotel_boutique = jQuery("#hotel_boutique").map(function () {return this.value;}).get();
}else{
var hotel_boutique = 'NULL';
}
if (jQuery('input#hotel_stars').is(':checked')) {
var hotel_stars = jQuery("#hotel_stars").map(function () {return this.value;}).get();
}else{
var hotel_stars = 'NULL';
}
var data = 'hotel_boutique="'+hotel_boutique+'"&hotel_stars="'+hotel_stars+'"';
jQuery.ajax({
url: "processAjax.php",
type: "GET",
data: data,
cache: false,
beforeSend: function() {
jQuery("#loading").show();
},
success: function(data, textStatus, XMLHttpRequest){
jQuery("#content").html('');
jQuery("#content").append(data);
jQuery("#loading").hide();
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
</script>
Now when I echo the variables in the server side (PHP) it displays:
"test"
Who and why are the " added? And how can I remove them?
I have already tried the PHP function preg_replace and other stuff.
please need your help...
You can use an object instead of string like
var data = {
hotel_boutique: hotel_boutique,
hotel_stars: hotel_stars
};
The problem is the " in the data string, you can also try
var data = 'hotel_boutique='+hotel_boutique+'&hotel_stars='+hotel_stars;
The overall code can be simplified as
jQuery("input[type='checkbox']").change(function () {
var data = {
hotel_boutique: $('#hotel_boutique:checked').val()||'NULL',
hotel_stars: $('#hotel_stars:checked').val()||'NULL'
};
jQuery.ajax({
url: "processAjax.php",
type: "GET",
data: data,
cache: false,
beforeSend: function () {
jQuery("#loading").show();
},
success: function (data, textStatus, XMLHttpRequest) {
jQuery("#content").html(data);
jQuery("#loading").hide();
},
error: function (MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
you need to pass key-value pair:
data: {hotel_boutique: hotel_boutique,hotel_stars: hotel_stars},
In this call:
jQuery.ajax({
data: data, // change here
});
it should be :
jQuery.ajax({
url: "processAjax.php",
type: "GET",
data: {
hotel_boutique: hotel_boutique,
hotel_stars : hotel_stars
},
cache: false,
beforeSend: function() {
jQuery("#loading").show();
},
success: function(data, textStatus, XMLHttpRequest){
jQuery("#content").html('');
jQuery("#content").append(data);
jQuery("#loading").hide();
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(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;
});
i'm using ajax in my codeigniter project but whenever i send data i get error and the response will be 'Undefined'.
i built the simplest code i've ever imagine but nothing works.
would you please tell me where is the wrong ??
<script type="text/javascript">
$(document).ready(function() {
var content = "test";
var datastring = 'content='+ content;
jQuery.ajax({
type:"POST",
url:"<?php echo site_url('test/test'); ?>",
data: datastring,
dataType: "html",
async: false,
success: function(data) { alert("succsess"); },
error: function(ts) { alert(ts.responseText); },
onComplete: function(data) {alert(data); }
});
});
</script>
and my codeigniter code is :
function test() {
echo $this->input->post('content');
}
ErrorText is the last parameter of error callback.
error: function(xhr, status, errorText) {
alert(errorText);
}
You should use complete in the place of oncomplete. The re-written code will be
<script type="text/javascript">
$(document).ready(function() {
var content = "test";
var datastring = 'content='+ content;
jQuery.ajax({
type:"POST",
url:"<?php echo site_url('test/test'); ?>",
data: datastring,
dataType: "html",
async: false,
success: function(data) { alert("succsess"); },
error: function(ts) { alert(ts.responseText); },
complete: function(data) {alert(data); }
});
});
</script>
I have php-script, firing with jquery ajax function. Somthing like this:
$("a.test").click (function () {
var new_id = $(this).attr("new_id");
$.ajax({
url: 'test.php',
type: "POST",
cache: false,
async: true,
data: ({
new_id : new_id
}),
success: function (data) {
alert (data);
},
error: function(){
alert('error');
}
});
return false;
});
Now, a have some errors in test.php, but I can't see them. Sript just runs and I have no feedback, only error alert (alert ('error')).
How can I get back errors, that I have in test.php to handle them?
If you echo the errors in test.php, you can simply do:
$.ajax({
url: 'test.php',
type: "POST",
cache: false,
async: true,
data: ({
new_id : new_id
}),
success: function (data) {
alert (data);
},
error: function(data){
alert('error:'+data);
}
});
return false;
});
Edit:
I usually do something like this. In test.php if you get an error, create an array with your error info and echo it json encoded:
$message=array('error' => 1,'message' => '<div class="alert alert-danger" role="alert">' . $login['message'] . '</div>' );
echo json_encode($message);
Now in your jquery you can retrive the error by:
success: function (data) {
alert (data);
},
error: function(data){
var obj = JSON.parse(data);
alert(obj.message);
}
When you have it in array like this you dont even need error: function(data) anymore, since you can simply:
success: function (data) {
var obj = JSON.parse(data);
if (obj.error) {
// do something
alert (obj.message);
}else{
// do something else
}
},
On test.php you could show errors using the code explained here: https://stackoverflow.com/a/21429652/6525724
And then on this page instead of alert('error') you could use alert(data).
Try this
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
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
});
I have a php function that get some xml information to be handled, but my problem is to pass a parameter to the function in addition to the data returned from the ajax :
$.ajax({
type: "POST",
url: 'proxy.php',
data:{country:'home'},
dataType: "xml",
success: function(data)
{
alert(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);
}
});
I want to pass parameter with the data .
I know that I could do it like the following:
$.ajax({
type: "POST",
url: 'proxy.php',
data:{country:'home'},
dataType: "xml",
success: function do_it(parameter)
});
function do_it(parameter)
{
return function(data)
{
alert(parameter);
alert(data);
}
}
I do not want to use this way I want to pass the parameter as the first code is showing.
Is it possible?
You can use the context option to $.ajax. This will then be available as this in the callback.
$.ajax({
type: "POST",
url: 'proxy.php',
data:{country:'home'},
dataType: "xml",
context: parameter,
success: function(data)
{
alert(data);
alert(this);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);
}
});
If your parameter is not affected by the AJAX call, simply define it in the same scope as the call and then access it from the success function. For example:
var parameter = 'some value';
$.ajax({
type: 'post',
url: 'proxy.php',
data: {country: 'home'},
dataType: 'xml',
success: function (data) {
alert(parameter);
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);
}
});
This works because parameter is in an outer scope and thus accessible by the success function.