Been getting a «parsererror» from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.
My project is in MVC3 and I’m using jQuery 1.5
I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.
Dropdown: (this loads the «Views» from the list in the Viewbag and firing the event works fine)
@{
var viewHtmls = new Dictionary<string, object>();
viewHtmls.Add("data-bind", "value: ViewID");
viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)
Javascript:
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'json',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
The above code successfully calls the MVC method and returns:
[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
{"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]
But jquery fires the error event for the $.ajax() method saying «parsererror».
when i try to get JSON from http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json with:
(jQuery 1.6.2)
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function (result) {
alert("SUCCESS!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
alert(xhr.responseText);
alert(xhr.status);
alert(thrownError);
}
});
I get: parsererror; 200; undefined; jquery162******************** was not called
but with the JSON from http://search.twitter.com/search.json?q=beethoven&callback=?&count=5 works fine.
Both are valid JSON formats. So what is this error about?
[UPDATE]
@3ngima, i have implemented this in asp.net, it works fine:
$.ajax({
type: "POST",
url: "WebService.asmx/GetTestData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
}
});
WebService.asmx:
[WebMethod]
public string GetTestData()
{
try
{
var req = System.Net.HttpWebRequest.Create("http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json");
using (var resp = req.GetResponse())
using (var stream = resp.GetResponseStream())
using (var reader = new System.IO.StreamReader(stream))
return reader.ReadToEnd();
}
catch (Exception) { return null; }
}
ndsmyter
6,4953 gold badges21 silver badges37 bronze badges
asked Jul 10, 2011 at 21:31
1
It’s because you’re telling jQuery that you’re expecting JSON-P, not JSON, back. But the return is JSON. JSON-P is horribly mis-named, named in a way that causes no end of confusion. It’s a convention for conveying data to a function via a script
tag. In contrast, JSON is a data format.
Example of JSON:
{"foo": "bar"}
Example of JSON-P:
yourCallback({"foo": "bar"});
JSON-P works because JSON is a subset of JavaScript literal notation. JSON-P is nothing more than a promise that if you tell the service you’re calling what function name to call back (usually by putting a callback
parameter in the request), the response will be in the form of functionname(data)
, where data
will be «JSON» (or more usually, a JavaScript literal, which may not be the quite the same thing). You’re meant to use a JSON-P URL in a script
tag’s src
(which jQuery does for you), to get around the Same Origin Policy which prevents ajax requests from requesting data from origins other than the document they originate in (unless the server supports CORS and your browser does as well).
answered Jul 10, 2011 at 21:34
T.J. CrowderT.J. Crowder
1.0m184 gold badges1874 silver badges1836 bronze badges
3
in case the server does not support the cross domain
request you can:
- create a server side proxy
- do ajax request to your proxy which in turn will get
json
from the service, and - return the response and then you can manipulate it …
in php you can do it like this
proxy.php contains the following code
<?php
if(isset($_POST['geturl']) and !empty($_POST['geturl'])) {
$data = file_get_contents($_POST['geturl']);
print $data;
}
?>
and you do the ajax request to you proxy like this
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
alert("abt to do ajax");
$.ajax({
url:'proxy.php',
type:"POST",
data:{geturl:'http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json'},
success:function(data){
alert("success");
alert(data);
}
});
});
});
</script>
tried and tested i get the json response back…
answered Jul 10, 2011 at 21:56
RafayRafay
30.8k5 gold badges67 silver badges101 bronze badges
At last i have found the solution. First of all, the webmethods in a webservice or page doesn’t work for me, it always returns xml, in local works fine but in a service provider like godaddy it doesn’t.
My solution was to create an .ahsx
, a handler in .net and wrap the content with the jquery callback function that pass the jsonp, and it works .
[System.Web.Script.Services.ScriptService]
public class HandlerExterno : IHttpHandler
{
string respuesta = string.Empty;
public void ProcessRequest ( HttpContext context )
{
string calls= context.Request.QueryString["callback"].ToString();
respuesta = ObtenerRespuesta();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write( calls +"("+ respuesta +")");
}
public bool IsReusable
{
get
{
return false;
}
}
[System.Web.Services.WebMethod]
private string ObtenerRespuesta ()
{
System.Web.Script.Serialization.JavaScriptSerializer j = new System.Web.Script.Serialization.JavaScriptSerializer();
Employee[] e = new Employee[2];
e[0] = new Employee();
e[0].Name = "Ajay Singh";
e[0].Company = "Birlasoft Ltd.";
e[0].Address = "LosAngeles California";
e[0].Phone = "1204675";
e[0].Country = "US";
e[1] = new Employee();
e[1].Name = "Ajay Singh";
e[1].Company = "Birlasoft Ltd.";
e[1].Address = "D-195 Sector Noida";
e[1].Phone = "1204675";
e[1].Country = "India";
respuesta = j.Serialize(e).ToString();
return respuesta;
}
}//class
public class Employee
{
public string Name
{
get;
set;
}
public string Company
{
get;
set;
}
public string Address
{
get;
set;
}
public string Phone
{
get;
set;
}
public string Country
{
get;
set;
}
}
And here is the call with jquery:
$(document).ready(function () {
$.ajax({
// url: "http://www.wookmark.com/api/json",
url: 'http://www.gjgsoftware.com/handlerexterno.ashx',
dataType: "jsonp",
success: function (data) {
alert(data[0].Name);
},
error: function (data, status, errorThrown) {
$('p').html(status + ">> " + errorThrown);
}
});
});
and works perfectly
Gabriel
Ivan Ferić
4,70511 gold badges37 silver badges47 bronze badges
answered Feb 2, 2013 at 15:58
Получил «parsererror» из jquery для запроса Ajax, я попытался изменить POST на GET, возвращая данные несколькими способами (создание классов и т.д.), но я не могу понять, что проблема есть.
Мой проект находится в MVC3, и я использую jQuery 1.5
У меня есть раскрывающийся список и в событии onchange я запускаю вызов, чтобы получить некоторые данные на основе того, что было выбрано.
Dropdown: (загружает «Views» из списка в Viewbag и срабатывает событие отлично)
@{
var viewHtmls = new Dictionary<string, object>();
viewHtmls.Add("data-bind", "value: ViewID");
viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)
JavaScript:
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'json',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
Вышеупомянутый код успешно вызывает метод MVC и возвращает:
[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
{"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]
Но jquery вызывает событие ошибки для метода $.ajax(), говорящего «parsererror».
See the answer by @david-east for the correct way to handle the issue
This answer is only relevant to a bug with jQuery 1.5 when using the file: protocol.
I had a similar problem recently when upgrading to jQuery 1.5. Despite getting a correct response the error handler fired. I resolved it by using the complete
event and then checking the status value. e.g:
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
handleError();
}
else {
var data = xhr.responseText;
//...
}
}
I recently encountered this problem and stumbled upon this question.
I resolved it with a much easier way.
Method One
You can either remove the dataType: 'json'
property from the object literal…
Method Two
Or you can do what @Sagiv was saying by returning your data as Json
.
The reason why this parsererror
message occurs is that when you simply return a string or another value, it is not really Json
, so the parser fails when parsing it.
So if you remove the dataType: json
property, it will not try to parse it as Json
.
With the other method if you make sure to return your data as Json
, the parser will know how to handle it properly.
You have specified the ajax call response dataType as:
‘json’
where as the actual ajax response is not a valid JSON and as a result the JSON parser is throwing an error.
The best approach that I would recommend is to change the dataType to:
‘text’
and within the success callback validate whether a valid JSON is being returned or not, and if JSON validation fails, alert it on the screen so that its obvious for what purpose the ajax call is actually failing. Have a look at this:
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'text',
data: {viewID: $("#view").val()},
success: function (data) {
try {
var output = JSON.parse(data);
alert(output);
} catch (e) {
alert("Output is not valid JSON: " + data);
}
}, error: function (request, error) {
alert("AJAX Call Error: " + error);
}
});
parsererror after jquery.ajax request with jsonp content type
When we make a cross domain call through jquery $.ajax method through jsonp request then often this error occurs ‘jQuery1510993527567155793_137593181353 was not called parsererror’ function name can vary as it is randomly generated by jquery.
request failed parsererror error jquery was not called
request failed parsererror error jquery was not called |
Explanation :
when you are using jsonp as datatype (making cross domain request) Jquery generate random function and append is to requested url as a querystring named callback (callback=?), you need to append response json data as a parameter of this function as given below —
url : http://www.dotnetbull.com/cross-domain-call.ashx?ref=jquery-jsonp-request
url call by ajax :
http://www.dotnetbull.com/cross-domain-call.ashx?ref=jquery-jsonp-request&callback=jQuery1510993527567155793_137593181353
Response data should look like this :
jQuery1510993527567155793_137593181353( { «result»: «success», «ref»: «jquery-jsonp-request» } )
string callback
= context.Request.QueryString[«callback»];
if (!string.IsNullOrEmpty(callback))
context.Response.Write(string.Format(«{0}({1});»,
callback, jc.Serialize(outputData)));
else
context.Response.Write(jc.Serialize(outputData));
jQuery ajax jsonp calls parse error after success
jQuery ajax jsonp calls parse error after success |
Popular posts from this blog
How to validate dropdownlist in JavaScript
In this article you will see how to put validation in dropdownlist by javascript, suppose first item value of dropdownlist is 0 and text is «-Select-» just like given below and we have to validate that at least one item is selected excluding default i.e «-Select-«.
Uploading large file in chunks in Asp.net Mvc c# from Javascript ajax
Often we have a requirement to upload files in Asp.net, Mvc c# application but when it comes to uploading larger file, we always think how to do it as uploading large file in one go have many challenges like UI responsiveness, If network fluctuate for a moment in between then uploading task get breaks and user have to upload it again etc.
Customize comment box in blogger
Now it is possible to customize your blogger comment box in simple way there no need to edit HTML of your blogger just through the adding some simple css to the blogger.
Regular expression for alphanumeric with space in asp.net c#
How to validate that string contains only alphanumeric value with some spacial character and with whitespace and how to validate that user can only input alphanumeric with given special character or space in a textbox (like name fields or remarks fields). In remarks fields we don’t want that user can enter anything, user can only able to enter alphanumeric with white space and some spacial character like -,. etc if you allow. Some of regular expression given below for validating alphanumeric value only, alphanumeric with whitspace only and alphanumeric with whitespace and some special characters.
How to handle click event of linkbutton inside gridview
Recently I have posted how to sort only current page of gridview , Scrollble gridview with fixed header through javascript , File upload control inside gridview during postback and now i am going to explain how to handle click event of linkbutton or any button type control inside gridview. We can handle click event of any button type control inside gridview by two way first is through event bubbling and second one is directly (in this type of event handling we need to access current girdviewrow container)
Hexus2 0 / 0 / 0 Регистрация: 11.05.2019 Сообщений: 8 |
||||||||
1 |
||||||||
13.12.2020, 19:42. Показов 1394. Ответов 12 Метки нет (Все метки)
Доброго времени суток, помогите разобраться, не могу понять в чем дело. dataType : ‘text’ — принимает
// ————————————————- userListAjaxTransfer.php —————————————————————
__________________
0 |
HotReboot 299 / 202 / 84 Регистрация: 22.04.2017 Сообщений: 1,002 |
||||
13.12.2020, 19:59 |
2 |
|||
Hexus2, Если вы указали
не нужно. Ответ уже приходит массивом.
1 |
dontknow 189 / 125 / 60 Регистрация: 18.05.2014 Сообщений: 264 |
||||||||||||
14.12.2020, 00:49 |
3 |
|||||||||||
нужно перед преобразованием строки в объект — вызовом метода json.parse сделать вывод этой строки, скорее всего увидеть что данные имеют некорректный формат — не json массив (из за вывода строк таблицы в php скрипте), поэтому метод json.parse не работает
чтобы решить проблему, нужно возвращать все данные из php скрипта одной json строкой
на стороне клиента получать из json объект, работать с его свойствами
0 |
Hexus2 0 / 0 / 0 Регистрация: 11.05.2019 Сообщений: 8 |
||||||||
14.12.2020, 17:27 [ТС] |
4 |
|||||||
Ваши замечания исправил.
================================================== ===========
0 |
0 / 0 / 0 Регистрация: 11.05.2019 Сообщений: 8 |
|
14.12.2020, 17:51 [ТС] |
5 |
Сообщение об ошибке в консоль. Миниатюры
0 |
dontknow 189 / 125 / 60 Регистрация: 18.05.2014 Сообщений: 264 |
||||
14.12.2020, 18:47 |
6 |
|||
так, ошибка json.parse потому что данные приходят уже в виде объекта
Если вы указали dataType:’json’ то это
Мне нужно именно ‘json’ получить. то есть получить json строку, а не объект из json?
0 |
Hexus2 0 / 0 / 0 Регистрация: 11.05.2019 Сообщений: 8 |
||||
14.12.2020, 19:14 [ТС] |
7 |
|||
Не могу получить ни объект, ни строку из объекта.
0 |
299 / 202 / 84 Регистрация: 22.04.2017 Сообщений: 1,002 |
|
14.12.2020, 19:20 |
8 |
Hexus2, Мне вообще не понятно зачем вам
0 |
Hexus2 0 / 0 / 0 Регистрация: 11.05.2019 Сообщений: 8 |
||||
14.12.2020, 20:07 [ТС] |
9 |
|||
мне нужно передать значение var ddd = respond.data в функцию в качестве параметра
Добавлено через 27 минут Причина, по которой parsererror это сообщение parsererror заключается в том, что когда вы просто возвращаете строку или другое значение, на самом деле это не Json, поэтому синтаксический анализатор дает сбой при его анализе.
0 |
HotReboot 299 / 202 / 84 Регистрация: 22.04.2017 Сообщений: 1,002 |
||||
14.12.2020, 20:08 |
10 |
|||
Hexus2, Ну и зачем вам то, что я написал выше? Умейте пользоваться отладкой. Удалите всё и посмотрит, что будет так
А то вы по-ходу стянули где-то и не поймёте, что делаете.
0 |
Hexus2 0 / 0 / 0 Регистрация: 11.05.2019 Сообщений: 8 |
||||
15.12.2020, 07:56 [ТС] |
11 |
|||
C dataType : ‘text’ — понятно, выводит все echo b die.
Конечно можно через dataType : ‘text’ решить задачу, но разобраться с dataType : ‘json’ хочу в чем причина. Миниатюры
0 |
HotReboot 299 / 202 / 84 Регистрация: 22.04.2017 Сообщений: 1,002 |
||||
15.12.2020, 11:06 |
12 |
|||
Hexus2, Да выкиньте вы этот error: function( jqXHR, status, errorThrown )
0 |
0 / 0 / 0 Регистрация: 11.05.2019 Сообщений: 8 |
|
15.12.2020, 11:07 [ТС] |
13 |
Все нашел причину ошибки. Спасибо за помощь!
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
15.12.2020, 11:07 |
Помогаю со студенческими работами здесь Необходимо отправить данные БД в формате json из PHP в JS (ajax)
Сделать ajax запрос и получить json ответ данные и отобразить их на той же страничке, но в блоке ниже Вернуть в Ajax-success $json из другого $json <?php Вернуть в Ajax-success $json из другого $json <?php JSON не принимает значения Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 13 |
Been getting a «parsererror» from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.
My project is in MVC3 and I’m using jQuery 1.5
I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.
Dropdown: (this loads the «Views» from the list in the Viewbag and firing the event works fine)
@{
var viewHtmls = new Dictionary<string, object>();
viewHtmls.Add("data-bind", "value: ViewID");
viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)
Javascript:
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'json',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
The above code successfully calls the MVC method and returns:
[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
{"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]
But jquery fires the error event for the $.ajax() method saying «parsererror».
Well, the value here is just the third argument given to the $.ajax
canonical error callback (see doc for error
in the $.ajax
doc page).
The reason it happened to have dumbed down values for aborts and timeouts is incidental to the fact there is no actual underlying error thrown in these situations. As a convenience, the third argument is thus set to the same value as the second.
Such is not the case for http errors (errorThrown
will be the http status text as provided by the xhr infrastructure) and parser errors (errorThrown
will be any exception thrown by converters). I see the documentation is lacking regarding the latter.
The fact you don’t have access to the second argument of the canonical error callback in the context of $.fn.ajaxError
(rather than the third one) is another of those wonderful design flaws that have been stacking on top of $.ajax
over the years.
Thankfully, since 1.5, you can easily get around this by using a prefilter:
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) { jqXHR.fail( function( jqXHR, textStatus, errorThrown ) { // I have access to textStatus AND errorThrown in here } ); } );
Remember, global ajax events are evil.
Получив «parsererror» от jquery для запроса Ajax, я попытался изменить POST на GET, возвращая данные несколькими разными способами (создание классов и т. Д.), Но я не могу понять, в чем проблема.
Мой проект находится в MVC3, и я использую jQuery 1.5. У меня есть раскрывающийся список, и в событии onchange я вызываю вызов, чтобы получить некоторые данные на основе того, что было выбрано.
Раскрывающийся список: (это загружает «Просмотры» из списка в панели просмотра, и запуск события работает нормально)
@{
var viewHtmls = new Dictionary<string, object>();
viewHtmls.Add("data-bind", "value: ViewID");
viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)
JavaScript:
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'json',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
Приведенный выше код успешно вызывает метод MVC и возвращает:
[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
{"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]
Но jquery запускает событие ошибки для метода $ .ajax (), говоря «parsererror».
672 votes
2 answers
Get the solution ↓↓↓
I’m doing an application web for a school and I’m stuck when trying to edit a student. I want the user to click in the row of and specific student and then open a form with his data.
I have to do an ajax request, so I can call my php function (the one which makes the query on my db) and load the data in the form. This is my jQuery code for the ajax request:
//When you click in the table students, in some element whose class is edit ...
$("#tblAlumnos").on("click", ".editar", function(event) {
var rowID = $(this).parents('tr').attr('id');
$.ajax({
type: 'POST',
url: '../ajax/',
data: {'table': 'alumnos', 'action': 'carga', 'ids': rowID},
dataType: 'json',
success: function(result) {
console.log(result.nombre);
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
alert(jqXHR.status);
alert(jqXHR);
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.n' + jqXHR.responseText);
}
}
});
});
The ajax request calls the method to get the data from my db:
function cargaAlumno($ids) {
require 'db.php';
$sql = "SELECT * FROM Alumnos WHERE ID=$ids";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
$row = $result -> fetch_assoc();
$nombre = $row['Nombre'];
$apellidos = $row['Apellidos'];
$telefono = $row['Telefono'];
$usuario = $row['Usuario'];
$contrasena = $row['Contrasena'];
$result = array();
$result["nombre"] = $nombre;
$result["apellidos"] = $apellidos;
$result["telefono"] = $telefono;
$result["usuario"] = $usuario;
$result["contrasena"] = $contrasena;
ChromePhp::warn($result);
ChromePhp::warn(json_encode($result));
echo json_encode($result);
}
}
This method has to return a JSON to the ajax request, but the success method is never reached because of the error: parsererror.
I’ve tried with dataType: ‘json’ (this is when I have the error) and without it (it thinks its html). I also have tried with and without contentType and in my php: header(‘Content-type: application/json; charset=utf-8’).
My json encoded looks like this:
{"nombre":"Susana","telefono":"56765336","usuario":"susa"}
I don’t know if I need some more methods because I’m doing it in WordPress or I have something wrong in my code.
Any help would be appreciated. Thank you in advance
2022-04-11
Write your answer
647
votes
Answer
Solution:
If you are doing it in WordPress, I’d use the built inwpdb
to handle the db connection and results. Like so:
function cargaAlumno() {
global $wpdb;
$ids = $_POST['ids'];
$sql = $wpdb->get_results(
$wpdb->prepare("
SELECT *
FROM Alumnos
WHERE id = '$ids'
")
);
echo json_encode($sql);
exit();
}
Also remember this goes into your themes functions.php file.
Remember to hook it into the wp_ajax hook:
add_action( 'wp_ajax_nopriv_cargaAlumno', 'cargaAlumno' );
add_action( 'wp_ajax_cargaAlumno', 'cargaAlumno' );
Then in your ajax:
$("#tblAlumnos").on("click", ".editar", function(event) {
var rowID = $(this).parents('tr').attr('id');
$.ajax({
type: 'POST',
url: ajaxurl, //this is a wordpress ajaxurl hook
data: {'table': 'alumnos', 'action': 'cargaAlumno', 'ids': rowID}, // You didn't use the correct action name, it's your function name i.e. cargaAlumno
//dataType: 'json', dont need this
success: function(result) {
//Parse the data
var obj = jQuery.parseJSON(result);
console.log(obj[0].nombre); // I'm guessing nombre is your db column name
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
alert(jqXHR.status);
alert(jqXHR);
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.n' + jqXHR.responseText);
}
}
});
});
This js file needs to be added into your theme to work in conjunction with the above reworked function()
Let me know if you need anymore help or have any other questions.
210
votes
Answer
Solution:
Not sure if you’re only providing particular lines of your code or this is the whole thing, anyway this is definitely NOT how you should handle AJAX requests in WordPress:
- You should use
wp_ajax_
for actions that requires authentication orwp_ajax_nopriv_
for ones that doesn’t - You should create an action for this function and send your request through
admin-ajax.php
usingadmin_url()
- You should definitely secure your requests by creating nonces using
wp_create_nonce()
and verify it usingwp_verify_nonce()
- You should restrict direct access to your AJAX file while checking
$_SERVER['HTTP_X_REQUESTED_WITH']
There’s no need to require db.php since you’re already working within functions.php and the db connection is already established.
Use the below method instead:
global $wpdb;
$query = "SELECT * FROM table_name";
$query_results = $wpdb->get_results($query);
To wrap it up, please follow the below structure:
Frontend (php file):
<?php
$ajax_nonce = wp_create_nonce("change_to_action_name");
$ajax_link = admin_url('admin-ajax.php?action=change_to_action_name&nonce=' . $ajax_nonce);
?>
<a class="do_ajax" href="#" data-ajax_link="<?php echo ajax_link; ?>" data-ajax_param="other_param">DO AJAX</a>
<input id="param" value="" />
Script File (js file):
$('.do_ajax').click(function () {
var ajax_link = $(this).attr('data-ajax_link');
var param = $(this).attr('data-ajax_param');
if (ajax_link && param) {
$.ajax({
type: "post",
dataType: "json",
url: ajax_link,
data: {
param: param,
},
success: function (response) {
if (response.type == "success") {
/*Get/updated returned vals from ajax*/
$('#param').val(response.new_param);
console.log('ajax was successful');
} else if (response.type == "error") {
console.log('ajax request had errors');
}else{
console.log('ajax request had errors');
}
}
});
} else {
console.log('ajax not sent');
}
});
Functions File (functions.php file):
add_action("wp_ajax_change_to_action_name", "change_to_action_name");
add_action("wp_ajax_nopriv_change_to_action_name", "change_to_action_name");
function change_to_action_name()
{
if (!wp_verify_nonce($_REQUEST['nonce'], "change_to_action_name")) {
exit("You think you are smart?");
}
$param = $_REQUEST['param'];
/*php actions goes here*/
$actions_success=0;
if($actions_success){
/*Query db and update vals here*/
$new_param = "new_val";
$result['new_param'] = $new_param;
$result['type'] = "success";
}else{
$result['type'] = "error";
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: " . $_SERVER["HTTP_REFERER"]);
}
die();
}
Your current code contains many security flaws, so it’s very recommended that you update it and use the above method.
Cheers!
Share solution ↓
Additional Information:
Date the issue was resolved:
2022-04-11
Link To Source
Link To Answer
People are also looking for solutions of the problem: mysqli::real_connect(): (hy000/2002): connection refused
Didn’t find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.