Ajax parameters passed return undefined - php

I am posting an Ajax call to a PHP function but all the data passed is "UNDEFINED". When I debugged the JQuery, the value seems work. The undefined is at server side. PHP side.
$('.js-checkout-shipping-submit').on('click', function(e) {
$.ajax({
// Change the URL to the right one
url: 'index.php?route=checkout/checkout/updateShippingAddress',
type: 'post',
dataType: 'json',
data: 'firstName:' + $(' .js-checkout-firstName').val() +
',lastName:' + $('.js-checkout-lastName').val() +
',address:' + $('.js-checkout-address').val() +
',zipcode:' + $('.js-checkout-zipcode').val() ,
success: function(data) {
if(data['status'] === "pass"){
console.log("success");
}
if(data['status'] === "fail") {
console.log("fail");
}
},
error: function(data) {
}
});
e.preventDefault();
});
public function updateShippingAddress(){
$firstName=$this->request->post['firstName'];
$lastName=$this->request->post['lastName'];
$address=$this->request->post['address'];
$zipCode=$this->request->post['zipcode'];
}

You are posting the JSON object as string, please try this
data: { // making the data to become object
firstName : $('.js-checkout-firstName').val(),
lastName : $('.js-checkout-lastName').val(),
address : $('.js-checkout-address').val(),
zipcode : $('.js-checkout-zipcode').val()
},
success: function(data) {
...
If you are getting undefined as value of post params, maybe there is jQuery selector problem.
Try to log $('.js-checkout-firstName').val() and see what you get and make shre an Input is present with class .js-checkout-firstName

You have to pass your request parameter in json format for ajax.
so your data parameter value is be like,
data: {'firstName' : $('.js-checkout-firstName').val(),'lastName' : $('.js-checkout-lastName').val(),'address' : $('.js-checkout-address').val(),'zipcode' : $('.js-checkout-zipcode').val()},
success: function(data) {

Related

Read data from mysql php jquery ajax

I need to read data from my web page with jquery + ajax
This is my function:
public function getvalueshahr()
{
if($_POST['ostan']!=0){
$db= JFactory::getDbo();
$query=$db->getQuery(TRUE);
$query->select('id,title')->from('#__categories')->
where($db->quoteName('parent_id').'='.$db->quote($_POST['ostan']));
$db->setQuery($query);
$res=$db->loadObjectList();
echo $db->getErrorMsg();
echo json_encode($res);}
}
I can read data with c# like this:
But my ajax method is not working. Here is the method:
$.ajax({
type: "POST",
url: "www.mysite.net/index.php?task=shahrestan.getvalueshahr",
data: "{ostan=77}",
dataType: "json",
success: function (result)
{
var d = $.parseJSON(result);
$.each(d, function (i, field)
{
$("#output").append("id: " + field.id + " title: " +
field.title+"br/>");
});
},
error: function (e)
{
alert("error:" + e.responseText);
}
});
The method returns nothing.
You're sending a string instead of an object in your ajax-request. Try changing :
data: "{ostan=77}"
to
data: { ostan: 77 }
And you should set the content type before echoing the results in PHP:
header('Content-Type: application/json');
echo json_encode($res);
Now you don't need $.parseJSON in the JS-code. You will get a json-object straight away.
First of all you send a wrong data to the server. You have to rewrite part of your code like this:
data: {ostan: 77},
or
data: "ostan=77",
The second problem is you get a result as a json object on the success method, but you try to parse it again to the json object. So remove this line from your code:
var d = $.parseJSON(result);
Finally your ajax function should looks like this:
$.ajax({
type: "POST",
url: "www.mysite.net/index.php?task=shahrestan.getvalueshahr",
data: {ostan: 77},
dataType: "json",
success: function (result)
{
$.each(result, function (i, field)
{
$("#output").append("id: " + field.id + " title: " +
field.title+"br/>");
});
},
error: function (e)
{
alert("error:" + e.responseText);
}
});
If you are loading data from you mysql-database you eventually have to convert these data because it is not stored as utf-8 converted. This piece of code convert given object to UTF-8: mb_convert_encoding(database-entry,'UTF-8');

Send variable to PHP using AJAX

I've got a variable that I want to send to my PHP code that is on top of the code but I keep getting an error and undefined. dTotaal is the variable name and it contains a number. All this code is in the same page, so i am posting to the same page.
$('#emailVerzenden').click(function() {
$.ajax({
url: "content.php",
type: "post",
data: ({
totaal: dTotaal
}),
success: function(msg) {
alert('Data saved: ' + msg);
},
error: function(error) {
alert("couldnt be sent " + error);
}
});
On top of my page I've got this code. I'm not sure if it's correct, I am new at this.
if(isset($_POST['emailVerzenden']))
{
$totaal = $_POST['totaal'];
var_dump($totaal);
}
What I wanted was to put the value of the totaal data in $totaal but that is not working. The data is not being sent. I keep getting the error alert().
In your PHP code, you are checking the presence of a variable to use another. For me it should be:
if(isset($_POST['totaal']))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
You are on right track but seperate PHP codes with jQuery codes then you will have full control of processing data asynchronously.
index.php
$('#emailVerzenden').click(function()
{
$.ajax
({
url: "content.php",
type: "post",
data:{totaal: dTotaal},
success: function(msg)
{
alert('Data saved: ' + msg);
},
error: function(error)
{
alert("couldnt be sent ".error);
}
});
And in your php file first check whether $_POST data is set
content.php
if(isset($_POST))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
Mention your data which you wanna send in html & give it an ID.
<div id="total"> HERE COMES THE VARIABLE YOU WISH TO SEND </div>
Then pick up the data in that <div> by its ID document.getElementById('total').value like below:
var total=document.getElementById('total').value;
<script> var total=document.getElementById('total').value;
$.post('content.php',
{'total':total},
function(response){
if(response == 'YES'){}
});
</script>
Hope this will resolve your problem. Good Luck!
Kind of look like i didnt use preventDefault() thats why it wasnt working.
$('#emailVerzenden').click(function(e)
{
cms=$('#sCms').val();
templates= $('#templates').val();
onderdelen = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
email = $('#email').val();
e.preventDefault();
$.ajax
({
type: "POST",
url:"test.php",
data:{postEmail : email,postOnderdelen : onderdelen,postCms : cms,postTotaal : postTotaal, postTemplates : templates},
success: function(rs)
{
alert("Data saved:" + rs);
},
error: function(error)
{
alert("couldnt be sent" + error);
}
});
e.preventDefault();
});

JQuery returning undefined from PHP JSON string

I am trying this JQuery code:
val = $(this).val();
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "?getCustomer=1&sequence="+val+"",
data: data,
success: function(data) {
alert(data["sequence"]);
}
});
but the alert is returning undefined
if i check the URL (?getCustomer=1&sequence=4) i get this returned:
[{"sequence":"53"}]
so the sequence value is definately the
this is what shows in the console:
[Object]0: Objectsequence: "112"__proto__: Objectlength: 1__proto__: Array[0]concat: concat()constructor: Array()copyWithin: copyWithin()entries: entries()every: every()fill: fill()filter: filter()find: find()findIndex: findIndex()forEach: forEach()indexOf: indexOf()join: join()keys: keys()lastIndexOf: lastIndexOf()length: 0map: map()pop: pop()push: push()reduce: reduce()reduceRight: reduceRight()reverse: reverse()shift: shift()slice: slice()some: some()sort: sort()splice: splice()toLocaleString: toLocaleString()toString: toString()unshift: unshift()Symbol(Symbol.iterator): values()Symbol(Symbol.unscopables): Object__proto__: Object
You misunderstood your json. Change
alert(data["sequence"]);
With
alert(data[0]["sequence"]);
or better
alert(data[0].sequence );
[{"sequence":"53"}] is an array, the first element of which is an object with a sequence member. You need to alert(data[0]['sequence']).

jQuery AJAX can't work with JSON response

I have a JSON response from my php file like:
[
{"id":"1"},
{"archiveitem":"<small>26.06.2015 12:25<\/small><br \/><span class=\"label label-default\">Bug<\/span> has been submitted by Admin"}
]
And try to fetch this response into a div after button was clicked, however firebug is telling me the message from the error-handler. I can't figure out the problem?
$('#loadarchive').click(function(){
$.ajax({
type: 'post',
url: '/src/php/LoadAdminDashboardArchive.php',
dataType: 'json',
data: {
action : 'getArchive'
},
success: function(results) {
var archiveelements = JSON.parse(results);
console.log(results);
$.each(archiveelements, function(){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
});
},
error: function(){
console.log('Cannot retrieve data.');
}
});
});
I tried to run your Code and I get
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
By defining dataType: 'json' your result is parsed already as an Array. So you can do something like:
success: function (results) {
if (results["head"]["foo"] != 0) {
// do something
} else if (results["head"]["bar"] == 1) {
// do something
}
}
this works on my computer:
$.ajax({
type: 'post',
url: '/src/php/LoadAdminDashboardArchive.php',
dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
console.log(results);
$.each(results, function(){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
});
},
error: function(){
console.log('Cannot retrieve data.');
}
});
You can get more information from the console if you dive into it a bit more. Or by logging these two parameters:
error: function(xhr, mssg) {
console.log(xhr, mssg);
}
First
your response is not correct,Correct response should look like this
[{
"id":"1",
"archiveitem":"<small>26.06.2015 12:25<\/small>
<br \/><span class=\"labellabel-default\">Bug<\/span> has been submitted by Admin"
},
{
...
}]
Second
You dont have to parse result ie.JSON.parse is not required since dataType:'json' will probably take care of json.
Finally your success method should look like this:
success: function(results) {
$.each(results, function(ind,el){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + el.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + el.archiveitem + '</div>');
});
},
As you are saying message from error-handler is showing.
That means AJAX is never sent to server because of incorrect URL or any other reason.
Use Firebug in Firefox and see the error in console tab.
Also I see your code
dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
var archiveelements = JSON.parse(results);
}
Do not use JSON.parse(results) because you have already written dataType: 'json', and any type of response is parsed automatically.
I was able to get it working and the problem was quite simple...
I forgot to paste the "button" - source code that initiated the ajax request. It was an Input of type "submit" and therefore the page reloaded by default after the response was retrieved successfully... so e.preventDefault(); was the way to go.
Thanks to all of you.

JQuery AJAX - Not sending with data?

I'm building a chatroom that sends messages via AJAX. Whenever I hit enter, with the data: parameter, it returns an error, but if I remove data:, it doesn't do anything. This is very puzzling, and I'm wondering what I'm doing wrong. Here is what I have:
$("#form").bind("keypress", function(e) {
if (e.keyCode == 13) {
$.ajax({
type: 'POST',
url: "send-message.php",
data: "message="+$("#message").val()+"&user="+$("#user").val()+"&room="+$("#room").val(),
success: $("#message").val(""),
error: $("#message").val("FAIL"),
});
return false;
}
});
I use PHP in my AJAX call, so I don't know if that is causing the problem?
Try this:
...
$.ajax({
type: 'POST',
url: "send-message.php",
data: {message: $("#message").val(), user: $("#user").val(), room: $("#room").val()},
success: function() { $("#message").val(""); },
error: function() { $("#message").val("FAIL"); }
});
...
In the above code:
a) data sent as JSON - this will make sure that any url encoding and escaping will be correctly performed by jQuery as needed
b) success and error options must be callback functions
I would do this just to check if it grabs all the data correct:
var data = {
message: $('#message').val(),
user: $('#user').val
};
console.log(data);
You need to change these lines:
success: $("#message").val(""),
error: $("#message").val("FAIL"),
to
success: function () { $("#message").val("") },
error: function () { $("#message").val("FAIL") // removed trailing comma
I wrapped your handlers in a function and removed the trailing comma.
You can pass an object into data, and jQuery takes care of transforming it into the correct form for the type of request you issue, in this case a POST:
$("#form").bind("keypress", function(e) {
if (e.keyCode == 13) {
$.ajax({
type: 'POST',
url: "send-message.php",
data: {
message: $("#message").val(),
user: $("#user").val(),
room: $("#room").val()
},
success: function () {
$("#message").val("");
},
error: function () {
$("#message").val("FAIL");
},
});
return false;
}
});
Also, error and success are callbacks, so you need to provide a function, not a string if you want it called. Fixed it for you.
If you want to pass your data in POST you should use the javascript key:value format (or JSON format).
Input the following in
data: {"message": $("#message").val(),"var2":variable}
and a hint
...
data: $("#form").serialize();
...

Categories